Search This Blog

AOP with Enterprise Library Policy Injection Block

I used to think aspect oriented programming (AOP) is not a very useful idea because quite often it only saves few keystrokes but requires a massive configuration file. I only came to realise the true value of AOP recently when we have to convert 4+ million lines of legacy COBOL code to .NET with Microfocus’ Visual COBOL compiler. Manually adding exception handling and logging code to these existing COBOL subroutines will not only take a lot of time but also makes code merging task much harder later.

I started experimenting with the policy injection block in the Enterprise Library to see if it will make this job simpler. I tried to google for AOP and Enterprise Library tutorials but I found most tutorials on the web are either old (most were done using Enterprise Library 3) or over-complicated. Especially many of them use the Enterprise Library Logging Block to demonstrate the policy injection concept, which requires lots of configurations itself.

The policy injection in Enterprise Library is actually pretty easy to use and therefore in this tutorial I decided to demonstrate it with a simple custom call handler that requires no configuration. This is done so that you won’t be distracted by those extra settings in the App.config. Also, I’ll be using the Enterprise Library 5 configuration GUI editor, which looks quite different from the old one.

So let’s start with a basic console program with a simple interface IGreeter, which has a single operation SayHello:

public interface IGreeter
{
void SayHello(string to);
}

and a very basic implementation, which prints a hello message to whatever name that was passed in:

The implementation of the Invoke method should be pretty self-explanatory, it basically prints a before and after message around the method invocation. Check this link out if you would like to know more about how to implement the ICallHandler interface.

A couple of things to note about the ConsoleCallLogger class above. Firstly It needs to implement the ICallHandler interface and have the ConfigurationElementType class attribute. Following assembly references needs to be added to the project in order for Visual Studio to resolve these classes:

Microsoft.Practices.EnterpriseLibrary.Common

Microsoft.Practices.Unity.Interception

System.configuration

Secondly, a custom call handler class is required to have a constructor that accepts a NameValueCollection argument. As you’ll see when we start configuring the App.config file, you can pass name/value pair values to the custom call logger from the configuration file.

Now, to apply the ConsoleCallLogger to the SayHello method, we need to configure the policy injection block with app.config. Before we start let’s have a look what the file will look like at the end (note: I have added space in class names so it will wrap properly):

Other than the ugly long class names, it's not too bad is it? You can pretty much just code this up by hand. However, since the enterprise library comes with a configuration editor, let's make use of it.

First of all we need to add a policy injection settings block in our file:

Next, right click on the policy injection block heading (“My Custom Logging” in my example) and add a member name matching rule block.

Enter our our target method name SayHello into the member name match field.

This will popup a dialog box and if you choose “Add From File”, you can then select the location of the DLL that contains the ConsoleCallLogger class. After selecting the DLL, the ConsoleCallLogger class should show up on the tree control as shown below:

I did run into few problems when I was adding my DLL. Here are some tips if you run into problems too:

Check your build settings, if you are using 64-bits EntLib configuration editor you should build 64-bits DLL too.

Check your class, is it public? did you implement the ICallHandler interface? did you remember to add the ConfigurationElementType attribute? and did you pass typeof(CustomCallHandlerData) to it?

Save and restart your configuration editor. I think there might be some bugs in the configuration editor because the first time I did this I just couldn’t get the ConsoleCallLogger class to show in the tree control no matter what I did. I end up saving and restarting a couple of times and eventually it came up.

After the call handler has been added, your setting should look something similar to this:

Now, save the app.config to the console program and add it to the project. To enable policy injection block in the console program, we first need to add following assemblies to the project:

Microsoft.Practices.EnterpriseLibrary.PolicyInjection

Microsoft.Practices.Unity.Interception

CustomCallHandlers (the DLL that contains the ConsoleCallLogger class).

Next we need to replace the direct object instantiation:

var greeter = new Greeter();

with PolicyInjection.Create in the Main method:

var greeter = PolicyInjection.Create<Greeter, IGreeter>();

If everything’s been configured properly, when you run the console program it’ll show the following output:

Before SayHello
hello bob
After SayHello

As you can see, the ConsoleCallLogger class has been magically applied to the SayHello method.

AOP is a very useful technique if you have to extend some legacy code without actually having to touch those code. Enterprise library already shipped with a few useful call handlers for common cross cutting concerns such as the logging and security. If none of them fits your needs you can always follow what I did in this tutorial and write your own call handlers.

Finally, you can download codes in this tutorial with the SkyDrive link below:

You say 'AOP is a very useful technique if you have to extend some legacy code without actually having to touch those code', but detail a step where the original code is edited. Inserting 'var greeter = PolicyInjection.Create();'. Is there truly a way to apply Unity without modifying the code which you are advising (like with AspectJ or PostSharp)?

Post a Comment

Popular posts from this blog

Following my previous post about using JMeter to test MOSS, I tried to figure out what are the bare minimum requirements of using JMeter against a plain ASP.NET website. I wrote a very simple ASP.NET web application with just a button, a text fields and a static label. This application displays the content of a text file in the static label when it loads and write content of the text field back to the file when the button is clicked.I found all I need to do in order to script this using JMeter is to extract __VIEWSTATE and __EVENTVALIDATION fields then send them back in the update request. My JMeter test plain looks like this:

I have used JMeter for load testing few non-ASP.NET web sites before, however I could not get it to work with ASP.NET web sites. This is mainly due to ASP.NET ViewState and event validations, which stops a recorded JMeter script from being played back.Recently I worked on a MOSS project and we were looking for tools to perform load testing on the server. Many people said the load testing tool in Microsoft Team System for Testers works well with MOSS. However, it is quite expensive so I decided to give JMeter another go. After several hours of hacking, I actually got it to work and here’s how I did it.My test page is the pretty standard MOSS edit document property screen with few extra text fields added and the goal here is to use a JMeter script to change the document properties. Once I have a working script, I can configure JMeter to fire hundreds of instances of this script simultaneously to simulate the user workload.As shown in the screenshot below, the test plan contains two HTTP…

As I have mentioned in the last tutorial, you use edited fields in COBOL to format data fields into human-readable display strings. Let’s start with a numeric field:01 NUMERIC-FIELD PIC 999999V99.and some COBOL code that set and display the field value:MOVE 1234.5 TO NUMERIC-FIELD.
DISPLAY NUMERIC-FIELD: ' NUMERIC-FIELD.As we’ve demonstrated in the previous tutorial, unused digits are padded with ugly zeros:NUMERIC-FIELD: 001234.50Let me put my C# programmer hat on again (apologies to Java, ruby, python, C/C++, assembly and many other programmers who don’t like C#), when we have to format a variable for display, we often use the string.Format method with a formatting string containing special formatting characters, which is “0,0.00” in the following example:// returns 1,234.50
string.Format("{0:0,0.00}", 1234.5)Now let’s come back to COBOL, an edited field is basically a normal COBOL data field with a formatting string in the picture clause instead of the “A”, “X” or “9”…