Download demo project source code

Welcome to day 1 of learning PostSharp. This series will walk you through the features of PostSharp over the course of a few weeks. Each feature will be explored and used in a functioning project to give a better understanding of the examples.

This week we'll be using PostSharp to enhance a simple contact management application while giving you an introduction to some of the out-of-the-box aspect classes that PostSharp provides for us.

Getting started

You will need to download and install PostSharp and the demo project source code. For this series we will be using PostSharp

About the demo application

The demo application is a simple windows forms project that uses an in-memory data store. It features search, add, edit and delete functionality. Go ahead and run the application and play around with it.

The Problem

If you have not done so already, try doing a search for a name that isn’t in the list. You receive an error dialog. This exception is very cryptic and contains some sensitive information about the data layer.

Exceptions are great for debugging because they contain a lot of information that can be used to track down troublesome code and conditions. However, this can be a double edged sword. If you were exposing a web service or a web site to the public and exception data was allowed to bubble up to the user, it could be used for malicious purposes. Another case is that the end user doesn’t need to know very specific details about what happened, just that something went wrong.

The best practice in these cases are to capture the real exception, perform some actions on it (such as logging) and then throw a new, more generic exception.

The Fix

There are two places where we can handle this, the data layer and the UI. We want to handle it in the data layer. The reason why is because we don’t want to expose details to the other layers if we don’t have to. This point might seem lost on this simple demo, but in real world development, you might have many public consumers of a data layer so you have to consider what data is exposed.

Update the GetByName method in InMemoryDataStore.cs by adding a try/catch around the method body

public IQueryable GetByName(string value)
        var res = _contactStore.Where(c => c.FirstName.Contains(value) 
                    || c.LastName.Contains(value));

        if (res.Count() < 1)

        return res.AsQueryable();
    catch (Exception ex)
        //Log exception here
        throw new Exception("There was a problem.");

Run the application and try a search for a non-existent name. This time we get a dialog with a friendly message and none of the sensitive information.

A Better Way

Not only did we fix our problem, we also cluttered the method with at least 7 lines of code to do it and it isn’t reusable. If we wanted to apply the same fix to the rest of the methods we would need to add the same try/catch to each method.

Since this problem is a cross-cutting concern we can employ Aspect Oriented Programming. This is where PostSharp comes in.


PostSharp comes with an aspect class called OnExceptionAspect that is specifically designed for implementing exception handling policies. This is exactly what we need. Add a new file named DatabaseExceptionWrapper.cs and add the following code

public class DatabaseExceptionWrapper : OnExceptionAspect
    public override void OnException(MethodExecutionArgs args)
        string msg = string.Format("{0} had an error @ {1}: {2}\n{3}", 
            args.Method.Name, DateTime.Now, 
            args.Exception.Message, args.Exception.StackTrace);


        throw new Exception("There was a problem");

To use OnExceptionAspect, we simply inherit from it. OnExceptionAspect exposes a few virtual methods that we can override to gain access to certain events. Since we want to handle exceptions when they occur, we override the OnException method.

The OnException method is called when an unhandled exception occurs in the target method. PostSharp will wrap the target method in a try/catch where the code we provided will be placed in the catch.

Inside OnException, we build a string to hold some exception information that we will log. OnException provides us with a MethodExecutionArgs parameter that contains useful information about the current method and the exception that was thrown. args.Exception holds the exception that was thrown by the method so we can extract the details we need from there. We’ll cover more of MethodExecutionArgs later this week.

Applying an aspect

Now that we have it, we need to use it. PostSharp is flexible in how aspects can be applied. Today we'll go over the most direct way which is applying it to the target method declaration. Open the InMemoryDataStore.cs and navigate to the GetByName method. Remove the extra code we added before and add a [DatabaseExceptionWrapper] attribute to the method declaration.

public IQueryable GetByName(string value)
    var res = _contactStore.Where(c => c.FirstName.Contains(value) 
                || c.LastName.Contains(value));

    if (res.Count() < 1)

    return res.AsQueryable();

Run the application again and the result is exactly the same as it was before. The difference is that we now have a reusable and clean way to apply our exception wrapping solution to methods.

Since PostSharp is a Post-Compile processor, meaning it does its work after msbuild.exe has turned your C# into MSIL, it uses the attributes to determine the work that needs to be done. PostSharp will find the DatabaseExceptionWrapper attribute decoration on the GetByName method and then inject our code in the correct spots.


Another method that OnExceptionAspect exposes for us is GetExceptionType. The way OnExceptionAspect works is by wrapping the method in a try/catch block and catching exceptions of type Exception. But there will be cases when you want to handle a specific type of error.

A good example of this would be a connection time-out exception when making a call to a web service. Your exception handling policy for a connection time-out could be to wait and retry before giving up. But you only want to handle that specific exception, not all exceptions. This is where GetExecutionType comes in.

Implementing GetExceptionType is nothing more than returning the type you wish to handle. This method is called at build-time by PostSharp to determine how the try/catch block is going to be created.

Add the following code to our aspect class

public override Type GetExceptionType(System.Reflection.MethodBase targetMethod)
    return typeof(InvalidOperationException);

GetExceptionType is called at compile time by PostSharp to determine how to generate the try/catch. We’re telling PostSharp that it should build the catch clause to only handle InvalidOperationException types. If a different exception were thrown then our aspect would not cover it.

To add flexibility, you can declare an ExceptionType public property on the aspect that will allow the type to be set when the aspect is declared. The GetExceptionType method would only need to return that property.


How much time will you save by creating logging code once and then forgetting about it? Adding logging and exception handling to new and existing methods is now just one line of code and no clutter. Different aspects can be built to handle different scenarios and can be added and removed to any method in any combination with little or no development effort.


selfDustin Davis is an enterprise solutions developer and regularly speaks at user groups and code camps. He can be followed on twitter @PrgrmrsUnlmtd or his blog

Now that PostSharp 2.1 CTP 2 is out of the door, I’ll write more about individual new features. Let’s start with something easy: the NuGet package.

The PostSharp nuget contains everything you need to add aspects to an application. So not only does it contain the run-time library PostSharp.dll, but all the stuff you need to build the project, including the Visual Studio Extension.

Adding PostSharp to your application

It has never been easier to add aspects to your code:

1. Open the Add Library Package Reference dialog normally and search for a package named PostSharp. You may have to scroll down a bit because we just uploaded the package.


2. Click on Install :), accept license terms.

3. A few seconds after the installation completes, and only the first time you add PostSharp on your machine, PostSharp will ask you if you want to install the Visual Studio Extension (VSX). The VSX is an important help, so we highly recommend you to install it.


4. After the VSX has been installed, restart Visual Studio (again, you should do that only once per machine).

You can see a new page in the project properties. It means PostSharp is enabled for this project.


A lot of smart things actually happen behind this apparent simplicity. The installation process will:

  • Add a reference to the proper PostSharp.dll library. Ok, this is obvious, all NuGet packages do that. Currently, the package supports the .NET Framework and Silverlight.
  • Add a reference to PostSharp.targets so that PostSharp kicks in the build process.
  • Remove any reference to a previous version of PostSharp.
  • Check whether a previous version of the VSX is installed, and help you to uninstall it if applicable.

Installation in Source Repository

It has always been possible to install PostSharp into the source repository however, until this version, there were some inconveniences. In version 1.5, PostSharp ran much more slowly from source repository because its libraries were not ngenned. Version 2.0 mitigated this issue by providing a long-running process (pipe server), but you had to use the setup program to use the VSX.

Starting from version 2.1, you can even deploy the Visual Studio Extension (VSX) from the source repository. When a developer runs PostSharp for the first time on his machine, he will see a dialog box asking whether the VSX should be installed. When someone installs a newer version of PostSharp in the source repository, all developers are requested to upgrade the VSX. No administrative privilege is required. Everything happens in the user profile only.

Note that this feature is not bound to NuGet. You get the same if you use the zip distribution instead of the NuGet package.


NuGet is a very convenient way to install PostSharp. It provides a streamlined experience and does not require administrative privileges. But most importantly, it will allow third-party vendors and OSS projects to handle dependencies to PostSharp in a very easy way. If your project or product ships aspects, make it easy for developers: include PostSharp as a NuGet dependency.

We’re open to remarks and ideas. Please add a comment to the current post or a topic to the support forum.

Happy PostSharping!


I’m excited to announce the release of PostSharp 2.1 CTP 2, available for download from our web site and from the NuGet gallery. This CTP is mostly feature complete and has zero known bugs. It includes all fixes from the 2.0 branch.

If you’re not on a tight go-to-production schedule, it’s pretty safe to give this version a try now. Unlike with the previous CTP, we will be in “continuous delivery” mode and will be able to release hot fixes very quickly.

So what’s new in PostSharp 2.1? I’ll be blogging about individual features the next days. Here is a short summary:

  • Build-time performance improvement
  • NuGet packaging and improved no-setup experience
  • Extensions to the System.Reflection API
  • Architecture validation (constraints)
  • Support for obfuscation
  • Support for Silverlight 5
  • License management

Build-Time Performance Improvement

Most users will see some improvement in the build-time performance of PostSharp, but for some users it could even mean a 500% speed up. The main reason? We completely rewrote the last step of the PostSharp pipeline: writing the modified assembly back to disk. The previous implementation was based on ILASM, which scaled badly for very large assemblies. The new implementation is fully written in unsafe C# and is probably the fastest available. Other improvements are due to a better utilization of multiple cores, although PostSharp remains largely a single-threaded program. For details about this feature, see our CTP 1 announcement.

This feature is available on all editions of PostSharp.

NuGet Package and Improved No-Setup Experience

PostSharp 2.1 can now be added to your application directly from Visual Studio thanks to NuGet. No need to run a program with elevated privileges. No need to edit your project file if you want to put PostSharp in your source repository. Everything is done by the NuGet package installer.

You can now use the Visual Studio Extension (VSX) even if you don’t want to run the setup program. The first time you (or your colleague) will build a program using PostSharp, a dialog box will ask you whether you want to install the VSX. No elevated privileges needed. When you deploy a new version of PostSharp to the source control, all developers get the updated VSX.

Thanks to NuGet, it will become much easier for vendors and open-source projects to include a dependency to PostSharp. Our friends at Gibraltar Software already uploaded their application monitoring agent, and will soon update it to include the dependency to the PostSharp package.

This feature is available on all editions of PostSharp.

Extensions to the System.Reflection API

How many times did you want to get the list of all classes in your assembly deriving from System.Forms.Control? Sure, you can enumerate all types and build the index yourself, but it’s quite CPU expensive. Since PostSharp already computes this information internally, it seemed natural to expose it to the PostSharp.dll library. The PostSharp.Reflection.ReflectionSearch class offers methods that allow you to search for:

  • All custom attributes of a given type (or derived type);
  • All custom attributes on a given declaration (including those added through MulticastAttribute);
  • All types derived from a given class or implementing a given interface;
  • All methods, fields or types referenced in the body of a given method;
  • All methods using a given method, field or type in their body;
  • All types, methods, fields, properties, events or parameters referencing a given type.

Note that this functionality is only available at build time. This feature is available on the Professional Edition only.

Architecture Validation (Constraints)

Many people used “empty” aspects that just did one thing: validate the code. You now have a better way to validate your code: constraints (namespace PostSharp.Constraints). As aspects, constraints are custom attributes that you put on your code. They contain code that gets executed for every assembly referencing this code. The constraint logic typically queries the current assembly using reflection and the newly introduced reflection extensions, and emit errors or warnings to Visual Studio. Since your code can use LINQ, you have a very powerful toy to play with! PostSharp comes with off-the-self constraints:

  • [Friend], applied to an internal declaration, will raise an error if the declaration is used in a different namespace than the current one. It can be used to enforce isolation of components, and gives a level of visibility that stands between private and internal.
  • [InternalImplements], applied on public interfaces, will raise an error if the interface is implemented in a different assembly. Use this constraint when you need to expose an interface but don’t want the users of your API to implement it, because you want to reserve the right to add new methods to the interface. PostSharp SDK is full of such interfaces that can be consumed but not implemented.
  • [Internal], applied on a public declaration, will raise an error if the declaration is used in a third assembly. It can be used when you don’t want users to reference a part of the API, but have to make it public for technical reasons.

Note that architecture validation is disabled by default. You need to enable it in your project properties (“PostSharp” property page). This feature is available on the Professional Edition only.

Support for Obfuscation

Let me start with a disambiguation: PostSharp does not become an obfuscator with this feature. It just became compatible with some obfuscators.

In previous versions, you could get into serious problems if you tried to use PostSharp and any obfuscator in the same project. PostSharp relied on some metadata references that were broken by the obfuscator because of renaming, so you got runtime exceptions. This is obvious if, for instance, you had a field of type MethodInfo in your aspect. The method name was stored in the serialization stream and the obfuscator did not know how to modify it. There were other less obvious cases with aspects on generic methods.

PostSharp 2.1 can be made aware of obfuscators and write metadata references in a way that obfuscators can understand and modify. But the obfuscator has also to be aware of PostSharp.

We implemented support for Dotfuscator because it is the market leader and has a free edition that ships with Visual Studio. According to the feedback we get from this CTP, we will publish our specification so that other vendors can implement it if they are interested.

This feature is available on the Professional Edition only.

Support for Silverlight 5 Beta

PostSharp 2.1 supports Silverlight 5 applications. What to add? This feature is available on all editions.

License Management

First of all, we chose to rename the community edition to Starter Edition. We got too many questions whether the community edition can be used for commercial project. We hope the new name makes the answer clear: yes, you can use the Starter Edition in commercial projects, you will just enjoy less features than with the Professional Edition.

At SharpCrafters, our license enforcement policy is to trust the customer to respect the license agreement. That’s why there was no license enforcement in version 2.0. It was not just a priority. But we may have been too liberal by letting people deploy the license key in the source control: for many companies, it meant that nobody knew how many developers were using the product. We strongly believe in trust, but we think that we should provide tools for proper license management. So we did a few changes.

We chose to deprecate deployment of license keys through source control because we want some mental process to take place when a developer first starts using the product: he also needs a license. We provide a license metering solution: we will monitor how many people install the license on their computer, but we will never block them. If we that believe a license key is being used too many times, we will simply contact the one who purchased the license key and discuss a solution. But we trust you in first place. By requesting license installation by each user, we are just asking that every company maintains a record of who is using the software.

What if manual license bookkeeping is impractical? For these situations, we provide a license server (technically: a simple ASP.NET application backed by an SQL database). The license server maintains the list of leases and ensures that the license agreement is respected. It will send emails to the license administrator (or team leader, or whomever else) when new licenses should be acquired – and you will get a 30-day grace period to purchase them. We tried to make the license server a valuable tool for the customer. You are free to modify the underlying database at will if it makes sense. You as the customer are responsible for respecting the legal agreement and we trust you.

The license server will be available with a new type of licenses called corporate licenses, that will be available for a premium (likely +30% compared to the normal commercial license).

Upgrade Today

The upgrade is free for anyone. I am pretty confident of the quality of this release so it’s a great time for you to download it. Submit all your changes to source control, do the upgrade, rebuild, and run your unit tests. If it fails, shelve the changes and report the issue. We do a lot of internal testing, but we need your feedback to move quality of this release forward.

In the next days, I’ll try to blog about individual features of this release.

Happy PostSharping!