We have refreshed PostSharp 2.0 CTP with a bunch of bug fixes and, most importantly, support for Visual Studio 2010 Beta 2 and .NET 4.0 Beta 2.
The PostSharp Add-In for Visual Studio currently don't work with Visual Studio 2010, but you should be able to build projects targetting all versions of the .NET Framework.
Note that the pipe server currently does not work with .NET 4.0.
PostSharp 2.0 CTP1 it out! You can
As you understood from my previous posts, PostSharp 2.0 is no disguised minor
upgrade. PostSharp 2.0 brings major innovations not only to the .NET community,
but also to the aspect-oriented programming (AOP) community in general.
The design objective of PostSharp 2.0 is to
provide a powerful, robust and supportable platform for build-time
aspect-oriented programming for the next 5 years, with high focus on
extensibility and well-definedness; PostSharp 2.0 is explicitely designed to
support multiple vendors of aspects so that ISVs can confidently distribute
aspects to their customers.
The principal new features of PostSharp 2.0 are the following:
That was for the hype.
Now, frankly. Put your expectations inline with this fact that it is the
first CTP. The objective of an early CTP is to deliver all risky features and
see if it works. Sure, we have hundreds of unit tests, and it works for us. But
there is a huge varierty of deployment conditions and source code structure in
the field, and it's something we'll never be able to fully reproduce in a lab.
What's Not There?
This is maybe as important as what's there. The following features are not in
the first preview but they will be there in a future preview.
- Conceptual documentation has not been updated. Class reference has been.
Please refer to the blog (links given above) for introduction.
- PostSharp SDK (PostSharp Core) is not a part of the release and is not
documented. Please do not use PostSharp Sdk with this CTP since next
previews will probably break your code.
- .NET 4.0 is not yet supported. Sorry for that. I know many of you are
looking forward for it. It'll be in next preview.
- Support for Compact Framework and Silverlight is not shipped with this
release. It will be enabled back in a future preview, and newer versions of
the platform will be supported.
When Will It Be Commercially Available?
Not before december; probably later.
Lenka, Jirka and others are working hard to deliver a brand new website.
Attorneys are at work to deliver license texts. And PostSharp 2.0 is far from a
release candidate anyway.
So please be patient and contact me for any commercial question.
So What's Now?
wrote when I gave the first indications about PostSharp 2.0:
You know how communication is like: people will blog about it, say it's
great (it is), and so on. I will do the same because I need to sell. But
don't forget we are first engineers and not marketers.
I want you to break the product. Find flaws. Find the weak element. Where
will the design break, when it will break? Compare the features to your
cases. Is there a case we could solve with a small design modification? We
will maybe not solve your use case in this release, but make sure the design
allows us to address the case in a future release. Nobody else than you,
knowledgeable of your particular business, can provide this feedback.
So download PostSharp 2.0 CTP1 and put it on the test bench. Discuss issues
on the forum and report bugs. You did a great job with PostSharp 1.0. Together,
we'll PostSharp 2.0 still better!
Let me finally discuss some changes in product packaging; they will are
important for performance and reliability.
Understanding the Build Performance Issue
Many people complained about PostSharp performance and wondered if the new
release would bring some improvement. The short answer is: yes.
The computing cost of PostSharp can be broken down into the following items:
- Initialization Time. It takes time to start a CLR
process, load assemblies in the AppDomain, JIT-compile code, and so on. For
long-running applications, you usually don't see the difference (we are talking of
tenths of seconds), but PostSharp is a process that is typically triggered
every couple of seconds, so this is really important.
- Processing Time. It's the time PostSharp takes to
analyze and process your code and dependencies. Here, I want to be very
clear: the code is extremely fast and very difficult to further optimize. PostSharp
is designed from ground to be fast. For instance, some say that PostSharp
parses the output of ILDASM. This is a myth; it is plainly false. PostSharp has a
super-fast binary module reader written in unsafe C# code and doing a lot of
pointer arithmetic (something I learned 15+ years ago on Turbo C 2.0).
- ILASM Time. Oh, yes. PostSharp relies on ILASM. This is
true. There are excellent reasons for that: it was much cheaper to implement
than a binary writer, has decent performance on Windows, makes it easier to
debug code generators, and provides an extra layer verifying generated code.
This was an excellent choice.
Therefore, there are 3 things we could do to improve build
- Improve initialization time. That's what we did in PostSharp 2.0. I'll
explain how below.
- Parallelize PostSharp processing. Ough. That's maybe the more difficult
since all threads would access the same object model concurrently.
- Writing an binary module writer instead of MSIL. This is doable at a
much lower cost than parallelizing. But even if we write a binary writer
some time, we will never scrap the ILASM back-end.
Improvement in PostSharp 2.0: Initialization Time
With PostSharp 1.5, you had to install PostSharp and generate native images
(ngen) to get decent initialization time. Otherwise, PostSharp was continuously
JIT-compiled and your build time suffered. The problem is we can't just tell people to
install PostSharp globally: in many teams, all build tools are checked in source
PostSharp 2.0 addresses this problem efficiently. First, it runs as a pipe
server. When a project needs to be built, the pipe server is started, and it is
stopped only after a long period of inactivity. So we don't have to continuously
load and unload PostSharp.
But we only won the half of the battle. Since PostSharp loads your executable
code and executes it (aspects are instantiated at build time), we need to create
a new application domain for each assembly being processed. So anyway assemblies
need to be loaded and JIT-compiled over and over again, unless... unless we host
the CLR and tell it that PostSharp assemblies, and all GAC assemblies, are
domain neutral. From this moment, they are loaded only once, and compiled only
once. Technically, hosting CLR means writing a half a dozen of COM classes in
C++ and somewhat tweaking an API that has been designed on-purpose for SQL
Server 2005, not for PostSharp.
The results: I have a test suite of 135 micro-projects I run in MSBuild
(that's part of the way you do unit testing of a build tool). The average execution time of PostSharp is the following (release
build, no ngen):
- Without Pipe Server: 1.21 s per project
- With Pipe Server: 0.94 s per project
- Difference: 0.22 s per project
So, theoretically, you should see some significant improvement if you have a
lot of small projects (to give you an idea, PostSharp still takes 10x more time
than the compiler itself).
In order to disable the Pipe Server, use the MSBuild property
PostSharp 2.0 finally solves the multi-platform problem. PostSharp 1.5 worked
fine with platform-neutral assemblies, but you had to tweak to support x86 or
x64 specific platforms. This is now addressed in PostSharp 2.0. The platform is
detected automatically, and the proper PostSharp process is started accordingly.
The same mechanism will allow a single distribution of PostSharp to target
both the CLR 2.0 and 4.0. Unfortunately -- and I will disappoint more than one
-- .NET 4.0 will not be supported in the first CTP. There are sometimes hard
choices to be done, and we preferred to deliver higher quality than more
features. Be patient! It's the next feature on the list. (I do confirm here that
.NET 4.0 will be supported in PostSharp 2.0 -- but not in its first CTP).
Another area of improvement: PostSharp 2.0 is more supportable than previous
versions. The installer (now a single package for both x86 and x64 platforms)
will contain two builds: release and diagnostic. Release is fast, but is not
able to trace and has no precondition checking. It's the version you use when
everything is right. When something goes wrong, build your project in diagnostic
mode: detailed logging will be available.
You can use the MSBuild property PostSharpBuild=Diag, or launch the PostSharp
We are working close with guys of Gibraltar Software
to make the support experience compelling. If you can't solve your problem
yourself (or if you think it's a PostSharp's bug), you can send us support
details, which we can then open using
Analyst. Actually, PostSharp integrates with Gibraltar, and
integrates with PostSharp. I have a long due post about that on my to-do
The way PostSharp 2.0 is started is significantly different than previously
and has several advantages:
- Build time improvement
- Reliability of the assembly search algorithm
- Diagnostic mode with comprehensive logging and support for Gibraltar.
So you are sold. You started using aspects in your new project. After many
months of development, the project gets larger and larger. You started with
rather simple aspects like tracing, but now your code is fully aspect oriented.
You have Resharped or DevExpress tool to help you navigate your code. But,
still, something is missing: you can't answer the following questions:
- How do I know to which code elements my aspect has been applied?
- How do I know which aspects have been applied to my code
That's why we developed the PostSharp Add-In for Visual Studio.
The first sign is a subtle difference on the splash screen of your favorite
Then a new item in the View menu:
Click on Aspect Browser and you'l have the answer to your first question. On the top of the new tool window, a list of all aspects
used in the current solution; in the bottom pane, a list of code elements to
which it has been applied. (Note that this works by reading a file written by
PostSharp build components, so you have to build the project to see something).
You can double-click on any code element in the tree and Visual Studio will open the corresponding
source code file and position the cursor at the proper location.
Now what with the second question? How do you know that a code element has been enhanced by an aspect?
Very simply: it is lightly underlined. Move your mouse cursor to that area and a tooltip will show you which aspects exactly
have been applied to this element.
Look at class Customer. The aspect EntityAspect is inherited from class Entity. How would you know this
without the plug-in, just by looking at the code?
And, yes, tooltips are clickable!
We in the Microsoft .NET community are lucky: at critical moments, we are a few steps
behind the Java community. So we got C# and .NET after them, but we learned from
their mistakes, and got better language and platform. The same with AOP. AspectJ is widely used
over there, there is
plently of feedback, and PostSharp has been designed accordingly.
One of the questions engineers face when applying aspects to large software
is: how do you ensure aspects don't collide? This was a key design concern for
PostSharp 2.0; here I'll show how it's addressed. Be confident that this
feature puts PostSharp at the peek of all industrial aspect weavers, without
distinction of language.
Let assume the following. We have two aspects: caching and authorization.
Obviously, we want authorization to be performed before caching.
I skip the code of the aspects. It's not the point here. But let see how we
define dependencies between aspects:
public class CacheAttribute : OnMethodBoundaryAspect
// Implementation omitted.
[AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.Before, StandardRoles.Caching)]
public class AuthorizationAttribute : OnMethodBoundaryAspect
// Implementation omitted.
It's fairly simple. There are only two concepts:
- Aspects can provide a role. A role describes the
function of the aspect; represented as a unique string. The class
StandardRoles is a list of the most common aspect roles you would find
in business applications. To name a few of them: caching, security,
persistence, validation, observabiltity, exception handling, transaction
handling, and so on. We specify this using the custom attribute
- Aspects can define relationships to other aspects.
Here, the custom attribute AspectRoleDependency specify a depedency
to other aspects that provide a given role. The custom attribute on
AuthorizationAspect just means: this aspect should be before any aspect
Now, if you apply two aspects on the same method, they will be ordered as you
public string GetQuoteDetailsHtml()
// Pretend we retrieve something large and confidential
// from database.
There are other ways than roles to match dependent aspects. For instance,
AspectTypeDependency allows you to specify an aspect type explicitely. All
dependency attributes are in namespace PostSharp.Aspects.Dependencies.
Expressing Aspect Conflicts
Let's take another scenario. I have a method, say ISecurable.IsUserInRole,
and I want to avoid at any price that this method gets cached.
Easy: we create an aspect NotCacheableAttribute with no logic at all
(the aspect does strictly nothing), and add a dependency:
class NotCacheableAttribute : MethodLevelAspect
Now apply it to our interface method. We use aspect inheritance to ensure
than the aspect dependency applies to all methods implementing this interface
public interface ISecurable
[NotCacheable(AttributeInheritance = MulticastInheritance.Strict)]
bool IsUserInRole( IPrincipal principal, string role );
Try to put a caching aspect on an implementation of this interface method:
class Organization : ISecurable
// Details omitted.
public bool IsUserInRole( IPrincipal principal, string role )
return accessList.IsUserInRole(principal, role);
Build the project; you'll get this error message:
Conflicting aspects on
principal, string role) : bool": 'Dependencies.Aspects.NotCacheableAttribute'
cannot be used together with 'Before Dependencies.Aspects.CacheAttribute (3)'
because the second provides the role 'Caching'.
And this is exactly what we wanted!
You maybe remember commutativity from school. Multiplication is commutative
because 5*4 = 4*5; division is not. And you maybe even remember
function composition, which combines two functions in one: (f o g)(x) =
f(g(x)). Functions f and g are mutually commutative if
f o g = g o f. If you have done a little more maths, you know that
commutativity applies to differential operators, so we have (in good cases):
d/dx o d/dy = d/dy o d/dx. And if you have done much more maths, you are
even maybe an ace in Lie
algrebra, which I never understood.
Just as with functions and differential operators, if makes sense to talk of
commutativity with aspects.
Say we have two aspects on the same method: tracing and exception handling.
Does it matter if one aspect executes after the other? If you don't care, then
these aspects are said to commute (in other words, they are mutually
commutative). If not, you have to specify their ordering specifically.
If two aspects are not commutative but are not strongly ordered
(because you did not specify an ordering dependency), you will get a nice
warning at buid time:
Conflicting aspects on "Dependencies.Entities.Quote/GetQuoteDetailsHtml()
: string": transformations "Dependencies.Aspects.TraceAttribute" and
"Dependencies.Aspects.AuthorizationAttribute" are not commutative, but they are
not strongly ordered. Their order of execution is undeterministic.
You have two ways to get rid of this warning: either your order them strongly
by aspecifying an order dependency (see above), either you specify that both
class TraceAttribute : OnMethodBoundaryAspect
// Details omitted.
You may ask -- why to bother, anyway? Well, because every professional knows
how hard it is to troubleshoot non-deterministic issues, PostSharp 2.0 carefully
detects these situations and warns about them. You can specify that your aspect
has no effect at all (therefore you would lie, since it does not make sense to
write an aspect that has no effect) and, therefore, it's like the function
commutes with any other aspect. But then you are supposed to have made an
educated choice (use the custom attribute WaiveAspectEffectAttribute
for this purpose).
Some Theory Behind
The theory behind shows that, while PostSharp Laos became popular quite
accidentally (PostSharp Core was well designed, but PostSharp Laos started as an
experiment), PostSharp 2.0 is really engineered to scale well in complexity and
to assume the burden of this popularity (be certain it is something we carry
both with pleasure and honor).
Before starting to execute transformations on a code element (say a method),
PostSharp gathers all transformations upfront. At this point, they form an
unstructured set of nodes. When this is done, PostSharp evaluates dependencies
between all transformations in the set. Ordering dependencies become edges in a
and form a partially
ordered set. Then, it performs a
on the graph to find out in which order transformations should be executed. A
part of this algorithm is to detect cycles, so you will get a build-time error
if two aspects have contradictory ordering requirements. Then, PostSharp checks
if it finds clusters of elements that are not strongly ordered. If it finds
some, it checks that all nodes in the cluster commute with all other nodes.
Finally, it checks if other dependency constraints (conflicts and requirements)
This complex algorithm is executed for every method, type, field, property,
or event that is the target of more than one aspect. Fortunately, the number of
aspects on a code element is typically small, so the performance cost is not
daunting in practice. Good news is that it scales in complexity.
Old Good Aspect Priority
"Where is my old AspectPriority property?" It's still there. You can
still specify a priority manually. The priority will be translated into a
dependency and will be merged with dependencies.
While using an aspect, you can always refind the dependencies provided by the
aspect developer. But you cannot break them. If you intend to do so, you will
introduce a circular reference in dependencies:
[Authorization("SalesManager", AspectPriority = 2)]
[Cache(AspectPriority = 1)]
Conficting aspects on "Dependencies.Entities.Quote/GetQuoteDetailsHtml()
: string": according to aspect dependencies, transformation "Before
Dependencies.Aspects.AuthorizationAttribute (4)" should be located both before
and after transformation "Before Dependencies.Aspects.CacheAttribute (3)".
Thanks to the topological sort algorithm, PostSharp is able to detect longer
dependency cycles and to enforce ordering even in complex situations.
I have shown how PostSharp 2.0 copes with mutliple aspects when they are
applied to the same code element. One word qualifies the approach: robustness.
Now you can safely use aspects in larger teams and projects. PostSharp is