My baby steps to PostSharp 1.0

So… you downloaded PostSharp 1.0 and you installed it and are wondering… “What’s next?”.

Well my friends, let me walk you through the first steps of PostSharp. What could we do that would be simple enough? Hummm… what about writing to a debug window? That sounds simple enough! Let’s start. So I created a new Console Application project and I added the reference to PostSharp.Laos and PostSharp.Public. As a requirement, the class must be tagged with “Serializable” attribute and implement OnMethodBoundaryAspect (not in all case but let’s start small here).

Next, I have a few methods I can override. The two that we are interested in right now is “OnEnter“ and “OnExit“. Inside of it, we’ll say which method we are entering and which one we are exiting. Here are my Guinea pig classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class FooBar
{
[DebugTracer]
public void DoFoo()
{

Debug.WriteLine("Doing Foo");
}

[DebugTracer]
public void DoBar()
{

Debug.WriteLine("Doing Bar");
}
}

[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public class DebugTracer : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{

Debug.WriteLine(string.Format("Entering {0}", eventArgs.Method.Name));
}

public override void OnExit(MethodExecutionEventArgs eventArgs)
{

Debug.WriteLine(string.Format("Exiting {0}", eventArgs.Method.Name));
}
}

See how simple this is? But… does it work? Let’s see the trace of calling each methods:

1
> Entering DoFoo         
> Doing Foo          
> Exiting DoFoo          
> Entering DoBar          
> Doing Bar          
> Exiting DoBar

Isn’t that wonderful? Compile execute and enjoy. But… what about the community you say? Of course if the tool is not open source there is probably nothing built around it, right? Wrong!

Here is a few resources for PostSharp that include pre-made attributes that are ready to be used:

That was everything I could find. Do you know any others?