Arrao4u

…a blog by Rama Rao

Archive for the ‘Custom Attributes Part2’ Category

Custom Attributes Part2

Posted by arrao4u on January 4, 2010

 

using 

System;

 

using 

System.Data;

 

using 

System.Configuration;

 

using 

System.Linq;

 

using 

System.Web;

 

using 

System.Web.Security;

 

using 

System.Web.UI;

 

using 

System.Web.UI.HtmlControls;

 

using 

System.Web.UI.WebControls;

 

using 

System.Web.UI.WebControls.WebParts;

 

using 

System.Xml.Linq;

 

using 

attr = System.Attribute;

 

/// 

/// 

 <summary> Summary description for ClsCustom

 

/// 

</summary>

 

AttributeUsage(AttributeTargets.Method |AttributeTargets.Class,AllowMultiple = false, Inherited = true)]

 

public 

class ClsCustom : attr

 

public ClsCustom(int iUsability, string sDev)this.UsabilityRating = iUsability;this.Developer = sDev;//

 

// TODO: Add constructor logic here

 

//

 

// scale of 1- 10

 

private 

int _usabilityRating;

 

// the name of the developer 

private 

string _developer;

 

/// 

/// 

indicates how usable a section of code is

 

/// 

on a scale of 1 – 10.

 

/// 

public 

int UsabilityRating

 

get 

return 

_usabilityRating;

 

set 

_usabilityRating = 

value;

 

/// 

/// 

the name of the developer

 

/// 

public 

string Developer

 

get 

return 

_developer;

 

set 

_developer = 

value;

 

/// 

/// 

overloaded. constructs a CodeUsabilityMeter

 

/// 

Attribute

 

/// 

/// 

on a scale

 

/// 

of 1 – 10 how usable the code is

 

/// 

/// 

/// 

the name of the developer

 

/// 

ClsCustom(10, “John Smith”)]

 

public 

class MyClass

 

public 

MyClass()

 

// indicate that this code is as 

// good as it gets 

ClsCustom(10, “John Smith”)]

 

public 

int SolidCode()

 

return 

2 + 2;

 

// this attribute (with a ranking of 1) indicates that the probability of 

//this code will 

// defintely crash 

ClsCustom(1, “Dave Q. Badprogrammer”)]

 

public 

int ShakeyCode()

 

int 

i = 0;

 

return 

2/i; 

} 

} 

Front end: 

MyClass obj = new MyClass();
        ClsCustom comments = (ClsCustom)Attribute.GetCustomAttribute(obj.GetType(), typeof
   (ClsCustom));
        Response.Write(comments.Developer);
        Response.Write(comments.UsabilityRating);
        MethodInfo[] methods = obj.GetType().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 ClsCustom)
                {
                    ClsCustom theComments = (ClsCustom)attribute;
                    Response.Write(theComments.Developer);
                }
            }

           
        }

Posted in C#, Custom Attributes Part2 | Leave a Comment »