Tag: AOP

AOP

Executing on the Background Thread with PostSharp

Background ThreadIn my last two PostSharp blog posts, I looked at creating some custom attributes that you could use to get custom behavior out of PostSharp. Of course, I was implementing simple functionality and in fact, PostSharp had most of if not all of those features already built in.

Today, I want to dig in a little more to some of the built in power of PostSharp. To do this, I had to sign up for the 45 day evaluation license for PostSharp Ultimate. I had been putting that off to do as much “free stuff” as I could, but I really wanted to see what PostSharp could do, so I fired up the evaluation.

I created a very simple UI that looks like this:
Simple "Long Running Process" UI

When you click the buttons, I call a class that just sleeps for three seconds and returns to simulate some slow process.

public void LongRunningOperationBlocking()
{
    Thread.Sleep(3000);
    return;
}

I created code that will run this blocking process and then when the UI thread is free again, it displays a message box with whatever was in the textbox. Here is the UI in action. Note that I cannot select the text after clicking the button because the UI is locked up for 3 seconds.
Blocking Fail

However, with PostSharp, we can easily execute these long running methods on a background thread. As long as the method returns void, the context menu will reveal the “Execute method in the background” option like this:
The PostSharp Context Menu Showing Background Thread Option

After selecting that option, you get this wizard:
The PostSharp Add a Feature Wizard

The sum total of the “visible” changes is that our other method got a new attribute, “[Background]”

[Background]
public void LongRunningOperationBackground()
{
    Thread.Sleep(3000);
    return;
}

But, the win is that now when I click the button, the UI returns immediately and we see the message box right away, even while the long running process is going.
Blocking Fail

That is a gigantic amount of threading code that we don’t have to write. It is only probably 4-6 lines per method, but you have to write the same thing over and over again for every method you want to have do work on a background thread. Of course, any time you can just cut out “boilerplate code”, you make your code not only easier to write, but easier to read and discern intent. And that is “A Good Thing™”!

As always, you can download the code for this series from my Github repository for it. The path to this post’s code is here.

AOP

Parameter Checking with PostSharp

Guard TowerLast time, I started off my PostSharp series by adding some logging coming in and out of a method. It was very easy to do and it was nice to have a single point of code that wasn’t copy-paste repeated all over the codebase. This time, I want to look at what it might take to check the parameters that come into the method.

As Matt Groves pointed out in the comments of my last post, Phil Haack created something called NullGuard to do the kind of thing that I’m endeavoring to do here. In addition, PostSharp themselves created the ability to do just this very thing with the release of PostSharp 3, but it is only available in the paid editions. You can see an explanation in detail here.

Smart people don’t roll their own code for things that are already “solved problems” (I ranted about this in a recent podcast). However, I’m going to tackle this simple problem a few different ways in order to demonstrate how you can create your own more complex rules with PostSharp.

I created a class called NoNullParamsAttribute.cs and its code is as follows

using PostSharp.Aspects;
using System;
using System.Text;

namespace IntroToAop2
{
    [Serializable] 
    public class NoNullParamsAttribute : OnMethodBoundaryAspect 
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            var messages = new StringBuilder();

            for (int i = 0; i < args.Arguments.Count; i++)
            {
                if (args.Arguments.GetArgument(i) == null)
                {
                    messages.AppendFormat("Parameter \"{0}\" cannot be null. ", args.Method.GetParameters()[i].Name);
                }
            }

            if (messages.Length > 0)
            {
                throw new ArgumentException(messages.ToString());
            }
        }
    }
}

Now, we can call that above one of our methods from last week like this

[NoNullParams]
public string ReverseString(string input)
{
    var inputArray = input.ToCharArray();
    Array.Reverse(inputArray);
    return new string(inputArray);
}

Now when I call it passing in null, I get an argument exception with the message ‘Parameter “input” cannot be null.’. I could obviously do the same check to make sure that it was not empty, or that all integers were greater than zero, and so on. Of course, the examples I mentioned earlier are much more sophisticated, however today we’ve seen how to iterate over method parameters, get their name, and examine them. Not too bad for a day’s work!

All of the code can be found on my GitHub repo for this series under IntroToAop2.

AOP

My Intro to AOP with PostSharp

PostSharp LogoOn the last episode of my podcast, I interviewed Matt Groves about Aspect Oriented Programming (AOP). Talking with him inspired me enough to really make a go and spend some time with it to see if I could get comfortable with it. I’m going to try to use PostSharp because I like how it works and because (to be honest) they helped promote that last podcast, and that makes me like their style 😉

As Matt talked about in the podcast, AOP is basically a kind of design pattern. Essentially, you find stuff that is in your code and in a lot of methods, but doesn’t ACTUALLY pertain to the method. Common examples are logging, error handling, cache checks, and parameter checking, to name a few. Once you isolate this code that is basically boilerplate code that is used over and over again throughout your methods, you pull that code out and allow it to exist in only one place.

Frameworks like PostSharp act as post-compilers, so you write your code, add some attributes, and PostSharp will take an extra compiler pass through your code and write the code in for you, as if you had done it yourself. This allows for no additional runtime overhead, as the code works out to just basically be your standard code you would have written anyway.

To get started, head over to PostSharp’s site and download their product. It gets added as a Visual Studio extension and – as of today – you get a 45 day license to their full product when you download it. After that, it will revert to the free version. The free version still has a ton of great features and everything I’m doing today will work on only the free version.

To start with, I’m only going to make a console application that just does some simple string manipulation. You can see the entire project in its completed state on GitHub here.

After I created the project, I had to right click the project and select Add PostSharp to Project. This added a reference to PostSharp’s .dll and set PostSharp up in my packages config. Now, we can start making our first aspect. I’m going to tackle the “low hanging fruit” of some very simple logging first.

I’m going to keep this very simple, so I’m just going to do Console.WriteLines instead of complicating this project by integrating a complicated logging framework just to show an example. I have a Utility class with a ReverseString method. In addition to the “business logic” of actually reversing the string, I am also writing out every entry and exit to and from the method.

public class Utility
    {
        public string ReverseString (string input)
        {
            Console.WriteLine("Entering ReverseString at {0}", DateTime.Now.Ticks.ToString());
            var inputArray = input.ToCharArray();
            Array.Reverse(inputArray);
            Console.WriteLine("Leaving ReverseString at {0}", DateTime.Now.Ticks.ToString());
            return new string(inputArray);            
        }
    }

Calling that method with some test data gives me this output:
Original Results

Now, every method I’d write, I’d have to dirty up with those WriteLines. It clutters up the code and makes it that much harder to understand. Let’s pull that out into an Aspect.

I add a plain C# class to my project called WriteLineAttribute.cs. The code for it is here:

using PostSharp.Aspects;
using System;

namespace IntroToAop1
{
    [Serializable] 
    public class WriteLineAttribute : OnMethodBoundaryAspect 
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("Entering {0} at {1}", args.Method.Name, DateTime.Now.Ticks.ToString());
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            Console.WriteLine("Leaving {0} at {1}", args.Method.Name, DateTime.Now.Ticks.ToString());
        } 
    }
}

Some things to point out. You have to mark the class as Serializable. This is just due to how PostSharp manages these things. Secondly, you just have to inherit from OnMethodBoundaryAspect. That is one of the built in Aspects that PostSharp offers for exactly what we want to do, operating coming in and out of methods. Now, to get my behavior, I just override the OnEntry and OnExit methods and put the Console.WriteLines in that I had before (making the method name dynamically generated from the arguments passed in to me).

Now, my ReverseString method looks like this:

[WriteLine]
public string ReverseString (string input)
{
    var inputArray = input.ToCharArray();
    Array.Reverse(inputArray);
    return new string(inputArray);            
}

The WriteLines are gone and I just added the [WriteLine] attribute at the top of my method. Running that gives me this output:
After Results

Okay, maybe this intro isn’t “blow your mind impressive”, but it does show you some of the power to make clean code that PostSharp offers you. If I wanted to log something new, I only have to change it in one place. If I wanted to make that logging come on and off based on a compile flag or a configuration value, again it is a single point of change. And the fact that my results are exactly the same (except for the timestamps) means that I had a successful refactor while cleaning up my code.

Again, if you want to play around with the code, you can find it on GitHub. I’ve added some more string manipulation methods just to further show how much nicer the code will look “PostSharp’ed”.

Next time, I’m going to use PostSharp to validate the parameters on my methods so that they don’t blow up when you pass in null values!