Last Thursday our good friend Matthew Groves delivered part 1 of his 5-part live webinar series on AOP in .NET. He has a new book coming out next month called Aspect Oriented Programming in .NET from Manning Publications and the series will cover some of the practical AOP insights found in his book and a variety of real-world coding examples using PostSharp.
In part 1, Matt does an excellent job of demonstrating the basics of Aspect-Oriented Programming, including a number of live coding examples using ASP.NET and PostSharp – all in under 30 minutes.
Q&A
Q: Can you provide any hints on unit testing with aspects involved?
A: We’re going to talk about unit testing aspects – unit testing code that aspects are applied to – in part 5 of this series [May 30th]. In fact, I have dedicated an entire chapter of my book to unit testing aspects.
Q: Is PostSharp the only AOP framework covered in your book?
A: My book is focused on AOP in .NET and PostSharp is a large part of that but I cover other .NET tools like Castle DynamicProxy and the ASP.NET examples [shown in the video]. The idea is that once you learn the principles of AOP, you will be comfortable using tools other than what’s covered in the book. So anything you learn about PostSharp or Castle you can apply to other frameworks as well.
I will be adding new recordings each week but, if you want to catch them live and have the chance to ask Matt any question you may have about AOP in .NET and/or PostSharp be sure to sign-up for the series and join us every Thursday throughout the month of May.
Mark your calendar for Thursdays in May as we kickoff a new series of live webinars with our good friend, Matthew Groves.
Matt is a developer with over 10 years of professional experience in education, consulting, and product development. He concentrates on web applications, using C# with ASP.NET, JavaScript, and PHP.
His new book Aspect Oriented Programming in .NET from Manning Publications debuts in June and we’ve put together a 5-part webinar series that will give you a taste of the practical aspect-oriented programming insights found in his book and a variety of real-world coding examples as implemented by PostSharp.
Read on to learn more about the upcoming schedule and a special offer from Manning Publications.
Sign-up for the PostSharp live webinar series today >>
SCHEDULE:
1) You May Already Be Using AOP
Thursday, May 2nd at 9:00 AM PDT |12:00 PM EDT | 4:00 PM GMT
Learn the basics of Aspect-Oriented Programming and see live coding examples of AOP frameworks that come with ASP.NET. We will also look at how to write a simple PostSharp aspect using a pattern that is similar to the ASP.NET framework.
2) Call This Instead: Intercepting Methods
Thursday, May 9th at 9:00 AM PDT |12:00 PM EDT | 4:00 PM GMT
One of the most common types of aspect is the method interception aspect, which runs a piece of code instead of the intended method. In this episode, we will look at a real-world application of the method interception aspect that can help with data transactions.
3) Before and After: Boundary Aspects
Thursday, May 16th at 9:00 AM PDT| 12:00 PM EDT | 4:00 PM GMT
A PostSharp method boundary aspect can execute code at its borders (e.g. before a method, after a method, on exception). In this episode, we will look at a real-world application of a method boundary aspect to help with caching.
4) Under the Hood of a Post-Compiler
Thursday, May 23rd at 9:00 AM PDT| 12:00 PM EDT | 4:00 PM GMT
The details of how a post-compiler like PostSharp works can be complex, but it's important to have a basic understanding of what's happening in order to make an informed decision about where and when to use it. In this episode, we will look at how to decompile a .NET assembly and view code with/without a PostSharp aspect with ILSpy.
5) Unit Testing and Thin Aspects
Thursday, May 30th at 9:00 AM PDT| 12:00 PM EDT | 4:00 PM GMT
The benefits of unit testing are numerous. When aspects are involved, keeping those aspects "thin" is a key to keeping your code easy to unit test. In the final episode we will explore some of the implications of unit testing when a post-compiler tool is involved.
SPECIAL OFFER:
Now there's even more reason to attend Matt's webinar series. The generous folks at Manning Publications are offering a big discount on AOP in .NET to all live webinar attendees. Seats are limited and this series is sure to sell out so reserve your spot today.
If you want to learn what difference AOP and PostSharp can make in your projects, and take advantage of Manning’s special discount offer, join us every Thursday throughout the month of May.
Reserve your seat for the PostSharp live webinar series now >>
Join us tomorrow, September 27th, for the next PostSharp Live Webinar when our guest will be Joe Kuemerle.
Joe is a developer and speaker in the Cleveland, OH area and specializes in .NET development, security, database and application lifecycle topics. He is currently a Lead Developer at BookingBuilder Technologies, a leading software innovator for the travel industry.
Tomorrow, Joe will show how the clutter of logging, security checks, exception handling, implementing INotifyPropertyChanged and much more can be purged from your methods with Aspect Oriented Programming (AOP) techniques.
Reserve Your Webinar Seat Now >>
During the webinar you will learn:
- Why cluttered code is a pervasive problem in software development.
- What AOP is all about, how it works and how to use it effectively.
- How AOP tools like PostSharp make applications more readable, better organized and easier to maintain.
- How to implement Logging and INotifyPropertyChanged automatically with PostSharp Toolkits.
If you've ever wondered what difference AOP and PostSharp can make in your projects, and want to gain more insight into how PostSharp Toolkits make short work of boilerplate code, be sure to attend tomorrow’s live webinar.
Space is limited
Reserve Your Webinar Seat Now >>
Last month Karol Waledzik, a software architect and team lead at Internetium, wrote a 2-part blog post about the pain WPF and Silverlight developers experience by having to manually implement change notifications.
He debuted the PostSharp Domain Toolkit and wrote about the pain it alleviates by automatically handling (nearly) all standard business cases and generating exactly the right notifications, at exactly the right time.
Last week he demoed the toolkit during a live webinar, showing how it makes short work of change notification pain for developers and sharing details on its inner-workings.
Watch the recording and learn:
- Why previous attempts to tackle INotifyPropertyChanged by other libraries fell short
- What makes the Domain Toolkit different from other libraries
- How the toolkit automates change notifications
- What other scenarios the toolkit supports automatically
- The limitations of the toolkit and available customization
The recording below includes the entire webinar plus Q&A session where Karol answered questions from the audience about the toolkit, the scenarios it currently handles and those still planned.
If you have additional questions about the Domain Toolkit, don’t hesitate to connect with our Support Desk for fast answers. If you’d like to take it out for a test drive, simply install the NuGet package.
Happy PostSharping!
-britt
This is a guest post by Alessandro Federici. Alessandro is a System Architect at CODY Systems, an industry leader in the collection, analysis, and sharing of critical data for public safety, law enforcement, and intelligence agencies in the United States for over 30 years. CODY Systems specializes in integrated public safety software solutions and interoperable vendor-neutral information-sharing for First Preventers.
Occasionally we’re asked by teams that are evaluating PostSharp to provide examples of organizations using it in real-world scenarios. I understand the request completely. It’s one thing for teams to try a new product that’s backed by loads of documentation and tutorials, but learning how companies from a variety of different industries are using it to successfully produce cleaner, more efficient, code builds trust in a way no other document can.
In the past, we’ve pointed to success stories such as FullArmor, Siemens Audiology, Thales Information Systems and IdeaBlade. In today’s post, Alessandro shows how he and his team at CODY are using PostSharp in a variety of ways to reduce code clutter, handle errors, simplify what they write and make their code more readable.
Enter Alessandro
My interest in Aspect Oriented Programming (AOP) started in 2005, approximately. At the time I was working at RemObjects Software (I was one of the two founders) and we had recently started the development of our compiler. The engineers behind it planned to natively support AOP. I didn't know anything about aspects at the time, but the moment I saw and had a chance to use them I got hooked and I realized their elegance and power. In a way, I think I had the classic "how could I live without them?" moment where you lean back on your chair, stair at the monitor and question decades of your (programming) life.
Years then passed. I left RemObjects Software and I am now System Architect for CODY Systems where we develop applications using exclusively C#. As a Delphi/Oxygene old-timer, I had my moments with C# but I came to love it. Yet, the lack of native AOP features has always bothered me. To use a parallel example, adopting aspects feels like adopting lambda expressions and Where() calls: Once you start using them there's no going back to for-i loops that embed if statements. It gets you to the same end-result, but it just feels and reads sloppy, to me.
A client-tier rid of unnecessary code
CODY is currently working on major enhancements of the infrastructure and picked some of the best-of-breed tools for .NET. PostSharp is definitely one of them and will play a large role in our re-factoring and re-engineering efforts.
Our system is built off of different modules and follows some of the common multi-tier design patterns. We have a client tier, an application-server tier and a data-storage tier. The client-tier is made off of different client applications: Some are written using WPF, one is in Silverlight and others use MVC, depending on the need.
Our WPF and Silverlight clients are all built using the MVVM pattern where the INotifyPropertyChanged interface plays a fundamental role. This is the first place where PostSharp will greatly help us re-factoring leaner and cleaner code. Currently we have hundreds of properties that explicitly fire notification events with code such as this:
public string FirstName
{
get { return _firstName; }
set { ChangeAndNotify(value, ref _firstName, () => this.FirstName); }
}
We have put effort into alleviating the most common problem with INotifyPropertyChanged: We don't use error-prone, "magic" strings to reference property names and we have code snippets that help writing that code. Still, in the end, we continue to have hundreds of lines of code that have nothing to do with business logic and only exist to address what is, in most cases, just a user interface concern.
Thanks to PostSharp, all that baggage will go away and we will be able to use automatic properties where possible and concentrate on the business logic associated to the property.
The code above can now turn into the following:
[NotifyAspect]
[CapitalizeNameAspect]
[StringLength(1, 100)]
public string FirstName { get; set; }
This new code (which is also one line shorter) does everything the previous one was doing but also adds two new extra “business” operations. It's more readable and directly communicates the intent behind FirstName.
I also compared the amount of bytes the old code and new code took on disk: The new code is less than half of what it used to be. I could also give the new code to non-developers who would have a chance to understand what they got, finally!
But there's more we can do, thanks to the fact PostSharp aspects are implemented through attributes.
Self-documenting validation aspects for a discoverable and rock-solid server-tier
One of the modules of our system generates HTML documentation by using reflection. Any time we add a new domain object, new documentation pages get dynamically generated and provide an English description of all its properties, along with their constraints and other useful information. The data annotation StringLength displays as “The length of FirstName must be between 1 and 100”. CapitalizeAspect displays as “The value assigned to this property will be automatically capitalized”. NotifyAspect only displays when it's not attached to a property, as a reminder of a special case.
In other words, aspects allowed us to first add and later infer behavior through the use of simple attributes. All that without having to maintain two separate documents containing such information: the code and manual text just for help files.
This feature is critical for our application server tier. CODY's application server has been openly accessible for years, through simple HTTP calls and XML messages. It's a very important part of our infrastructure for many different reasons. The features we are now adding make this tier much easier to understand, use and test and the self-documenting aspect is of paramount importance in all this.
This brings us to the next use of PostSharp: ServiceMessageHandlerAspect. Our API layer is composed of services whose methods receive one request and return one or more responses. For instance, our sample CalculatorService is coded as:
[Description("Performs simple mathematical calculations")]
public sealed class CalculatorService
{
[...]
[ServiceMessageHandlerAspect]
[Description("Sums two integer numbers")]
public SumResponse Sum(SumRequest request)
{
return new SumResponse()
{
Result = request.A + request.B
};
}
}
SumRequest is coded as:
[Description("A message that contains two operands (A and B) for a sum operation.")]
public class SumRequest : ServiceRequest
{
[...]
[Required]
[Range(0, 1000000)]
[Description("Number A")]
public int? A { get; set; }
[Required]
[Range(0, 1000000)]
[Description("Number B")]
public int? B { get; set; }
}
The implementation of CalculatorService.Sum() only returns a result with the sum of A and B, but ServiceMessageHandlerAspect does a lot more for us, behind the scenes. When this aspect is applied to a method, validation code ensures that all the data annotations bound to SumRequest are satisfied (e.g. A and B are not null and their values are between 0 and 100000) before letting the flow get into the Sum() implementation. If any requirements are not met, the execution of Sum() is skipped and a SumResponse containing error information is returned to the caller.
In other words, by using this aspect and by defining solid request classes with validation attributes, we can be sure that whenever our service methods are called, their request argument is well formed and contains everything that is needed for it to be processed.
Among the same lines, responses can also contain validation attributes. ServiceMessageHandlerAspect ensures that whatever output is generated by the method matches such requirements.
Uniform and standardized access to 3rd party products through exception wrapping
Finally, we have another aspect that greatly helps us in error management: The WrapExceptionsAspect.
Like I mentioned before, we picked a number of the best-of-breed tools for the development of our core. We have queuing and caching integrated in the core, for scalability purposes. While these products are very solid and unlikely to disappear from the market, we abstract them and access them only through interfaces. What we cannot abstract easily are the errors these products return. Some might have their own exception types while others might use standard .NET Exception classes. What we wanted, in our wrappers, is to be sure that whenever an error occurs in the current cache implementation, we always get back a CacheException (which then embeds the original exception).
The following code shows how we use the WrapExceptionsAspect:
public abstract class BaseCache : BaseDisposable, ICache
{
[..]
[WrapExceptionsAspect(typeof(CacheException), null)]
void ICache.Store(string key, object value, int? maxMinutes)
{
if (!InternalStore(key, value, maxMinutes))
throw new CacheException(string.Format("Cannot store item [{0}] in the cache", key));
}
[..]
[WrapExceptionsAspect(typeof(CacheException), null)]
bool ICache.TryGet(string key, out T value, int? maxMinutes)
{
return InternalTryGet(key, out value, maxMinutes);
}
[..]
}
The above could have been easily accomplished by using a try...catch block around the calls to the Internalxxx methods but that would have meant having that extra code in each of the methods above and in any of the other wrapper classes we have (e.g. Queuing, etc.).
If we were to change how exception interception worked we would have had to touch every method. With the aspect we built we can be sure that there's one place to touch and all our wrappers immediately change.
Conclusion
Any piece of code that performs a function can be written in infinite ways. Many of such implementations will work and will produce the same results, but I strongly believe the result is not all that matters. How you achieve your goal is, many times, just as important. If a certain implementation is hard to read, understand or modify, it will cause problems down the road. Using aspects helps reducing clutter in code. It helps simplifying what we write and, later, what we read. It's a very elegant, simple and effective way to write code that focuses on the real problem, not language or framework needs.
Join us on Thursday, September 13th, for the next PostSharp Live Webinar when our guest will be Karol Waledzik from Internetium.
Karol is the software architect and team lead at Internetium in Warsaw, Poland, and is largely responsible for building our new line of PostSharp Toolkits.
He wrote a 2-part blog post last month about the pain most WPF developers experience by having to manually implement change notifications, and how the Domain Toolkit, the latest addition to our product family, automates this for (nearly) all standard business cases.
On Thursday’s live webinar, Karol will walk you through the PostSharp Domain Toolkit and show how it treats the implementation of INotifyPropertyChanged seriously and finally ends change notifications pain for WPF developers.
During the webinar you will learn:
- Why previous attempts to tackle INotifyPropertyChanged by other libraries fell short
- What makes the Domain Toolkit different from other libraries
- How the toolkit automates change notifications
- What other scenarios the toolkit supports automatically
- The limitations of the toolkit and available customization
If you're tired of having to manually implement INotifyPropertyChanged in WPF applications, and want to gain insight into how the PostSharp Domain Toolkit can end change notification pain in your own projects, be sure to watch Thursday's live webinar.
Space is limited.
Reserve your Webinar Seat Now >>

Our never-ending mission to spread the word about using PostSharp to produce cleaner code finds Gael and I in the good ole U.S. of A. for a week of presentations at user groups and businesses in Ohio and Michigan.
Joe Kunk first contacted us about the idea earlier this year and, together with the undying help of David Giard, we were able to build a tour that combines 4 user groups, 3 businesses, and 1 university over a 5 day stretch of interstate travel.
We sprinkled-in some customer visits for good measure, and added an extended layover at TechEd Europe on the way back to Prague and voilà: the perfect summer tour.
Gael has two presentations prepared for the tour:
- “Multithreading Beyond the Lock Keyword.” Dusting-off low-level synchronization primitives, Gael shows how to design programs that make better use of multiple cores. Because playing directly with low-level primitives can be overly complex, you’ll discover how large-scale multi-core software can be simplified using design patterns and how some these patterns can be ultimately simplified using aspect-oriented programming.
- “Intro to Aspect-Oriented Programming (AOP) with PostSharp.” Gael speaks about the problem with conventional programming, gives a gentle introduction to AOP with PostSharp, demonstrates how it works and why you should use it to eliminate scattered, tangled and coupled code from your codebases.
We’re excited to connect with user group leaders, members, and area businesses in Cleveland, Toledo, Detroit and Lansing. We look forward to learning about your current projects, the insight you provide about the solutions you’re looking for, and any feedback you can give about how you’re using PostSharp and our new toolkits.
Tour dates and locations include:
TechEd Europe promises to be one of the summer highlights, connecting us with new and old friends alike. Many thanks to Sara Faatz and the DevExpress team for their generosity. We’re very excited to get to know you and your team better. To our old friend Brady Gaster , who will be in Amsterdam to support the Azure team and participate in some breakout sessions, our apologies in advance to your liver.
If you find yourself in Ohio or Michigan next week, or attending TechEd Europe 2012 at the end of the month, please don’t hesitate to contact me to arrange a meet-up. Here’s to another wonderful summer!
Happy PostSharping!
-britt
p.s. – check out our Community page to find other opportunities to learn about PostSharp this summer.

We’ve got great news for those of you who have been waiting patiently for a PostSharp online training course to become a reality:
Pluralsight, the online training provider for hardcore developers, announced this week the availability of the PostSharp Fundamentals course authored by senior software developer, trainer, and PostSharp MVP – Donald Belcham.
The course is an introduction to using PostSharp and covers all the fundamentals needed to effectively use it to create basic aspects in your applications. The course includes:
- Introduction (Why and How to use Aspect-Oriented Programming)
- Installation (EXE & MSI, NuGet, Source Control, License Management)
- Out of the Box Aspects (OnMethodBoundaryAspect, OnExceptionAspect, EventInterceptionAspect, etc.)
- Aspect Lifetime (Compile Time, Serialization & Deserialization, Run Time)
- Existing Codebases (Approach, Attaching Aspects, Side Effects, Low Hanging Fruit)
- Deployment (Deployables, Signing Assemblies, Obfuscation)
- Developer Experience (Debugging, IDE Enhancements)
Many thanks to Aaron Skonnard and his team at Pluralsight for continuing to deliver quality online training from some of today’s leading .NET developers. Also a big congratulations and thanks to our good friend Donald Belcham for his continuing efforts to spread the word about the benefits of using PostSharp for AOP.
Watch Donald’s PostSharp Fundamentals course on Pluralsight >>
Join us on Thursday, February 23 at 9:00 AM PST | 12:00 PM EST | 5:00 PM GMT for the next PostSharp Live Webinar when our guest will be Ward Bell.
Ward is V. P. of Technology at IdeaBlade and, with over 25 years of application development experience, he champions the company's customer-focused product direction.
Due to the popular demand of last week's live webinar, we've asked Ward to join us again to show how IdeaBlade's DevForce product uses PostSharp to infuse “Code First” entity model classes - entities like Customer and Order – with rich behaviors that go way beyond property change notification.
During the webinar you will learn:
- How IdeaBlade uses PostSharp to achieve important product goals
- Which alternatives to PostSharp the company considered, and rejected
- What initially worried IdeaBlade about using AOP and PostSharp
- Where IdeaBlade is planning to go next with PostSharp
If you've ever wondered what difference AOP and PostSharp can make in real products, and want to gain insight into how it can help with your own project, be sure to watch Thursday's webinar.
Happy PostSharping!
-Britt

If learning more about Aspect Oriented Programming is on your to-do list for 2012, we have some very good news for you.
We’ve teamed up with the good folks at Pluralsight to make it easier than ever for developers to get up to speed on developing with aspects. PostSharp users can sign-up to receive a free 30-day trial membership good towards one Pluralsight online course.
Start learning about Aspect Oriented Programming for .NET today >>
Pluralsight, “the leader in high-quality online training for hardcore developers,” has a huge library of online courses to choose from but, naturally, the course we recommend is Aspect Oriented Programming for .NET by PostSharp MVP and Pluralsight Author, Donald Belcham.
Donald is a senior software developer, independent contractor, author, and trainer based in Edmonton, Canada. He spoke about the topic of Aspect Oriented Programming at NDC and DevTeach Montreal earlier this year, and published the online course on Pluralsight in June.
The course is divided into four parts:
- Introduction to AOP
- AOP using Interceptors
- AOP using IL Code Weaving
- AOP beyond decorators
From Donald: “My course is perfect for developers who want to learn how to avoid code repetition by implementing AOP in .NET projects using IL Code Weaving frameworks like PostSharp, Interception frameworks like Castle Windsor, and even how to implement AOP without following the traditional decorator pattern.”
Apply for your free 30-day Pluralsight trial membership today and, upon approval, we’ll email you a unique login code plus a link to a special sign-in page for PostSharp users.
Start your free 30-day trial membership today >>
-Britt