AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=37&pId=-1
Programming with Attributes
page
by Kavitha Pradeep
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22668/ 36

What is Attribute Based Programming?

Before the advent of object oriented programming, the design of the system was done by breaking the system into modules and then integrating the entire functionality by making calls to the functions. The concept of reusability was bleak.

Then software development ventured into object oriented programming, where reusability and scalability were targeted. Normally, a design of any application is thought in terms of componentizing the entire application for further reuse. In a distributed web application the UI tier, the business tier and the data tier is what comes to our mind. But the paradigm shift to object oriented programming or component based development was not helpful to a very good extent as objects were glued to code. In a method  “ Save “ of a class File the code written would be , instantiating a sequence of objects for establishing a connection , execute a command , log the transaction , close connection . These sequences of object creation would have to be written in all the methods where data is going to be saved. A developer is thus doing some kind of re-writing of code. In C++ the constants, attributes and operations were annotated with public, private or protected. This annotation is interpreted by the C++ compiler to add special meaning for each annotation there by giving access and security to data. Attribute based programming helps to annotate classes, constructors, properties, methods to add more meaning to them during runtime. The attributes can be added or removed from the code conveniently and the duplication of code across methods is eliminated. The runtime uses these attributes to compose an object stack when the object is created. When the client makes method call each attribute gets a chance to execute its part and transfer control until finally the actual method is invoked. During the stack wind up each attribute is again given a chance to wind up and the final stack wind up takes place. This means that the sequence of operations that you wrote is now handled by the runtime. Usage of attributes gives flexibility to code and avoids duplication of code. Lets us look into the recipe of .NET to design attributes, write custom attributes and use pre-defined attributes.

Attribute Based Programming in .NET

The Microsoft .NET Framework makes life easy by extensively supporting attributes.  You could add flavor to your code by using the existing attributes or you could define and design your own attributes. The base class for attributes is System.Attribute. 

Using existing attributes is relatively easier and Microsoft has provided you with a huge list of attributes that you could use.  You must have definitely developed simple console applications.

[STAThread]
static void Main(string[] args)
{


}

The [STAThread ] annotated before the main method is an attribute that marks a thread to use the Single-Threaded COM Apartment if COM is needed. SImilary if you have developed web services than you must have seen the attribute [webmethod] annotated before methods act as web services. Thus using these attributes is pretty easy .

We shall now delve into how to write our own custom attributes. Writing custom attribute greatly helps in annotating pieces of software code according to our needs. The basis for Attributes is the System.Attribute class.

Authoring Your Own Attributes

When we play around with attributes we need to wear three hats at any point of time
a) The attribute creator
b) The attribute user
c) The attribute interpreter

Let us briefly understand the steps involved in writing attributes. The points to remember are

a) Your class must be derived  from System.Attribute
b) Every class needs to have a default constructor ( at the minimal)
c) If your attribute takes parameters than it must have a constructor that takes parameter.

Step 1 Writing attributes

We shall write a simple ClassDeveloper attribute. This attribute when used for a class would tell us who the owner of the class is or who has coded this class.

The code for this attribute is as given below

using System;


namespace DeveloperTrackTool
{
 /// <summary>
 /// Summary description for Sales.
 /// </summary>
 /// 


 class ClassDeveloperAttribute:Attribute
 {
  public string loggerName;
  public ClassDeveloperAttribute(string strName)
  {
   loggerName = strName;
   
  }
 }


 
    }

To help you understand attributes we shall write a simple code .In the above code we have written a class called ClassDeveloperAttribute that is inherited from Attribute.  This class has a single data member and a constructor. We have thus created a custom attribute called ClassDeveloper . This attribute can now be applied to other classes whenever we need to track who the developer of the class is. Thus we have worn the hat of a creator.


 [ClassDeveloper("Kavitha")]
 public class Sales
 {
  public Sales()
  {
   //
   // TODO: Add constructor logic here
   //
  }
 }
  
  
}

Now let us start using this attribute. The Sales class is a very simple class which is annotated with the attribute that we have created i.e the ClassDeveloper attribute. It is being passed the developers name who has created the Sales class . So now we have worn the hat of a user.

Let us now write a simple code to interpret this attribute. Create a simple form based application with a textbox and a button .

When the user clicks on the button we would instantiate a Sales object and invoke a method called DisplayDeveloper() that would display all the attributes applied to the Sales class

private void button1_Click_1(object sender, System.EventArgs e)
  {
   Sales s1 = new Sales();
   DisplayDeveloper (s1);
   
  }

Let us take a look at the DisplayDeveloper() method in detail

public void DisplayDeveloper(object obj1)
{
  
   Type typ = obj1.GetType();
   object []obj = typ.GetCustomAttributes(true);
   if ( obj[0]  is ClassDeveloperAttribute )
    textBox1.Text = " Class Developed by    " + ((ClassDeveloperAttribute)obj[0]).loggerName.ToString();
   else 
    textBox1.Text= "No Owner for this class";


}

The method gets the type of the object passed as the parameter to the method. In this case a Sales object . The GetCustomAttributes() function helps in getting the custom attributes for the Sales class. Currently the attribute for the Sales class is ClassDeveloperAttribute. The attributes are then displayed within a textbox

Now in future if you would need to also check who has debugged the Sales class probably the easiest thing you could do is to create the ClassDebuggerAttribute and then annotate the Sales class with this attribute.

Conclusion

Attributes provide an excellent way to annotate pieces of code and add more meaning to the code. Use them wherever possible.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 10:04:29 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search