A Custom Attribute based approach to write summary on business object

Last day, I have got a mail from a junior developer he needs some help about custom attributes. He has no previous experience about it. I have delivered his some speech or send some link for study. Today I have made an example for him, so that he can understand its usage very easily. Now this also share with you it may also help other friends.


using System;
using

System.Collections.Generic;
using System.Reflection;

namespace CustomAttributes
{
   //First custom attribute class

 // The AuthorAttribute class is a user-defined custom attribute class.
 // It can be applied to any declaration including
 //  - types (struct, class, enum, delegate)
 //  - members (methods, fields, events, properties, indexers)
 // It can be use multiple times on any object.

       [AttributeUsage(AttributeTargets.All, AllowMultiple = true,Inherited = false)]
        public class AuthorAttribute : Attribute
        {
            public AuthorAttribute(string name,string date)
            {
                this.name = name;
                this.date = date;
            }

            protected String name;
            public String Name
            {
                get { return name; }
            }

            protected String date;
            public String Date
            {
                get { return date; }
            }
       
            protected double version;
            public double Version
            {
                get;
                set;
            }

            protected String comments;
            public String Comments
            {
                get;
                set;
            }

            public override string ToString()
            {
                string value = "Author : " + Name + Environment.NewLine; ;
                value += "Date : " + Date+Environment.NewLine;
                value += "Comments : " + Comments + Environment.NewLine;
                if (Math.Abs(version - 0) > 0.0)
                {
                    value += " Version : " + Version.ToString()+Environment.NewLine;
                }
                return value;
            }
        }

 //Second custom attribute class

// The IsTested class is a user-defined custom attribute class.
// It can be applied to any declaration including
//  - types (struct, class, enum, delegate)
//  - members (methods, fields, events, properties, indexers)
// It is used with no arguments.

    public class IsTestedAttribute : Attribute
    {
        public override string ToString()
        {
            return "Is Tested";
        }
    }

    //attaching Author attribute to our TestClass
        [Author("Ahsan murshed", "19-02-2012", Comments = "Create a new method TestMethod()", Version = 0.5)]
        [Author("Kamrul hasan", "19-02-2012", Comments = "Update TestMethod()", Version = 1.0)]
        public class InsertClass
        {
            //attaching Author attribute to our InsertMethod
            [Author("Ahsan murshed", "17-01-2011", Comments = "This InsertMethod() used for insert comments", Version = 1.0),IsTested()]
            public void InsertMethod()
            {
            }

            [Author("Ahsan murshed", "17-01-2011", Comments = "This DeleteMethod() used for delete comments", Version = 1.0)]
            public void DeleteMethod()
            {
            }   

            //attaching Author attribute to our AnyInt Field
            [Author("Ahsan murshed", "17-01-2011", Comments = "This is TestField comments", Version = 1.0)]
            public int TestField;
        }

    [Author("Ahsan murshed", "17-01-2011", Comments = "This is UpdateClass comments", Version = 1.0)]
    public class UpdateClass
    {
        [Author("Shahidul alam", "19-01-2012", Comments = "Add this UpdateMethod() method for update comments", Version = 1.0)]
        public void UpdateMethod()
        {
        }
    }

    public class AuthorTest
    {
        private static void WriteAttributes(MemberInfo member)
        {
            Console.WriteLine("Attributes for : " + member.Name);
            foreach (object attribute in member.GetCustomAttributes(true))
            {
                Console.WriteLine(attribute);
            }
        }

        //This is the main class
        public static void Main()
        {
            //Get the InsertClass attribute information
            Type type = typeof(InsertClass);
            WriteAttributes(type);
            FindMethodandFieldsAttributes(type);
       
           //Get the UpdateClass attribute information
            type = typeof(UpdateClass);
            WriteAttributes(type);
            FindMethodandFieldsAttributes(type);
         
            Console.ReadLine();
        }

     
        private static bool IsMemberTested(MemberInfo member)
        {
            foreach (object attribute in member.GetCustomAttributes(true))
            {
                if (attribute is IsTestedAttribute)
                {
                    return true;
                }
            }
            return false;
        }

         private static void FindMethodandFieldsAttributes(Type type)
         {
             AuthorAttribute authorAttributeAttr;
         
             //Finding Class level custom Attributes
             foreach (MethodInfo method in type.GetMethods())
             {
                 foreach (Attribute attr in method.GetCustomAttributes(true))
                 {
                     authorAttributeAttr = attr as AuthorAttribute;
                     if (null != authorAttributeAttr)
                     {
                         Console.WriteLine("Comments on {0} : {1}",
                                           method.Name,
                                           authorAttributeAttr.Comments);
                 
                         Console.WriteLine(IsMemberTested(method) ? "Member {0} is tested!" : "Member {0} is NOT tested!",method.Name);
                     }

                 }
             }

             //Finding Field level (only public) custom Attributes
             foreach (FieldInfo field in type.GetFields())
             {
                 foreach (Attribute attr in field.GetCustomAttributes(true))
                 {
                     authorAttributeAttr = attr as AuthorAttribute;
                     if (null != authorAttributeAttr)
                     {
                         Console.WriteLine("Comments on {0} : {1}",
                                           field.Name, authorAttributeAttr.Comments);
                     }
                 }
             }
             Console.WriteLine("\n");
         }
    }
}

Output:


Comments

Smith said…
Thanks guy..its really a wonderful blog.carry on pls

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript