Dynamic Programming

Introduction

 
The article is about attributes. You'll see how to define attributes on various items within your program. We shall also discuss the most innovative feature that the .NET framework has to offer, custom attributes, a mechanism that allows you to associate custom metadata with program elements. This metadata is created at compile-time and embedded into an assembly. You can then scrutinize the metadata at runtime using reflection. The article also explains the use of reflection in custom attributes.
 
Attributes
 
As illustrated in earlier articles, the .NET compiler generates metadata descriptions for all defined and reference types. However, the developer can integrate additional metadata into an assembly using attributes. So attributes are like adjectives for metadata annotation similar to a COM IDL that can be applied to a given type, assembly, modules, methods, and so on. The .NET framework provides two types of attribute implementations, Predefined Attributes, and Custom Attributes.
 
Attributes are types derived from the System.Attribute class. This is an abstract class defining the required services of any attribute. The following is the syntax of an attribute:
 
[type: attributeName(parameter1, parameter2,………n)]
 
The attribute name is the class name of the attribute. Attributes can have zero or more parameters. The following code sample states the implementation of the attribute in which we are declaring a method as deprecated using the obsolete attribute:
  1. using System;  
  2.   
  3. namespace attributes  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Attributes sample");  
  10.             TestMethod();  
  11.             Console.ReadKey();    
  12.         }  
  13.         [Obsolete("Deprecated Method",false)]  
  14.         public static void TestMethod()  
  15.         {  
  16.             Console.WriteLine("Hello world");    
  17.         }  
  18.     }  
  19. }  
The following figure shows the MSIL code of the TestMethod method as displayed in ILDASM. Notice the custom directive that defines the Obsolete attribute.
 
attribute
 
Role of Attributes
 
Attributes might be useful for documentation purposes. They fulfill many roles, including describing serialization, indicating conditional compilation, specifying import linkage, and setting a class blueprint. Attributes allow information to be defined and applied to nearly any metadata table entry. This extensible metadata information can be queried at run time to dynamically alter the way code executes.
 
The C# compiler itself has been programmed to discover the presence of numerous attributes during the compilation process. For example, if the csc.exe compiler discovers an item being annotated with the [obsolete] attribute, it will display a compiler warning in the IDE error list.
 
Predefined Attributes
 
The predefined attributes have been defined by Microsoft as a part of the .NET FCL and many of them receive special support from the C# compiler. Which implies that for those specific attributes, the compiler could customize the compilation process in a specific way.
 
The System.Attribute base class library provides a number of attributes in various namespaces. The following table gives a snapshot of some predefined attributes.
 
Attributes

 

Description

 

[Serialization]
By marking these attributes, a class is able to persist its current state into the stream.
[NonSerialization]
It specifies that a given class or field should not be persisted during the serialization process.
[Obsolete]
It is used to mark a member or type as deprecated. If they are attempted to be used somewhere else then compiler issues a warning message.
[DllImport]
This allows .NET code to make calls to an unmanaged C or C++ library.
[WebMethod]
This is used to build XML web services and the marked method is being invoked by an HTTP request.
[CLSCompliant]
Enforce the annotated items to conform to the semantics of CLS.
 
Attributes Description
 
To illustrate the predefined attributes in action, let's create a console based application to apply the implementation of them.
 
[Serialization] and [NonSerialization]
 
Here, assume that you have built a test class that can be persisted in a binary format using the [Serialization] attribute.
  1. [Serializable]  
  2. public class test  
  3. {  
  4.    public test() { }  
  5.   
  6.    string name;  
  7.    string coutnry;  
  8.    [NonSerialized]  
  9.    int salary;  
  10. }  
Once the class has been compiled, you can view the extra metadata using the ildasm.exe utility. You can notice the Red triangle, where these attributes are recorded using the serializable token, and the salary filed is tokenized using the nonserilaized attribute as in the following.
 
NonSerialization
 
[WebMethod]
 
The following example depicts the implementation of XML web services. Here, the UtilityWebService class is annotated with [WebService] attributes. This class defines two methods that are marked with [WebMethod] attributes.
  1.     [WebService(Namespace = "http://tempuri.org/")]  
  2.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  4.     // [System.Web.Script.Services.ScriptService]  
  5. public class UtilityWebService : System.Web.Services.WebService {  
  6.   
  7.     public UtilityWebService () {  
  8.   
  9.         //Uncomment the following line if using designed components   
  10.         //InitializeComponent();   
  11.     }  
  12.   
  13.     [WebMethod]  
  14.     public string HelloWorld() {  
  15.         return "Hello World";  
  16.     }  
  17.   
  18.     [WebMethod]  
  19.     public int addition(int a,int b)  
  20.     {  
  21.         return a+b;  
  22.     }  
  23.       
  24. }  
[DLLImport]
 
The following code plays around the unmanaged assembly user32.dll to utilize its existing method using the [DLLImport] attributes as in the following:
  1. using System;  
  2. using System.Runtime.InteropServices;  
  3. namespace attributes  
  4. {  
  5.     public class test  
  6.     {  
  7.         [DllImport("user32.dll", EntryPoint = "MessageBox")]  
  8.         public static extern int ShowMessageBox(int hWnd,string text, string caption,uint type);  
  9.     }  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             string caption = "Hello World";  
  15.             string text = "Sample Article on DLLImport Attribute";  
  16.             test.ShowMessageBox(0, text, caption, 0);     
  17.             Console.ReadKey();    
  18.         }  
  19.           
  20.     }  
  21. }  
Note: a member can be assigned more than one attribute and can be applied multiple times itself.
 
Once this code is compiled successfully, it produces the following output as in the following:
 
compiled
 
[CLSCompliant]
 
If you annotate this attribute at an assembly or module level and you try to use the following non-CLR compliant code, then the compiler issues a warning message.
 
CLSCompliant
 
Custom Attributes
 
We can create custom attributes for private usage or to be published in a library for others. The following procedure is the definitive procedure for creating custom attributes:
  1. The custom attribute class should be derived from System.Attribute.
  2. The Attribute name should have the Attribute suffix.
  3. Set the probable targets with the AttributeUsage attribute.
  4. Implement the class constructor and write-accessible properties.
The first step in building a custom attribute is to create a new class FunWith with an Attribute suffix that is derived from the System.Attribute class. Then define the class constructor and write an accessible property, Company.
  1. [AttributeUsage(AttributeTargets.Class)]  
  2. public class FunwithAttribute : Attribute  
  3. {  
  4.    public FunwithAttribute(string s)  
  5.    {  
  6.       this.Company = s;   
  7.    }  
  8.    public string Company { getset; }   
  9. }  
Now, it is time to apply a custom attribute class on another class. So we are creating another class, test, that has a FunWith attribute annotation in which we are passing the company name information.
  1. [Funwith("HCL Technology")]  
  2. public class test  
  3. {  
  4.     public test(string name, string country)  
  5.     {  
  6.         this.EmpName = name;  
  7.         this.Country = country;     
  8.     }  
  9.     public string FullDetails()  
  10.     {  
  11.         string str = EmpName + "-" + Country;  
  12.         return str;  
  13.     }  
  14.   
  15.     private string EmpName;  
  16.     private string Country;  
  17. }  
  18. class Program  
  19. {  
  20.     static void Main(string[] args)  
  21.     {  
  22.         test obj = new test("Ajay","India");  
  23.         Console.WriteLine("Result:{0}",obj.FullDetails());  
  24.         Console.ReadKey();    
  25.     }  
  26. }  
After compiling this program, it yields the following output.
 
Output
 
Result: Ajay - India
 
Well, as you can see, the custom attribute does not impose any impact on the final output. But we can reveal the annotation done using attributes at the metadata level using ildasm.exe as in the following:
 
custom attribute
 
Custom defined attributes are sometimes valuable simply as information. However, the real power lies in associating with an attribute. You can read custom attributes with reflection using Attribute.GetCustomAttribute and Type.
 
The following code states of accessing the custom attribute values at runtime using reflection. Here, we are storing the custom attributes members in an array of object types, then iterating through it to get the property value:
  1. static void Main(string[] args)  
  2. {  
  3.     MemberInfo info = typeof(test);  
  4.     object[] attrib = info.GetCustomAttributes(typeof(FunwithAttribute), false);  
  5.     foreach (Object attribute in attrib)  
  6.     {  
  7.         FunwithAttribute a = (FunwithAttribute)attribute;  
  8.         Console.WriteLine("Company: {0}", a.Company);  
  9.           
  10.     }  
  11. }
For a better understanding, the following code shows the actual utilization of custom attribute values. Here, we are displaying a string value based on the custom attribute Boolean value. The output varies on the status True or False values.
  1. using System;  
  2. using System.Reflection;    
  3.   
  4. public class CheckStatus : Attribute  
  5. {  
  6.     private bool Val = false;  
  7.     public bool status  
  8.     {  
  9.         get { return Val; }  
  10.     }  
  11.     public CheckStatus(bool val)  
  12.     {  
  13.        Val = val;  
  14.     }  
  15. }  
Now we are annotating the Custom Attribute in the Test class. Here, we need to configure the CheckStatus value to true to false manually. In the FullDetails() method, we are accessing the custom attributes members using a foreach loop construct and later we check whether the status value is true or false.
  1. [CheckStatus(false)]  
  2.  public class test  
  3.  {  
  4.   
  5.      private string EmpName;  
  6.      private string Country;  
  7.   
  8.      public test(string name, string country)  
  9.      {  
  10.          this.EmpName = name;  
  11.          this.Country = country;     
  12.      }  
  13.      public string FullDetails()  
  14.      {  
  15.          string str = null;  
  16.          Type type = this.GetType();  
  17.   
  18.          CheckStatus[] attrib = (CheckStatus[])type.GetCustomAttributes(typeof(CheckStatus), false);  
  19.   
  20.          if (attrib[0].status == true)  
  21.          {  
  22.              str = EmpName + "-" + Country;  
  23.          }  
  24.          else  
  25.          {  
  26.              str = "Hi " + EmpName;  
  27.          }  
  28.   
  29.          return str;  
  30.      }  
  31.  }  
  32.  class Program  
  33.  {  
  34.      static void Main(string[] args)  
  35.      {  
  36.          test obj = new test("Ajay","India");  
  37.          Console.WriteLine("Result:{0}",obj.FullDetails());  
  38.          Console.ReadKey();    
  39.      }  
  40.  }  
After successfully compiling this code, the following figure shows the output in both of the cases:
 
compiling this code
 
It is also possible to apply attributes on all types within a given module or assembly. To do so, simply add the attributes at assembly level in the AssemblyInfo.cs file. This file is a handy place to put attributes that are to be applied at the assembly level.
  1. using System.Reflection;  
  2. using System.Runtime.CompilerServices;  
  3. using System.Runtime.InteropServices;  
  4.   
  5. [assembly: AssemblyTitle("CustomAttribute")]  
  6. [assembly: AssemblyDescription("")]  
  7. [assembly: AssemblyConfiguration("")]  
  8. [assembly: AssemblyCompany("")]  
  9. [assembly: AssemblyProduct("CustomAttribute")]  
  10. [assembly: AssemblyCopyright("Copyright ©  2013")]  
  11. [assembly: AssemblyTrademark("")]  
  12. [assembly: AssemblyCulture("")]  
  13. [assembly: ComVisible(false)]  
  14. [assembly: Guid("ce5fc30b-e670-4115-aa64-4be10e7b6ea9")]  
  15. [assembly: AssemblyVersion("1.0.0.0")]  
  16. [assembly: AssemblyFileVersion("1.0.0.0")]  

Summary

 
This article examines the role and importance of attributes that is an identical aspect of dynamic programming. When you adorn your types with attributes, the result is the expansion of the underlying assembly metadata. We also explored the various types of attributes as well as got an understanding of programmatically implementing a Predefined attribute such as [WebMethod], [Serialization] and so on. The prime objective of this article is to teach the readers how to create your own custom attributes depending on the programming needs. After going through this article, we have a full understanding of how to apply both predefined and custom attributes over types.


Similar Articles