Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Aspect Oriented Programming in .NET using PostSharp

DZone's Guide to

Aspect Oriented Programming in .NET using PostSharp

·
Free Resource
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.
Topics:

Published at DZone with permission of Łukasz Budnik, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}