Tuesday, 3 April 2012

What is Attribute based programming and Reflection ?


Attribute Is a type. Which is used adding additional metadata to our programm. With the help of attribute based programming.
Attribute based programming allows programmer to resue the existing code as a metadata. The code is added to our program at complie time.
How to add additional data(meta data) to our program?
Yes, we can add additional meta data to our program using declarative manner.
Like [AttributeName]

We have 2 types of attributes

1.instrict attributes. 2. Custom attributes
1. instric Attributes
Intrinsic attributes are supplied as part of the Common Language Runtime, and they are integrated into .NET.
Ex: [ObsoleteAttribute()]

2. Custom attributes

Attribute is also a class. The purpose of attribute based programming is we can add some meta data to our program at complie time and we can use(read) that meta data at runtime (using Reflection API ) for further processing of our programm.
Ex Demo:
[AttributeUsage(AttributeTargets.All)]
Class  Passenger Attribute: System.Attribute
{
}
Note 1: Every Attribute must derive from System.Attribute
Note 2: We have to specify that attribute scope.

Using -2-thingsàAttributeUsage and
AttributeTargets.All,assembly,class,construtor….ect;
Default is anywhere.
All: anywhere in the program. We can declare that attribute scope.
Like as method level,class level,property level,constructor level…..ect.

public AttributeUsageAttribute(AttributeTargets validOn);

Attribute Usage
The scope and target of the attribute can be defined by applying AttributeUsage. It contains three properties, which we can set to specify attributes.
AllowOn
This is a set of flags that indicates the program entities on which the attribute can be placed. Multiple AttributeTargets can also be specified using a bitwise OR operator.
AllowMultiple
AllowMultiple lets you specify whether you can apply multiple instances of a particular attribute to the same element. If AllowMultiple is set to true, then inherited classes will inherit all instances of the attribute from the parent class. The default value for AllowMultiple is false.
Inherited
The Inherited property determines whether the attribute will be inherited by classes that are derived from the classes to which the attribute is applied. The default value for Inherited is true, indicating that an attribute applied to the base class will be applied to all its derived classes.
Attribute Parameters
Attributes accept parameters for customization. They take two types of parameters, positional and named.
Positional Parameters: Positional parameters are specified using constructor arguments to the attribute class.
Named Parameters: Named parameters are defined by having a non-static field or property in the attribute class.
Attribute parameter types can be:
bool, byte, char, double, float, int, long, short, string
System.object
System.Type
A public enum
A one-dimensional array of the above types.
Incase of Attribute we have 2 Attributes.
1.    Positional parameters
2.    Named parameters. 
While passing positional parameters using constructor 
A named parameter is a non-static field or a non-readonly property. 
A positional parameter is what we pass on to a constructor.
We have 2 positional parameters as our constructor has two parameters and mukhi and sonal are our named parameters. The named parameters come after the positional ones. The positional parameter's order is important, but the named parameters can be in any order.
Attribute targets can be one of the following:
·         All   ·         Assembly ·         Class  ·         Constructor
·         Delegate ·         Enum ·         Event   ·         Field ·         Interface ·         Method ·         Module ·         Parameter·         Property
·         ReturnValue   ·         Struct
Here  Attribute is base calss.
Reflection:
To inspect the meta data information dynamically using the reflection API.
The reflection classes are contained in the namespace System.Reflection. The classes in the Reflection namespace, along with the System.Type and System.TypedReference classes, provide support for examining and interacting with the metadata. The abstract base class Type helps access metadata information. The types include the constructors, methods, fields, properties, and events of a class and the module and the assembly in which these are stored.
The System.Reflection namespace defines the following types:
·         Assembly  ·         Module ·         Enum ·         MethodInfo
·         ConstructorInfo  ·         MemberInfo ·         ParameterInfo  ·         Type
·         FieldInfo ·         EventInfo ·         PropertyInfo
Here is a complete example of a class that inspects another class and demonstrates the power of reflection to display the metadata information dynamically.
Type is base calss.
The meta data is used by many classes as per our usage.
Ex:
[serializable]
Public class StudentAttribute:system.Attribute
Here some meta data is added to our student class then this added meta data is used for student class
[serializable]
Public class EmployeeAttribute:system.Attribute
Here also some meta data is added to our Employee class then this added meta data is used for employee class.
Here we can observer constructor overloading.using ildasm.exe
Demo:
  [AttributeUsage( AttributeTargets.All )]
         public class Comments : System.Attribute
         {
             public string author = String.Empty;
             public string type = String.Empty;
             public string description = String.Empty;
             private string status = String.Empty;
             public Comments(string author, string type,string description)
             {
                 this.author = author;
                 this.type = type;
                 this.description = description;
             }
             public string Status
             {
                 get
                 {
                     return status;
                 }
                 set
                 {
                     status = value;
                 }
             }
             public static void DisplayAttributes(Type t)
             {
                 Comments comments = (Comments) Attribute.GetCustomAttribute(t,typeof(Comments));
Console.WriteLine("The Author is:{0}." , comments.author);
Console.WriteLine("The Description is:{0}." , comments.description);
                 System.Console.WriteLine("Class Name:{0}", t.Name);
                 MethodInfo[] methods = t.GetMethods();
                 object[] attributes = null;
                 for (int i = 0, l = methods.GetLength(0); i< l; i++)
                 {
                     MethodInfo mi = methods[i];
                     attributes = mi.GetCustomAttributes(true);
                     foreach (Attribute attribute in attributes)
                     {
                         if (attribute is Comments)
                         {
                             Comments theComments = (Comments)attribute;
                             System.Console.WriteLine("Name: {0} ,Type : {1}, Purpose: {2} , Created By : {3}", mi.Name, theComments.type ,theComments.description,theComments.author );

                         }
                     }
                 }
             }
         }
Now we are using Comment Class as a attribute.

Example 1:

   [Comments("Joydip", "Class", "Employee Entity")]
    class Employees
    {
        public static void Main(string[] args)
        {
        
            Comments.DisplayAttributes(typeof(Employees));  //static class
            System.Console.Read();
        }
    }

Example 2:
[Comments("kasi","1234","purre")]
    class Student
    {      
        static void Main()
        {
            Comments.DisplayAttributes(typeof(Student));       //static class             
            Console.Read();
        }
    }


we can see constructor overloading in attribute based programming and we can see this with the help of ildasm.exe

No comments:

Post a Comment