The Inquisitive Coder - Davy Brion’s Blog

Thinking outside of the typical .NET box

Archive for the 'PostSharp' Category


NHibernate and virtual methods/properties

Posted by Davy Brion on 24th May 2008

I love NHibernate but one of the things that bothers the hell out of me is that i keep forgetting to add the virtual keyword to each method or property in my entities. And since NHibernate needs your classes’ properties and methods to be virtual, this causes run-time errors when i run my tests. Since i’m already using custom compile time checks, i figured i might as well add another one… from now on, i want my compilation to fail if any of my NHibernate entities have public methods/properties that aren’t marked virtual.

Once again, it’s PostSharp to the rescue:

using System;

using System.Reflection;

 

using PostSharp.Extensibility;

using PostSharp.Laos;

 

namespace Northwind.Aspects

{

    [Serializable]

    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method | AttributeTargets.Property)]

    [MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Managed |

        MulticastAttributes.NonAbstract | MulticastAttributes.Instance |

        MulticastAttributes.Protected | MulticastAttributes.Public)]

    public class RequireVirtualMethodsAndProperties : OnMethodBoundaryAspect

    {

        public override bool CompileTimeValidate(MethodBase method)

        {

            if (!method.IsVirtual)

            {

                string methodName = method.DeclaringType.FullName + “.” + method.Name;

 

                var message = new Message(SeverityType.Fatal, “MustBeVirtual”,

                    string.Format(“{0} must be virtual”, methodName), GetType().Name);

                MessageSource.MessageSink.Write(message);

 

                return false;

            }

 

            return true;

        }

    }

}

And then we make sure this check is applied to my NHibernate entities:

#if DEBUG

[assembly: RequireVirtualMethodsAndProperties(AttributeTargetTypes = "Northwind.Domain.Entities.*")]

#endif

Now, whenever i forget to mark my properties/methods as virtual, i get this:


EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.RemoveTerritory must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.AddTerritory must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.get_Territories must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.set_Description must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.get_Description must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.set_Id must be virtual
EXEC : error MustBeVirtual: Northwind.Domain.Entities.Region.get_Id must be virtual

...

Done building project "Northwind.csproj" -- FAILED.

And there we go :)

Posted in NHibernate, PostSharp | No Comments »

Creating Sanity Checks

Posted by Davy Brion on 24th May 2008

Ever been in a situation where you notice that one of the team-members used classes from an assembly that really shouldn’t be used in that part of the code? For instance, accessing the data layer from the presentation layer. It’s not always easy to keep an eye on improper assembly usage. You could keep an eye on the referenced assemblies manually. You could write an FxCop rule that checks for disallowed assembly references. There’s a lot of stuff you can do, but it’ll always be an after-the-facts check. By that time, the ‘illegal’ code is already there.

Wouldn’t it be cool if you could break the compilation whenever a developer tries to build code that has improper assembly usage? Actually, with PostSharp, we can do just that. You can simply create an aspect like this:

    [Serializable]

    [AttributeUsage(AttributeTargets.Assembly)]

    public class SanityCheck : OnMethodInvocationAspect

    {

        public override bool CompileTimeValidate(System.Reflection.MethodBase method)

        {

            var methodName = method.DeclaringType.FullName + “.” + method.Name;

 

            var message = new Message(SeverityType.Fatal, “ProhibitedMethodCall”, String.Format(

                “Sorry, but we can’t allow you to call {0} from the current assembly”, methodName),

                “SanityCheck”);

            MessageSource.MessageSink.Write(message);

 

            return false;

        }

    }

First of all, we declare that the SanityCheck attribute can only be applied on the assembly level. Notice that we inherit from OnMethodInvocationAspect. This aspect is applied on events, properties, and methods. So basically, whenever you call a property or method or try to hook to an event in an assembly that you’ve applied this attribute to, our SanityCheck aspect will run. Well, actually we won’t get that far. We override the virtual CompileTimeValidate method where we display a message and then we return false. Meaning that this compilation is invalid.

Suppose you’ve used the attribute in the AssemblyInfo.cs file of your presentation layer like this:

[assembly: SanityCheck(AttributeTargetAssemblies = "System.Data")]

If you try to compile the following code:

            DataTable table = new DataTable();

            table.NewRow();

You’ll see the following line in your build output:

EXEC : error ProhibitedMethodCall: Sorry, but we can't allow you to call System.Data.DataTable.NewRow from the current assembly

And most importantly:

========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

Obviously, this will only cause compile errors when you try to touch the prohibited parts within the assembly where you used the SanityCheck attribute. If you call a method in another assembly that is allowed to touch System.Data, it will not cause a compile error.

Posted in PostSharp, Software Development | 2 Comments »

WCF Exception Handling with PostSharp

Posted by Davy Brion on 23rd May 2008

In your WCF service methods, you should always provide proper exception handling. The exception handling code is almost always the same, so it’s usually just copy/pasted in each method. Here’s an example of a typical service method:

        public void PersistOrder(Order order)

        {

            try

            {

                Container.Resolve<IPersistOrderHandler>().Handle(order);

            }

            catch (BusinessException b)

            {

                throw new FaultException<BusinessExceptionInformation>(new BusinessExceptionInformation(b),

                    new FaultReason(b.Message));  

            }

            catch (FaultException)

            {

                throw;

            }

            catch (Exception e)

            {

                Container.Resolve<ILogger>().LogException(e);

                throw new FaultException(new FaultReason(e.Message));

            }

        }

That’s a lot of code, even though only ONE line will differ from the other service methods in this service. Let’s clean up this mess, shall we? Exception handling is a cross cutting concern so we might as well put it in one place (at least, one place for each different kind of exception handling that you need). We’ll use PostSharp to define an ApplyServiceExceptionHandling aspect:

    [Serializable]

    public class ApplyServiceExceptionHandling : OnExceptionAspect

    {

        public override void OnException(MethodExecutionEventArgs eventArgs)

        {

            if (eventArgs.Exception is BusinessException)

            {

                throw new FaultException<BusinessExceptionInformation>(

                    new BusinessExceptionInformation(eventArgs.Exception as BusinessException),

                    new FaultReason(eventArgs.Exception.Message));

            }

            else if (eventArgs.Exception is FaultException)

            {

                eventArgs.FlowBehavior = FlowBehavior.RethrowException;

            }

            else

            {

                Container.Resolve<ILogger>().LogException(eventArgs.Exception);

                throw new FaultException(new FaultReason(eventArgs.Exception.Message));

            }

        }

    }

And now we can modify the earlier service method to this:

        [ApplyServiceExceptionHandling]

        public void PersistOrder(Order order)

        {

            Container.Resolve<IPersistOrderHandler>().Handle(order);

        }

That’s a lot cleaner than the previous version right? Actually, this service has more than one service method so we’re better off moving the ApplyServiceExceptionHandling attribute to the class level instead of the method level:

    [ApplyServiceExceptionHandling]

    public class OrderManagementService : IOrderManagementService

now we can get rid of all of the exception handling code in each service method, but each one will have exception handling applied to it because the exception handling aspect is applied to the class, and thus, to each method of that class. And if you need to modify your exception handling (to handle TargetInvocationExceptions with BusinessExceptions as InnerExceptions for instance?) you’d only have to do this in one place.

Btw, i’m aware of WCF’s IErrorHandler interface (which allows you to handle exceptions in a general manner as well)… i just don’t like it :)

Posted in Aspect Oriented Programming, PostSharp, WCF | 1 Comment »

Adding Behavior With PostSharp

Posted by Davy Brion on 21st May 2008

A little while ago, i talked about adding behavior to components using Windsor’s Interceptors. I wanted to try something similar with PostSharp, which is a very powerful Aspect Oriented Programming framework for the .NET world. Discussing everything PostSharp can do (which is a lot) is way beyond the scope of this post, so we’ll just focus on what i’m trying to do, and how PostSharp helps us with that.

In the previous post, i used a logging example… i didn’t want logging code mixed up with my real code, so i used a Windsor Interceptor to intercept calls to classes that i had configured to be logged. The interceptor would then log before and after the method calls were executed. In this post we’ll do something very similar, but a bit more advanced. We’re gonna write some tracing logic that will write a trace statement when the method is entered, along with the parameter values for each of its parameters. Then after the original method has executed, we’ll write a trace statement to indicate that we have left the method, and we’ll display the return value of the method as well, if there is one. That kind of tracing information can be very valuable, but writing that code is extremely tedious work. Nobody wants to do that, right? I sure as hell don’t.

We’ll use the following simple class as an example:

    public class Calculator

    {

        public int Add(int firstValue, int secondValue)

        {

            return firstValue + secondValue;

        }

 

        public int Subtract(int firstValue, int secondValue)

        {

            return firstValue - secondValue;

        }

    }

This calculator has a pretty limited feature-set, but we don’t need anything more for this example. Ok, so how do we add the tracing code without actually adding it to this code? We can just compile the code, and then we can have PostSharp inject some extra code to the compiled code. Sounds pretty hard, right? It is. But PostSharp Laos is a small framework that runs on top of PostSharp and it takes care of the hard work for you. PostSharp Laos offers some base classes which make it really easy for you to write your aspects (if you don’t understand that term, you should have clicked on the aspect oriented programming link earlier in the post ;)). There are a couple of approaches you can choose between, and they all have their pro’s and con’s. A nice overview of the different kinds of aspects you can inherit from can be found here. For this example, we’ll use the OnMethodInvocationAspect base class. This basically intercepts calls to methods and allows you to add some logic.

So what would our tracing aspect look like? How about this:

    [Serializable]

    public class TraceAspect : OnMethodInvocationAspect

    {

        public override void OnInvocation(MethodInvocationEventArgs eventArgs)

        {

            string methodName = GetFullMethodName(eventArgs);

            WriteOutput(String.Format(“Entering {0}”, methodName));

            WriteParameterInfo(eventArgs.Delegate.Method.GetParameters(), eventArgs.GetArgumentArray());

            base.OnInvocation(eventArgs); // calls the original method

            WriteOutput(String.Format(“Leaving {0}”, methodName));

            WriteReturnValueInfo(eventArgs.Delegate.Method.ReturnType, eventArgs.ReturnValue);

        }

 

        private static void WriteParameterInfo(ParameterInfo[] parameterInfos, object[] parameters)

        {

            if (parameterInfos == null || parameterInfos.Length == 0)

            {

                return;

            }

 

            WriteOutput(“With the following parameters: “);

 

            for (int i = 0; i < parameterInfos.Length; i++)

            {

                WriteOutput(string.Format(“{0} = {1}”, parameterInfos[i].Name, parameters[i]));

            }

        }

 

        private static void WriteReturnValueInfo(Type returnType, object returnValue)

        {

            if (returnType == typeof(void))

            {

                return;

            }

 

            WriteOutput(string.Format(“Return Value: {0}”, returnValue));   

        }

 

        private static string GetFullMethodName(MethodInvocationEventArgs args)

        {

            return args.Delegate.Target.GetType().FullName + “.” + args.Delegate.Method.Name;

        }

 

        private static void WriteOutput(string line)

        {

            Trace.WriteLine(DateTime.Now.TimeOfDay + ” “ + line);

        }

    }

So now we have a trace aspect which shows some valuable information about method calls… it shows when the method is entered, which parameters were passed in, when we leave the method and what the return value is.

So how do we apply this aspect to our code? We modify the definition of the Calculator class like this:

    [TraceAspect]

    public class Calculator

And then we compile… Well actually you have to add something to your project file so PostSharp can modify the compiled code, but since that’s covered nicely in the PostSharp documentation we’ll skip that step in this post. Anyways, when you compile this, you’ll get the following build output:

------ Build started: Project: UsingPostSharp, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:POSTSHARP;DEBUG;TRACE /reference:..\Libs\postsharp\PostSharp.Laos.dll /reference:..\Libs\postsharp\PostSharp.Public.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\UsingPostSharp.exe /target:exe Program.cs Properties\AssemblyInfo.cs TraceAspect.cs

Compile complete -- 0 errors, 0 warnings
“C:\mydocs\src\dbr\Experiments\UsingPostSharp\Libs\postsharp\PostSharp.exe” “C:\mydocs\src\dbr\Experiments\UsingPostSharp\Libs\postsharp\Default.psproj” “C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\UsingPostSharp.exe” “/P:Output=obj\Debug\PostSharp\UsingPostSharp.exe ” “/P:ReferenceDirectory=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp ” “/P:Configuration=Debug ” “/P:Platform=AnyCPU ” “/P:SearchPath=bin\Debug\, ” “/P:IntermediateDirectory=obj\Debug\PostSharp ” “/P:CleanIntermediate=False ” “/P:MSBuildProjectFullPath=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\UsingPostSharp.csproj ” “/P:SignAssembly=False ” “/P:PrivateKeyLocation= ”
PostSharp 1.0 [1.0.9.365] - Copyright (c) Gael Fraiteur, 2005-2008.

info PS0035: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ilasm.exe “C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.il” /QUIET /EXE /PDB “/RESOURCE=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.res” “/OUTPUT=C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\obj\Debug\PostSharp\UsingPostSharp.exe” /SUBSYSTEM=3 /FLAGS=1 /BASE=4194304 /STACK=1048576 /ALIGNMENT=512 /MDV=v2.0.50727
UsingPostSharp -> C:\mydocs\src\dbr\Experiments\UsingPostSharp\UsingPostSharp\bin\Debug\UsingPostSharp.exe

========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

If we use the calculator class like this:

            var calculator = new Calculator();

            calculator.Add(10, 15);

            calculator.Subtract(10, 15);

We’ll get the following trace output:

21:48:49.9414848 Entering UsingPostSharp.Calculator.~Add
21:48:49.9615136 With the following parameters:
21:48:49.9615136 firstValue = 10
21:48:49.9615136 secondValue = 15
21:48:49.9615136 Leaving UsingPostSharp.Calculator.~Add
21:48:49.9615136 Return Value: 25
21:48:49.9615136 Entering UsingPostSharp.Calculator.~Subtract
21:48:49.9615136 With the following parameters:
21:48:49.9615136 firstValue = 10
21:48:49.9615136 secondValue = 15
21:48:49.9615136 Leaving UsingPostSharp.Calculator.~Subtract
21:48:49.9615136 Return Value: -5

How nice is that? With some exception handling, better formatting and some clever indenting, this tracing aspect could be the only tracing code you’ll ever need from now on :)

So how does it work? Well, we can look at the compiled code in reflector for that. Here’s how the Add method looks like after PostSharp modified the code:

private int ~Add(int firstValue, int secondValue)
{
return (firstValue + secondValue);
}

[DebuggerNonUserCode, CompilerGenerated]
public int Add(int firstValue, int secondValue)
{
Delegate delegateInstance = new ~PostSharp~Laos~Implementation.~delegate~0(this.~Add);
object[] arguments = new object[] { firstValue, secondValue };
MethodInvocationEventArgs eventArgs = new MethodInvocationEventArgs(delegateInstance, arguments);
~PostSharp~Laos~Implementation.TraceAspect~1.OnInvocation(eventArgs);
return (int) eventArgs.ReturnValue;
}

As you can see, it’s renamed our Add method to ~Add, and it added another Add method which calls the OnInvocation method of our TraceAspect class with the correct MethodInvocationEventArgs. Pretty cool stuff IMO. Oh and btw, if you’re debugging this code in Visual Studio, you still only see your own code, with the original method name. While you step through it, the code runs just like it normally would, and the applied aspects are also executed. Very impressive.

If you use the OnMethodBoundaryAspect instead of the OnMethodInvocationAspect, you’ll see that the modified code doesn’t replace your method like it did here. But it will add a lot of extra code to it as well. All in all, there are a lot of possibilities here. If i’m not mistaken, i can now even use our TraceAspect and use it on classes in other assemblies, even if i don’t have access to them. We’ll look into that in a future post :)

Anyway, PostSharp is an extremely impressive piece of software which provides a whole lot of power and flexibility. You should definitely check it out and play around with it… i know i’m gonna be experimenting with it more often to see what kind of weird and cool stuff we can make it do :)

Posted in Aspect Oriented Programming, PostSharp, Software Development | 5 Comments »