Tuesday, April 29, 2014

.Net Listing Classes or Methods With A Particular Attribute.

Whenever I build a website I always like to build an admin section and expose information such as which actions are cached, which controllers require authorization and which fields are required etc. Luckily in .Net MVC most of these things are implemented as attributes.

Here is an example of scanning an assembly and listing all the classes and methods with a particular attribute on them. I chose two random attributes for this example:

[Obsolete]
public class Program
{
    public static void Main(string[] args)
    {
        var program = new Program();
        var types = program.GetAttributesOnClasses();
        foreach (var t in types)
        {
            Console.WriteLine("Class: {0}  - Attribute: {1}", t.Type.Name, t.Attributes);
        }

        var methods = program.GetAttributesOnMethods();
        foreach (var method in methods)
        {
            Console.WriteLine("Method Name: {0} -  Attribute: {1}", method.MethodInfo.Name, method.Attributes);
        }

        Console.ReadLine();
    }
  
    public IEnumerable GetAttributesOnClasses<T>() where T : Attribute
    {
        return new AttributeScan().GetTypesWith<T>(new[] { Assembly.GetExecutingAssembly() }, false);
    }

    public IEnumerable<methodattributeinfo> GetAttributesOnMethods<T>() where T : Attribute
    {
        return new AttributeScan().GetMethodsWith<T>(new[] { Assembly.GetExecutingAssembly() }, false);
    }

    [STAThread]    
    public void DoNothing()
    {          
    }

    [STAThread]
    private void PrivateDoNothing()
    {
    }

}
Will output:

Class: Program  - Attribute: System.ObsoleteAttribute[]
Method Name: DoNothing -  Attribute: System.STAThreadAttribute[]

Note that the scan did not take into account the private method.

No comments:

Post a Comment