DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Aspect Oriented Programming in .NET using PostSharp

Aspect Oriented Programming in .NET using PostSharp

Łukasz Budnik user avatar by
Łukasz Budnik
·
Jul. 27, 12 · Interview
Like (0)
Save
Tweet
Share
7.40K Views

Join the DZone community and get the full member experience.

Join For Free
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.
Aspect (computer programming) Aspect-oriented programming

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Development Trends 2023
  • Using the PostgreSQL Pager With MariaDB Xpand
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • Kotlin Is More Fun Than Java And This Is a Big Deal

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: