Joydip Kanjilal
Contributor

How to program using PostSharp in C#

opinion
Mar 25, 20164 mins
Software Development

Take advantage of this popular AOP framework to seamlessly manage common functionalities like exception handling, logging, security, and transactions in your application

Aspect Oriented Programming (AOP) is a programming paradigm that enables you to define policies to seamlessly manage the cross-cutting concerns in applications. AOP can be leveraged to remove intermingled code, write cleaner code, increase code abstraction and modularity, reduce maintenance and development costs, and make applications more manageable and flexible. PostSharp is one of the most popular tools available that can be used to implement AOP in applications.

Getting started

To start using PostSharp, you may want to install the latest stable release using the Package Manager Console. Alternatively, you can install PostSharp using the “Manage NuGet Packages” window. To get started using PostSharp in your application, follow these steps.

1.       Open Visual Studio 2015.

2.       In the Visual Studio menu, click on File > New > Project.

3.       Select the Console Application template from the list of the project templates displayed.

4.       Save the new console application project with a name.

5.       In the Visual Studio menu, click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

6.       Search for the most recent stable release of PostSharp and click Install.

And that’s all you need to do for now. When prompted, select the project(s) you want PostSharp to be installed in and click OK. Once the installation is complete, you are ready to use PostSharp in your application.

Programming PostSharp

Once PostSharp is installed, you can get started using it in your application. To do this, you’ll need to create one or more aspects for your application to use. One way to implement AOP in your applications is through the use of attributes. Once your aspect has been defined, you’ll want to apply the aspect to your program through attributes.

In the Solution Explorer Window, select your project, right click, and add a new class named ExceptionAspect. Note that the aspect needed to handle exceptions in your application should derive from the OnExceptionAspect class of the PostSharp library. OnExceptionAspect includes a method called OnException that you’ll need to override to handle exceptions.The following code illustrates our custom exception aspect class.

[Serializable]

    public class ExceptionAspect : OnExceptionAspect

    {

        public override void OnException(MethodExecutionArgs args)

        {

            Console.WriteLine("Error occured at: "+

            DateTime.Now.ToShortTimeString() + " Error Message: "+

            args.Exception.Message);

            args.FlowBehavior = FlowBehavior.Continue;

            base.OnException(args);

        }

    }

Every aspect should be serializable — note the usage of the [Serializable] attribute in the ExceptionAspect class shown above. Now that the aspect is in place, you can apply it on one or more methods in your application using attributes. The following code snippet illustrates a sample method for applying the exception aspect just created.

[ExceptionAspect]

 public static void TestExceptionAspect()

  {

      throw new Exception("This is a test message");

  }

You can apply the custom exception aspect just created to one or more methods in the application — or even at the class level. If the aspect is applied at the class level, exceptions thrown by any of the methods of the class would be handled. PostSharp aspects can also be applied throughout the entire assembly. This feature is known as Multicast, and it can be applied to the target namespace by specifying the following statement in the AssemblyInfo.cs file:

[assembly: ExceptionAspect(AttributeTargetTypes = “IDGPostSharp.*”)]

“IDGPostSharp.*” in the above code snippet refers to all the types that are present inside the IDGPostSharp namespace.

The OnMethodBoundaryAspect class enables you to execute custom code before and after execution of a method. While its OnEntry method is executed prior to execution of a method on which the aspect is applied, the OnExit method is executed after execution of your method.  The following code listing illustrates how you can measure the execution time of a method using an aspect. The ExecutionTimeAspect class below derives the OnMethodBoundaryAspect class and overrides the OnEntry and OnExit methods.

 [Serializable]

    public class ExecutionTimeAspect : OnMethodBoundaryAspect

    {

        [NonSerialized]

        Stopwatch stopWatch;

        public override void OnEntry(MethodExecutionArgs args)

        {

            stopWatch = Stopwatch.StartNew();

            base.OnEntry(args);

        }

        public override void OnExit(MethodExecutionArgs args)

        {

            string method = new

            StackTrace().GetFrame(1).GetMethod().Name;

            string message = string.Format("The method: [{0}] took

            {1}ms to execute.",

                        method, stopWatch.ElapsedMilliseconds);

            Console.WriteLine(message);

            base.OnExit(args);

        }

    }

You can also tweak the OnExit method above to log the execution time of methods. Now that your aspect is ready to be used, it can be applied on one or more methods to retrieve the execution time.

[ExecutionTimeAspect]

public static void TestExceptionAspect()

{

   //Some code

}

You can learn more about PostSharp by reading the documentation.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author