.NET Zone is brought to you in partnership with:

Łukasz works as a Technical Architect for an international IT company and is responsible for delivering applications written in Java EE, Spring, and .NET. He has been involved in many various projects ranging from online insurance systems, voice and video solutions, mobile systems (both native and HTML5-based), medical systems, and large system integration projects. Łukasz is an expert in distributed systems, SOA, and cloud. Łukasz holds PhD in Computer Science. Łukasz is a DZone MVB and is not an employee of DZone and has posted 13 posts at DZone. You can read more from them at their website. View Full User Profile

Aspect Oriented Programming in .NET using PostSharp

07.26.2012
Email
Views: 558
  • submit to reddit
The .NET Zone is presented by VaraLogix to keep you updated on all the latest news, tips, and tools in the .NET community.  Check out today's top .NET content and read about VaraLogix's deployment automation and CM utilities plus their best practices.
PostSharp is claiming to be the most comprehensive AOP library in the .NET world. I gave it a try and I must to say that their claim is very well founded.

Read more to see PostSharp in action.

PostSharp

PostSharp is not a free tool, but the trail version should be OK to get you started and do some proof of concepts.

The best way to learn AOP and PostSharp itself is to watch PostSharp's podcasts. The usecases shown in those podcasts are well balanced, they are not too easy not too difficult. I suspect that even people without any previous AOP experience will get a pretty solid idea of what AOP is. The podcasts are here: http://www.sharpcrafters.com/media/tutorials.

Audit aspect

I wanted to write a fine-grained audit aspect which could log execution traces. I wanted to be able to do something like this.

1) Add [Audit] attribute to methods:
public class GenericDAO<T>
{
    [Audit("DAO")]
    public void Save(T entity)
    {
        /* ... */
    }
}
2) Add [Audit] attribute to classes, but be able to switch off auditing for some of the methods using [NoAudit] attribute just like this:
[Audit("DAO")]
public class GenericDAO<T>
{
    [NoAudit]
    public GenericDAO()
    {
        /* ... */
    }
}
It took me 10 minutes to write the following 2 aspects (note if I were to use them in production, which I'm sure I will in a few weeks, I would make them a slightly more optimised - like reduce reflections etc). Here they are:
[Serializable]
public sealed class AuditAttribute : OnMethodBoundaryAspect
{
    private readonly string _category;
    public AuditAttribute(string category)
    {
        _category = category;
    }
    public override bool CompileTimeValidate(MethodBase method)
    {
        object[] attributes = method.GetCustomAttributes(typeof(NoAuditAttribute), true);
        if (attributes.Length > 0)
        {
            Message.Write(SeverityType.Warning, "Audit", "Skipping auditing on " + method.DeclaringType.ToString() + " method " + method.ToString());
            return false;
        }
        return base.CompileTimeValidate(method);
    }
    public override void OnEntry(MethodExecutionArgs args)
    {
        StringBuilder sb = new StringBuilder();
        ParameterInfo[] parameterInfos = args.Method.GetParameters();
        for (int i = 0; i < parameterInfos.Length; i++)
        {
            ParameterInfo parameterInfo = parameterInfos[i];
            object parameterValue = args.Arguments[i] ?? "null";
            sb.AppendFormat("{0}={1}", parameterInfo.Name, parameterValue);
            if (i < parameterInfos.Length - 1)
            {
                sb.Append(", ");
            }
        }
        Trace.WriteLine(string.Format("Entering {0}.{1} {2}",
            args.Method.DeclaringType.Name, args.Method.Name, sb), _category);
        args.MethodExecutionTag = DateTime.Now;
    }
    public override void OnException(MethodExecutionArgs args)
    {
        Trace.WriteLine(string.Format("Exception " + args.Exception + " thrown in {0}.{1}",
            args.Method.DeclaringType.Name, args.Method.Name), _category);
    }
    public override void OnSuccess(MethodExecutionArgs args)
    {
        DateTime endTime = DateTime.Now;
        TimeSpan executionTime = endTime.Subtract((DateTime)args.MethodExecutionTag);
        bool isVoid = ((MethodInfo)args.Method).ReturnType == typeof(void);
        object returnValue;
        if (isVoid)
        {
            returnValue = "void";
        }
        else
        {
            returnValue = args.ReturnValue ?? "null";    
        }
        Trace.WriteLine(string.Format("Leaving {0}.{1} processing took me {2}ms return value was {3}",
            args.Method.DeclaringType.Name, args.Method.Name, executionTime, returnValue), _category);
    }
}
[Serializable]
public sealed class NoAuditAttribute : Attribute
{
}
When AuditAttribute is applied to class and a method has NoAuditAttribute then a warning message "Skipping auditing on ClassABC method MethodXYZ" is displayed in MS VS errors tab (see CompileTimeValidate method above).

Applying different aspects to the same method

Next I wanted to mix my aspects. Apart of auditing aspect I wrote a ValidateAttribute and wanted to use it this way:
[Serializable]
public sealed class ValidateAttribute : OnMethodBoundaryAspect
{
    /* ... */
}
[Audit("DAO")]
public class GenericDAO<T>
{
    [Validate("Full")]
    public void Save(T entity)
    {
        /* ... */
    }
}
There was one small issue with the above code. It worked, but PostSharp was saying that the order of aspects may have been undeterministic. But this is really not a problem with PostSharp. If I wanted to log the parameters before validation we should have added AspectTypeDependency attribute to ValidateAttribute just like this:
[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, typeof(AuditAttribute))]
Summary

As an excercise you can write support for shadowing parameters. For example add a new parameter to the AuditAttribute which would take an array of parameters' names to shadow (like username, password) and print either null if passed value is null or "*****" otherwise.
Published at DZone with permission of Łukasz Budnik, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

This content was brought to you in partnership with VaraLogixVaraLogix empowers developers and IT operations with an all-in-one deployment and CM product.  See VaraLogix's tips for taking the risk out of .NET deployment.