SlideShare a Scribd company logo
Dot Net Training
Learning .NET Attributes
Dot Net Training
Assemblies are the building blocks of .NET Framework ; they form the basic unit of
deployment, reuse, version control, reuse, activation scoping and security
permissions.
An assembly is a collection of types and resources that are created to work together
and form a functional and logical unit.
.NET assemblies are self-describing, i.e. information about an assembly is stored in
the assembly itself. This information is called Metadata.
.NET also allows you to put additional information in the metadata via Attributes.
Attributes are used in many places within the .NET framework.
This page discusses what attributes are, how to use inbuilt attributes and how to
customize attributes.
Dot Net Training
Define .NET Attributes
A .NET attribute is information that can be attached with a class, an assembly,
property, method and other members. An attribute bestows to the metadata about an
entity that is under consideration. An attribute is actually a class that is either inbuilt or
can be customized. Once created, an attribute can be applied to various targets
including the ones mentioned above.
For better understanding, let’s take this example:
[WebService]public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
5. public string HelloWorld()
{
return “Hello World”;
}
}
Dot Net Training
The above code depicts a class named WebService1 that contains a method:
HelloWorld(). Take note of the class and method declaration. The WebService1 class
is decorated with [WebService] and HelloWorld() is decorated with [WebMethod].
Both of them – [WebService] and [WebMethod] – are features. The [WebService]
attribute indicates that the target of the feature (WebService1 class) is a web service.
Similarly, the [WebMethod] feature indicates that the target under consideration
(HelloWorld() method) is a web called method. We are not going much into details of
these specific attributes, it is sufficient to know that they are inbuilt and bestow to the
metadata of the respective entities.
Two broad ways of classification of attributes are : inbuilt and custom. The inbuilt
features are given by .NET framework and are readily usable when required. Custom
attributes are developer created classes.
Dot Net Training
On observing a newly created project in Visual Studio, you will find a file named
AssemblyInfo.cs. This file constitute attributes that are applicable to the entire project
assembly.
For instance, consider the following AssemblyInfo.cs from an ASP.NET Web
Application
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.[assembly:
AssemblyTitle("CustomAttributeDemo")][assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomAttributeDemo")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
Dot Net Training
As you can see there are many attributes such as AssemblyTitle, AssemblyDescription
and AssemblyVersion. Since their target is the hidden assembly, they use [assembly:
<attribute_name>] syntax.
Information about the features can be obtained through reflection. Most of the inbuilt
attributes are handled by .NET framework internally but for custom features you may
need to create a mechanism to observe the metadata emitted by them.
Inbuilt Attributes
In this section you will use Data Annotation Attributes to prove model data. Nees to
start by creating a new ASP.NET MVC Web Application. Then add a class to the
Models folder and name it as Customer.
Dot Net Training
The Customer class contains two public properties and is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
5. using System.ComponentModel.DataAnnotations;
namespace CustomAttributesMVCDemo.Models
{
public class Customer
10. {
[Required]
public string CustomerID { get; set; }
[Required]
15. [StringLength(20,MinimumLength=5,ErrorMessage="Invalid company
name!")]
public string CompanyName { get; set; }
}
Dot Net Training
Take note of the above code. The Customer class comprise of two string properties –
CustomerID and CompanyName. Its important to note that these properties are
decorated with data annotation features residing in the
System.ComponentModel.DataAnnotations namespace.
The [Required] features points that the CustomerID property must be given some
value in order to consider it to be a valid model. Similarly, the CompanyName property
is designed with [Required] and [StringLength] attributes.
The [StringLength] feature is used to specify that the CompanyName should be a at
least five characters long and at max twenty characters long. An error message is also
specified in case the value given to the CompanyName property doesn’t meet the
criteria.
To note that [Required] and [StringLength] attributes are actually classes –
RequiredAttribute and StringLengthAttribute – defined in the
System.ComponentModel.DataAnnotations namespace.
Dot Net Training
Now, add the HomeController class to the Controllers folder and write the following
action methods:
public ActionResult Index()
{
return View();
}
5.
public ActionResult ProcessForm()
{
Customer obj = new Customer();
bool flag = TryUpdateModel(obj);
10. if(flag)
{
ViewBag.Message = “Customer data received successfully!”;
}
else
15. {
ViewBag.Message = “Customer data validation failed!”;
}
return View(“Index”);
}
Dot Net Training
The Index() action method simply returns the Index view. The Index.cshtml consists of
a simple <form> as given below:
<form action=”/home/processform” method=”post”>
<span>Customer ID : </span>
<input type=”text” name=”customerid” />
<span>Company Name : </span>
5. <input type=”text” name=”companyname” />
<input type=”submit” value=”Submit”/>
</form>
<strong>@ViewBag.Message</strong>
<strong>@Html.ValidationSummary()</strong>
The values entered in the customer ID text box and company name text box are
submitted to the ProcessForm() action method.
Dot Net Training
The ProcesssForm() action method uses TryUpdateModel() method to allot the
characteristics of the Customer model with the form field values. The
TryUpdateModel() method returns true if the model properties contain proven data as
per the condition given by the data annotation features, otherwise it returns false. The
model errors are displayed on the page using ValidationSummary() Html helper.
Then run the application and try submitting the form without entering Company Name
value. The following figure shows how the error message is shown:
Thus data notation attributes are used by ASP.NET MVC to do model validations.
Creating Custom Attributes
In the above example, some inbuilt attributes were used. This section will teach you to
create a custom attribute and then apply it. For the sake of this example let’s assume
that you have developed a class library that has some complex business processing.
You want that this class library should be consumed by only those applications that got
a valid license key given by you. You can devise a simple technique to accomplish this
task.
Dot Net Training
Let’s begin by creating a new class library project. Name the project
LicenseKeyAttributeLib. Modify the default class from the class library to resemble the
following code:
namespace LicenseKeyAttributeLib
{
[AttributeUsage(AttributeTargets.All)]
public class MyLicenseAttribute:Attribute
5. { public string Key { get; set; }
}
}
As you can see the MyLicenseAttribute class is created by taking it from the Attribute
base class is provided by the .NET framework. By convention all the attribute classes
end with “Attribute”. But while using these attributes you don’t need to write “Attribute”.
Thus MyLicenseAttribute class will be used as [MyLicense] on the target.
The MyLicenseAttribute class contains just one property – Key – that represents a
license key.
Dot Net Training
The MyLicenseAttribute itself is decorated with an inbuilt attribute – [AttributeUsage].
The [AttributeUsage] feature is used to set the target for the custom attribute being
created.
Now, add another class library to the same solution and name it ComplexClassLib.
The ComplexClassLib represents the class library doing some complex task and
consists of a class as shown below:
public class ComplexClass1
{
public string ComplexMethodRequiringKey()
{
5. //some code goes here
return “Hello World!”;
}
}
The ComplexMethodRequiringKey() method of the ComplexClass1 is supposed to be
doing some complex operation.
Dot Net Training
Applying Custom Attributes
Next need to add an ASP.NET Web Forms Application to the same solution.
Then use the ComplexMethodRequiringKey() inside the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
ComplexClassLib.ComplexClass1 obj = new ComplexClassLib.ComplexClass1();
Label1.Text = obj.ComplexMethodRequiringKey();
}
The return value from ComplexMethodRequiringKey() is assigned to a Label control.
Now it’s time to use the MyLicenseAttribute class that was created earlier. Open the
AssemblyInfo.cs file from the web application and add the following code to it:
using System.Reflection;
…
using LicenseKeyAttributeLib;
5. …
[assembly: MyLicense(Key = "4fe29aba")]
Dot Net Training
Summary
Attributes help you to add metadata to their target. The .NET framework though
provides several inbuilt attributes , there are chances to customize a few more. You
knew to use inbuilt data notation features to validate model data; create a custom
attribute and used it to design an assembly. A custom feature is a class usually
derived from the Attribute base class and members can be added to the custom
attribute class just like you can do for any other class.
If you are considering to take ASP.Net training then our CRB Tech .Net Training
center would be very helpful in fulfilling your aspirations. We update ourself with the
ongoing generation so you can learn ASP.Net with us.
Stay connected to this page of CRB Tech reviews for more technical up-gradation and
other resources.
For more information on .net do visit : http://crbtech.in/Dot-Net-Training
Thank You..!
Dot Net Training

More Related Content

What's hot

Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
Aashish Jain
 
Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language
Mahika Tutorials
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
NicheTech Com. Solutions Pvt. Ltd.
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developers
Sanjaya Prakash Pradhan
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
Sudarshan Dhondaley
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15
aminmesbahi
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
Eric Nelson
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
Ankit Desai
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
Sudarshan Dhondaley
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
aminmesbahi
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity FrameworkDoncho Minkov
 
Oracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new featuresOracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new features
Philip Stoyanov
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
C# Unit5 Notes
C# Unit5 NotesC# Unit5 Notes
C# Unit5 Notes
Sudarshan Dhondaley
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
NicheTech Com. Solutions Pvt. Ltd.
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
Muthuselvam RS
 

What's hot (20)

Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developers
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Oracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new featuresOracle Sql Developer Data Modeler 3 3 new features
Oracle Sql Developer Data Modeler 3 3 new features
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
C# Unit5 Notes
C# Unit5 NotesC# Unit5 Notes
C# Unit5 Notes
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Java Beans
Java BeansJava Beans
Java Beans
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 

Viewers also liked

Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
Rohit Vipin Mathews
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
Bình Trọng Án
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
Robert MacLean
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
LearnNowOnline
 
.Net Core
.Net Core.Net Core
.Net Core
Bertrand Le Roy
 
ASP.NET Core 1.0 Overview
ASP.NET Core 1.0 OverviewASP.NET Core 1.0 Overview
ASP.NET Core 1.0 Overview
Shahed Chowdhuri
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
Jm Ramos
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
Siraj Memon
 

Viewers also liked (12)

Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
 
Net remoting
Net remotingNet remoting
Net remoting
 
Session 6
Session 6Session 6
Session 6
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
 
Net remoting
Net remotingNet remoting
Net remoting
 
.Net Core
.Net Core.Net Core
.Net Core
 
ASP.NET Core 1.0 Overview
ASP.NET Core 1.0 OverviewASP.NET Core 1.0 Overview
ASP.NET Core 1.0 Overview
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
 

Similar to Learning .NET Attributes

Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
sonia merchant
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
jlshare
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
Mahmoud Ouf
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
Naveen Kumar Veligeti
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra
ijaprr_editor
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
kenatmxm
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Sony Suci
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
 

Similar to Learning .NET Attributes (20)

Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Entity framework1
Entity framework1Entity framework1
Entity framework1
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
 

More from Pooja Gaikwad

Building A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- IIBuilding A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- II
Pooja Gaikwad
 
How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?
Pooja Gaikwad
 
Forms authentication in asp dot net
Forms authentication in asp dot netForms authentication in asp dot net
Forms authentication in asp dot net
Pooja Gaikwad
 
Owin and katana overview
Owin and katana overviewOwin and katana overview
Owin and katana overview
Pooja Gaikwad
 
Top 15 asp dot net interview questions and answers
Top 15 asp dot net interview questions and answersTop 15 asp dot net interview questions and answers
Top 15 asp dot net interview questions and answers
Pooja Gaikwad
 
Dot Net Certification Course Pune
Dot Net Certification Course PuneDot Net Certification Course Pune
Dot Net Certification Course Pune
Pooja Gaikwad
 
An Overview ASP.NET vNEXT - CRB Tech
An Overview ASP.NET vNEXT - CRB TechAn Overview ASP.NET vNEXT - CRB Tech
An Overview ASP.NET vNEXT - CRB Tech
Pooja Gaikwad
 
Importance of msil in dot net
Importance of msil in dot netImportance of msil in dot net
Importance of msil in dot net
Pooja Gaikwad
 
A simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB TechA simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB Tech
Pooja Gaikwad
 
History of-silverlight-versions-and-its-features-CRB-Tech
History of-silverlight-versions-and-its-features-CRB-TechHistory of-silverlight-versions-and-its-features-CRB-Tech
History of-silverlight-versions-and-its-features-CRB-Tech
Pooja Gaikwad
 
Exploring MVVM, MVC, MVP Patterns - CRB Tech
Exploring MVVM, MVC, MVP Patterns - CRB TechExploring MVVM, MVC, MVP Patterns - CRB Tech
Exploring MVVM, MVC, MVP Patterns - CRB Tech
Pooja Gaikwad
 
.Net framework-garbage-collection
.Net framework-garbage-collection.Net framework-garbage-collection
.Net framework-garbage-collection
Pooja Gaikwad
 

More from Pooja Gaikwad (12)

Building A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- IIBuilding A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- II
 
How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?How To Optimize Asp.Net Application ?
How To Optimize Asp.Net Application ?
 
Forms authentication in asp dot net
Forms authentication in asp dot netForms authentication in asp dot net
Forms authentication in asp dot net
 
Owin and katana overview
Owin and katana overviewOwin and katana overview
Owin and katana overview
 
Top 15 asp dot net interview questions and answers
Top 15 asp dot net interview questions and answersTop 15 asp dot net interview questions and answers
Top 15 asp dot net interview questions and answers
 
Dot Net Certification Course Pune
Dot Net Certification Course PuneDot Net Certification Course Pune
Dot Net Certification Course Pune
 
An Overview ASP.NET vNEXT - CRB Tech
An Overview ASP.NET vNEXT - CRB TechAn Overview ASP.NET vNEXT - CRB Tech
An Overview ASP.NET vNEXT - CRB Tech
 
Importance of msil in dot net
Importance of msil in dot netImportance of msil in dot net
Importance of msil in dot net
 
A simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB TechA simplest way to reconstruct .Net Framework - CRB Tech
A simplest way to reconstruct .Net Framework - CRB Tech
 
History of-silverlight-versions-and-its-features-CRB-Tech
History of-silverlight-versions-and-its-features-CRB-TechHistory of-silverlight-versions-and-its-features-CRB-Tech
History of-silverlight-versions-and-its-features-CRB-Tech
 
Exploring MVVM, MVC, MVP Patterns - CRB Tech
Exploring MVVM, MVC, MVP Patterns - CRB TechExploring MVVM, MVC, MVP Patterns - CRB Tech
Exploring MVVM, MVC, MVP Patterns - CRB Tech
 
.Net framework-garbage-collection
.Net framework-garbage-collection.Net framework-garbage-collection
.Net framework-garbage-collection
 

Recently uploaded

Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 

Recently uploaded (20)

Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 

Learning .NET Attributes

  • 2. Dot Net Training Assemblies are the building blocks of .NET Framework ; they form the basic unit of deployment, reuse, version control, reuse, activation scoping and security permissions. An assembly is a collection of types and resources that are created to work together and form a functional and logical unit. .NET assemblies are self-describing, i.e. information about an assembly is stored in the assembly itself. This information is called Metadata. .NET also allows you to put additional information in the metadata via Attributes. Attributes are used in many places within the .NET framework. This page discusses what attributes are, how to use inbuilt attributes and how to customize attributes.
  • 3. Dot Net Training Define .NET Attributes A .NET attribute is information that can be attached with a class, an assembly, property, method and other members. An attribute bestows to the metadata about an entity that is under consideration. An attribute is actually a class that is either inbuilt or can be customized. Once created, an attribute can be applied to various targets including the ones mentioned above. For better understanding, let’s take this example: [WebService]public class WebService1 : System.Web.Services.WebService { [WebMethod] 5. public string HelloWorld() { return “Hello World”; } }
  • 4. Dot Net Training The above code depicts a class named WebService1 that contains a method: HelloWorld(). Take note of the class and method declaration. The WebService1 class is decorated with [WebService] and HelloWorld() is decorated with [WebMethod]. Both of them – [WebService] and [WebMethod] – are features. The [WebService] attribute indicates that the target of the feature (WebService1 class) is a web service. Similarly, the [WebMethod] feature indicates that the target under consideration (HelloWorld() method) is a web called method. We are not going much into details of these specific attributes, it is sufficient to know that they are inbuilt and bestow to the metadata of the respective entities. Two broad ways of classification of attributes are : inbuilt and custom. The inbuilt features are given by .NET framework and are readily usable when required. Custom attributes are developer created classes.
  • 5. Dot Net Training On observing a newly created project in Visual Studio, you will find a file named AssemblyInfo.cs. This file constitute attributes that are applicable to the entire project assembly. For instance, consider the following AssemblyInfo.cs from an ASP.NET Web Application // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly.[assembly: AssemblyTitle("CustomAttributeDemo")][assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomAttributeDemo")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
  • 6. Dot Net Training As you can see there are many attributes such as AssemblyTitle, AssemblyDescription and AssemblyVersion. Since their target is the hidden assembly, they use [assembly: <attribute_name>] syntax. Information about the features can be obtained through reflection. Most of the inbuilt attributes are handled by .NET framework internally but for custom features you may need to create a mechanism to observe the metadata emitted by them. Inbuilt Attributes In this section you will use Data Annotation Attributes to prove model data. Nees to start by creating a new ASP.NET MVC Web Application. Then add a class to the Models folder and name it as Customer.
  • 7. Dot Net Training The Customer class contains two public properties and is shown below: using System; using System.Collections.Generic; using System.Linq; using System.Web; 5. using System.ComponentModel.DataAnnotations; namespace CustomAttributesMVCDemo.Models { public class Customer 10. { [Required] public string CustomerID { get; set; } [Required] 15. [StringLength(20,MinimumLength=5,ErrorMessage="Invalid company name!")] public string CompanyName { get; set; } }
  • 8. Dot Net Training Take note of the above code. The Customer class comprise of two string properties – CustomerID and CompanyName. Its important to note that these properties are decorated with data annotation features residing in the System.ComponentModel.DataAnnotations namespace. The [Required] features points that the CustomerID property must be given some value in order to consider it to be a valid model. Similarly, the CompanyName property is designed with [Required] and [StringLength] attributes. The [StringLength] feature is used to specify that the CompanyName should be a at least five characters long and at max twenty characters long. An error message is also specified in case the value given to the CompanyName property doesn’t meet the criteria. To note that [Required] and [StringLength] attributes are actually classes – RequiredAttribute and StringLengthAttribute – defined in the System.ComponentModel.DataAnnotations namespace.
  • 9. Dot Net Training Now, add the HomeController class to the Controllers folder and write the following action methods: public ActionResult Index() { return View(); } 5. public ActionResult ProcessForm() { Customer obj = new Customer(); bool flag = TryUpdateModel(obj); 10. if(flag) { ViewBag.Message = “Customer data received successfully!”; } else 15. { ViewBag.Message = “Customer data validation failed!”; } return View(“Index”); }
  • 10. Dot Net Training The Index() action method simply returns the Index view. The Index.cshtml consists of a simple <form> as given below: <form action=”/home/processform” method=”post”> <span>Customer ID : </span> <input type=”text” name=”customerid” /> <span>Company Name : </span> 5. <input type=”text” name=”companyname” /> <input type=”submit” value=”Submit”/> </form> <strong>@ViewBag.Message</strong> <strong>@Html.ValidationSummary()</strong> The values entered in the customer ID text box and company name text box are submitted to the ProcessForm() action method.
  • 11. Dot Net Training The ProcesssForm() action method uses TryUpdateModel() method to allot the characteristics of the Customer model with the form field values. The TryUpdateModel() method returns true if the model properties contain proven data as per the condition given by the data annotation features, otherwise it returns false. The model errors are displayed on the page using ValidationSummary() Html helper. Then run the application and try submitting the form without entering Company Name value. The following figure shows how the error message is shown: Thus data notation attributes are used by ASP.NET MVC to do model validations. Creating Custom Attributes In the above example, some inbuilt attributes were used. This section will teach you to create a custom attribute and then apply it. For the sake of this example let’s assume that you have developed a class library that has some complex business processing. You want that this class library should be consumed by only those applications that got a valid license key given by you. You can devise a simple technique to accomplish this task.
  • 12. Dot Net Training Let’s begin by creating a new class library project. Name the project LicenseKeyAttributeLib. Modify the default class from the class library to resemble the following code: namespace LicenseKeyAttributeLib { [AttributeUsage(AttributeTargets.All)] public class MyLicenseAttribute:Attribute 5. { public string Key { get; set; } } } As you can see the MyLicenseAttribute class is created by taking it from the Attribute base class is provided by the .NET framework. By convention all the attribute classes end with “Attribute”. But while using these attributes you don’t need to write “Attribute”. Thus MyLicenseAttribute class will be used as [MyLicense] on the target. The MyLicenseAttribute class contains just one property – Key – that represents a license key.
  • 13. Dot Net Training The MyLicenseAttribute itself is decorated with an inbuilt attribute – [AttributeUsage]. The [AttributeUsage] feature is used to set the target for the custom attribute being created. Now, add another class library to the same solution and name it ComplexClassLib. The ComplexClassLib represents the class library doing some complex task and consists of a class as shown below: public class ComplexClass1 { public string ComplexMethodRequiringKey() { 5. //some code goes here return “Hello World!”; } } The ComplexMethodRequiringKey() method of the ComplexClass1 is supposed to be doing some complex operation.
  • 14. Dot Net Training Applying Custom Attributes Next need to add an ASP.NET Web Forms Application to the same solution. Then use the ComplexMethodRequiringKey() inside the Page_Load event handler: protected void Page_Load(object sender, EventArgs e) { ComplexClassLib.ComplexClass1 obj = new ComplexClassLib.ComplexClass1(); Label1.Text = obj.ComplexMethodRequiringKey(); } The return value from ComplexMethodRequiringKey() is assigned to a Label control. Now it’s time to use the MyLicenseAttribute class that was created earlier. Open the AssemblyInfo.cs file from the web application and add the following code to it: using System.Reflection; … using LicenseKeyAttributeLib; 5. … [assembly: MyLicense(Key = "4fe29aba")]
  • 15. Dot Net Training Summary Attributes help you to add metadata to their target. The .NET framework though provides several inbuilt attributes , there are chances to customize a few more. You knew to use inbuilt data notation features to validate model data; create a custom attribute and used it to design an assembly. A custom feature is a class usually derived from the Attribute base class and members can be added to the custom attribute class just like you can do for any other class. If you are considering to take ASP.Net training then our CRB Tech .Net Training center would be very helpful in fulfilling your aspirations. We update ourself with the ongoing generation so you can learn ASP.Net with us. Stay connected to this page of CRB Tech reviews for more technical up-gradation and other resources. For more information on .net do visit : http://crbtech.in/Dot-Net-Training