Tallan Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

PostSharp Logging and Fundamentals with C#

Before we start learning PostSharp we must understand the idea of Aspect Oriented Programming.

Aspect oriented programming, or “AOP”, is the programming style which allows the separation of distinct, independent functions. This inevitably increases code modularity and in turn drives towards cohesive functionality. We tend to classify these distinct functions as cross-cutting concerns due to the fact that they can “cut across” multiple abstractions in a program. These concerns classify the major parts of a whole application such as the business logic, data model or the user interface. These concerns could be broken down even further if need be. This high level of encapsulation is the central concept behind AOP.

Whereas PostSharp is simply the software development tool that reflects the concept of AOP. PostSharp offers the tools necessary to create a clean and concise piece of code in fewer lines than normal procedures. This is due to the fact that PostSharp’s method of operation can be categorized as a Design Pattern Automation tool, which is a tool that optimizes productivity of development teams and implements software based on patterns. The benefits to using PostSharp and Automated Design Patterns are that:

  1. Code will be cleaner
  2. There is less boilerplating/ Repeating code is eliminated
  3. Increase code abstraction and modularity
  4. Improves maintenance for performance tracking and debugging
  5. Lowers maintenance costs/ Risking Fewer defects
  6. More resilient code when adding and removing functionality
  7. Increases team productivity due to organized readability

With these benefits, PostSharp becomes a very simple yet versatile tool that applies to a wide variety of applications. Some great examples for using PostSharp are:

  • Application security
  • Application logging
  • Multithreading
  • Transactions
  • Event change notifiations
  • Etc.

The way PostSharp operates is through a type of event handler which are known as aspects. Some of these aspects include Method aspects, Exception aspects, Event Interception aspects, and Location Interception aspects where they are able to detect and interject code during the beginning /end of a method call, when an exception has been raised, whether an event has been raised, or whether getter or setter methods have been invoked, respectively. What is best about this functionality is that upon detection of one the events, PostSharp will know to call a portion of code before continuing operations. Yet the contents of these aspect methods do not need to be hardcoded into the actual code. This will help slim down the code overall and avoid repetition.

Getting Started
So to get started with adding PostSharp to our code, we must first assure that the extension exists on our computer. If PostSharp has not yet been install, a free version is available for download
here. Otherwise we can add PostSharp into our Visual Studios project by performing the following steps:

  1. Go to Solution Explorer pane and right click the desired solution
  2. Click “Manage NuGet Packages…”
  3. Search “PostSharp”
  4. Install PostSharp package
  5. Follow through the prompt
  6. Accept terms and complete installation

Note: It’s best to check your project reference to see if the installation process was successful.

To start coding in PostSharp we can begin by creating a single class. The class should contain something similar:

using PostSharp.Aspects;
namespace ...
public class MethodAspects : OnMethodBoundaryAspect
//Add Methods

The abstract class OnMethodBoundaryAspect is provided by the PostSharp.Aspects package and is necessary for the functionality behind PostSharp method aspects. As for the methods, what we want to add in next is the following:

public override void OnEntry(MethodExecutionArgs args)

Console.WriteLine("I'm using PostSharp!")

This method overrides the existing method from the OnMethodBoundaryAspect class and enables its contents to be called in the beginning of any function referencing our PostSharp class. To add this reference, we can either tag an attribute with the class name onto the top of specific method, the beginning of an entire class, or assembly level through an app config file. To tag PostSharp onto a method, add an attribute like so:

[MethodAspects] public static void main(string[] args) {
Console.WriteLine("Hello world!")

Doing so will output the following:

I'm using PostSharp!
Hello World!

As you can see there is no trace of the actual PostSharp code in the method with the attached attribute but, it performs the method as is the PostSharp method was hardcoded like so:

public static void main(string[] args) {
Console.WriteLine("I'm using PostSharp!")
Console.WriteLine("Hello world!")

Case Example
Another great example to use PostSharp in is exception handling, in particular the OnExceptionAspect class and the OnException method. The OnExceptionAspect class like the OnMethodBoundaryAspect class is an extension added by PostSharp but solely works with exceptions. What’s great with PostSharp as well is its ability to pull information regarding a certain method or class such as the name of the class of the method , or its parameters.

One of my assignments regarding PostSharp is exception handling. On an exception call, we wanted the information from the parameters to be pulled and displayed into a log. I created a recursive method which is able to not only pull parameter values, but also break larger objects down into primitive data values and label these them with their proper name and type. Here is the psuedocode:

public class ExceptionAspect: OnExceptionAspect
public override void OnException(MethodExecutionArgs args)
string s = string.Empty;
foreach (var param in args.Arguments)
s += GetParam(param, "");

private string GetParam(Object a, string param)
var props = a.GetType().GetProperties();
foreach (var propertyInfo in props)
param += propertyInfo.GetInformation();
param += GetParam(propertyInfo, param);
return param;

In conclusion, PostSharp is a great tool to use when needing to eliminate any boilerplates, separating concerns between distinct sets of code, to decorate and add functionality to code, and to help organize and slim down code for better readability. The installation process is seamless and the learning curve for the tool is very little, so the tool will be ready to use out of the box.

Learn more about Tallan or see us in person at one of our many Events!

Share this post:

2 Comments. Leave new

code is missing. I try to use your code example and getting error on “property” and “propertyInfo.GetInformation() ” as both are missing in your code sample.
Can you please share the complete code to implement Error Logging aspect using postsharp

Code snippet is as bellow:
param += propertyInfo.GetInformation();
param += GetParam(propertyInfo, param);

You need:

if (a.GetType().IsPrimitive)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>