PostSharp Blog

The official blog of PostSharp: annoucements, tips & tricks

Annoucements
3 May 2013

We’re excited to announce that PostSharp 3 RTM is now available for download from Visual Studio Gallery and NuGet. After a successful RC cycle, PostSharp 3 now enters the stable quality band and replaces PostSharp 2.1 as our featured version.

PostSharp 3 marks a huge evolution from previous versions. Designed to deliver more value with less learning, PostSharp 3 is now much more than an awesome framework: using simple smart tags in the Visual Studio code editor, you can add to your code ready-made implementations of some of the most common design patterns. Other improvements include first-class support for Windows Store, Windows Phone and Silverlight apps.

Improved Visual Studio Integration

The single most striking feature of PostSharp 3 is its deeper integration with Visual Studio.

For instance, move the caret to the name of a class or a method. Visual Studio will display a smart tag proposing actions that make sense in the current context: apply a threading model, add logging, implement INotifyPropertyChanged, …

 

A wizard then guides you through the configuration of the aspect.

The wizard installs all required NuGet packages and generates the code for you – so you don’t have to study documentation to figure out how it works.

Of course, you can still add aspects to your code the old good way.

Ready-Made Pattern Implementations

While talking to customers, we figured out that the Pareto law also applies to our product: 80% of customers use the same top 20% aspects. We thought we would provide more value to our customers by providing ready-made implementations for the most common patterns. The results are our three first pattern libraries:

Windows Store, Windows Phone and Silverlight

In previous versions of PostSharp, support for alien .NET platforms was quite limited. The raise of Windows Phone and Windows Store stressed the importance of supporting new trends, so we decided to invest in providing first-class support for Windows Store, Windows Store and Silverlight.

I’m very pleased that we could this through Portable Class Libraries.

The first challenge was to develop a portable alternative to the system BinaryFormatter and its  [Serializable] attribute. The result is the PortableFormatter class and its [PSerializable] attribute – an interesting piece of software in itself.

Deployment through NuGet and Visual Studio Gallery

When PostSharp 1 was released seven years ago, it seemed mandatory to have a setup program. Over the years, source control and build servers have conquered the world, changing requirements on deployment of development tools.

Despites important limitations, Microsoft’s NuGet and Visual Studio Gallery are becoming the de-facto standards for deployment of development components and their user interface, so we decide to get aligned with Microsoft’s lead.

We are aware of some negative consequences and will be happy to work with customers who may be affected by this choice.

Subscription-Based Maintenance Model

PostSharp 3 marks also the move from a per-version to a per-year maintenance model, as described in a previous blog post. A maintenance subscription is now included as a mandatory part of the product fee. The maintenance subscription not only gives right to major versions, but also to bug fixes.

We believe that part of our failure to deliver support for Visual Studio 2012 in time was due to our per-version revenue model. The new revenue model will allow us to release features as soon as they are needed, irrespective of the current major version number.

For more information regarding licensing and support, please read our FAQ page or contact our sales team.

Tip: Upgrade Before Summer

PostSharp 3 is now stable and it’s a good time to upgrade. During the next 2 months, the team will be ready to answer your questions and address support issues, without any other big project in the pipeline. We may be a bit slower during the vacation period, so it’s a good idea not to delay the upgrade if you can do it now.

PostSharp 3 is a big turn for our company, and so far we are very happy with the feedback and the businesses we received.

Happy PostSharping!

-gael

Annoucements
17 April 2013

We’re happy to announce that PostSharp 3 has finally reached the RC quality band. This means that it is now sufficiently documented, internal testing is completed, all known bugs (except some minor ones) have been fixed, and the rate of new bug reports has significantly decreased. We plan to move to RTW with two weeks, unless important bugs delay this objective.

It is now a good time for small teams to upgrade to the new versions. The procedure is described in our online documentation. We are planning more articles and webinars regarding upgrades and deployment of PostSharp 3 in the next weeks.

Happy PostSharping!

-gael

Annoucements
27 March 2013

We reached one of the last milestones before the RC: publishing the documentation! You can now browse it online from http://doc.postsharp.net/.

Yet this is not a good time for all of you to rush on PostSharp 3 because I’ll have vacation (till April 7th) before the dead march to RTM. Support will be provided as usually, but we won’t do bug fixing releases until I’m back.

I like to write the documentation myself because it forces me to do a last API review and makes sure all concepts line up. Documenting is a never-ending job, and I hope this first version of the documentation cover the most important questions. Yet, there are still important holes. Let me know if you find one that is specially important to you, so I can prioritize.

This being done, the road is now clear for RC and then RTM. Finally!

Happy PostSharping!

-gael

Annoucements
8 March 2013

It's been a few days since we released our new website. Although PostSharp 3 is still in preview, we've become confident enough in its quality to start selling licenses – with a 30% discount until we reach RTM. I wanted to quickly tell you about changes made to the PostSharp product lineup, including maintenance, pricing, and upgrade conditions.

New focus on design patterns

In the past years, we've successfully positioned PostSharp as the leading framework for Aspect-Oriented Programming in .NET. With time and customer feedback, we've realized that AOP was only an instrument serving automation and enforcement of design patterns. Unlike AOP, design patterns are readily understood and accepted by the majority. We published our view of Design Pattern Automation in a recent article on InfoQ.

PostSharp is now composed of the following members:

Note that Pattern Libraries were previously incubated as a satellite project of PostSharp 2.1, where they were named toolkits. They are now an integral and supported member of our product line.

We're very proud of our new website, reflects our new vision of PostSharp. There are plenty of tutorials for beginners and intermediate users, and more are coming.

What's New in PostSharp 3?

PostSharp 3 is not just about repackaging old ideas differently. We also added a lot of new features and support for the latest platforms:

  • First-class support for Silverlight, Windows Phone, and Windows Store. Not only did we add new platforms, but we also brought all features to most cousins of the .NET Framework. Best of all: these platforms are supported through a single Portable Class Library, so it's now possible to write truly portable aspects. A central component of this feature is the Portable Serializer, similar in function to the BinaryFormatter (just replace [Serializable] by [PSerializable]).
  • Pattern Libraries, providing ready-made implementation of some the most common patterns. Improvements over PostSharp 2.1 Toolkits include better management through logging profiles, logging to Enterprise Library, code contracts, and performance enhancements.
  • Smart tags in the code editor help you adding ready-made aspects to your application without coding – without even reading our Getting Started. Smart tags are completed with a comprehensive wizard interface coupled with NuGet and a code generator.
  • Support for Visual Studio 2012, including the dark theme.
  • Transparency to all obfuscators: PostSharp does not rely on any string references that may be broken during serialization.
  • Better differentiation of "reference assemblies" and "runtime assemblies".
  • New approach to licensing that will allow to install the license key to source control.
  • Streamlined deployment through NuGet and Visual Studio Gallery

New Maintenance Model

PostSharp 2 was ruled by a "major-version" maintenance model: all updates (minor versions and bug fixes) within a major version were available for free. We released important improvements as "bug fixes": for instance, support for .NET 4.5 was included into PostSharp 2.1 because PostSharp 3 was not ready. This maintenance model created a conflict of interest between us (we need to be paid for our work) and our customers (you can't wait for a new major version to get new necessary features). It was time to change.

PostSharp now comes with 1-year of maintenance subscription included that gives you access to free updates, bug fixes and premium support. Every license key includes the subscription end date, which is tested against the build date of PostSharp. Importantly, licenses are still perpetual: if you can use a given PostSharp build one day, you can use it forever (except with the trial license).

Please read our Licensing & Maintenance FAQ for details. Note that we have an updated License Agreement that reflects these changes. If you need to continue with the previous license agreement, please contact our sales team.

New Product Line

There are now three distinct editions available.
  1. PostSharp Express (formerly Starter Edition) – for getting started with simple custom design pattern automation. Free as in beer.
  2. PostSharp Professional – for automating custom design patterns (aspect framework) and logging (diagnostics pattern library). Price: 449$ or 329€ including maintenance subscription.
  3. PostSharp Ultimate – for automating custom design patterns (aspect framework) and enforcing design rules (architecture framework), includes all ready-made design pattern libraries. Price: 799$ or 589€ including maintenance subscription.
For more information, see the feature matrix of all editions. As you can see, we dropped the Personal License. On the other side, we're now offering free licenses to all freelancers and consultants, additionally to students, educational facilities, and influencers of all sorts. We're also offering a one-time 1000$ discount to all businesses enrolled in BizSpark.

Upgrade Conditions

We're giving 6 months of maintenance subscription for free to all customers:

  • Customers without support subscription fully-featured PostSharp Ultimate for free and get 6-months of maintenance starting from the original date of purchase. Practically, it means that this offer only applies to customers who have purchased PostSharp later than six month ago.
  • Customers with a current support subscription get PostSharp Ultimate for free and will receive an additional 6 months of maintenance, at no cost.
  • Other customers can benefit from our upgrade price (224$/164€ for PostSharp Professional or 399$/299€ for PostSharp Ultimate).

Technically, we consider PostSharp 3 mature enough for most situations. However, if you cannot afford taking risks right now (tight deadline, large team), we recommend to wait until RTM before doing the upgrade. The principle obstacle on the path to RTM is now the lack of documentation for new features and new deployment options.

Downgrade Conditions

We understand that some teams don't want to upgrade to PostSharp 3 now, and may need to acquire new PostSharp 2.1 licenses. When you acquire a PostSharp 3 commercial license, you become eligible for a free PostSharp 2.1 license. To request your license key, please contact our sales team. The offer does not apply to PostSharp Express.

Time-Limited Discount

For a limited time, we’re offering a special discount on PostSharp 3 purchases. From now until the RTM announcement, purchase any new PostSharp Professional or PostSharp Ultimate license and save 30% off your order by entering the discount code POSTSHARP3 during checkout. This offer also includes license upgrades and maintenance subscription renewals.

PostSharp 3 is going to change the way software engineers think about design patterns. Happy PostSharping!

-gael
Annoucements
14 February 2013

Just a very short post to update you on the status on PostSharp 3. We spent the last 2 months stabilizing the new version, polishing new features without adding any new one, adding more tests, and running test suites on all supported platforms. The team is now quite satisfied with the quality, so we decided to move the quality label from Alpha to Beta. It means that we are code complete, that no important refactoring is planned, and that the only changes should be bug fixes and documentation. We have a few minor UI and UX bugs open, but there should be nothing serious.

The main task that separates us from the Release Candidate status is API and reference documentation. That’s what we are going to work on during the next couple of weeks. The API could still change during this process because documenting also works as an excellent review process.

If you are already using PostSharp 2.1, it is now a good time to try to upgrade to the next version and see if anything goes well. We don’t recommend you to “commit” the upgrade to your main development branch yet (and the PostSharp 3 does not come with a go-production license yet), but it would really help us to have feedback from the field. To upgrade to PostSharp 3, just use NuGet package manager at solution-level and add the pre-release PostSharp package to all projects.

We’re looking forward for your feedback.

Happy PostSharping!

-gael

Annoucements
14 January 2013

Microsoft Logging Application Block, a part of Enterprise Library, is very popular in corporate environments. As all logging frameworks, the Logging Application Block provides an infrastructure for collecting and routing log entries, but falls short at generating them. If you want to log something, you have to write code that emits this log record. But there are situations where you just want to trace the execution of every method in some part of your application so that you can troubleshoot some issue. That typically requires a lot of boilerplate code.

This is why we designed PostSharp Diagnostics Toolkit, a tool that excels at generating the boilerplate needed to emit tracing information at a very low level of details. Today, we’re proud that the toolkit also supports Enterprise Library, besides NLog, Log4Net and System.Diagnostics.

Adding tracing to your application

Seriously, adding tracing to your application has never been so easy.

First, install PostSharp 3 CTP from Visual Studio Gallery or Visual Studio Extension Manager.

Then, in the Solution Explorer, right-click on the project and choose Add > PostSharp policy

You’ll get a list of project-level policies. Choose logging.

You’re then asked which types and methods should be logged.

Here you have a chance to specify which details need to be included. There are two default profiles: log everything, and log only on exceptions. Both default profiles will include parameter values by default. You can edit the profiles and create new ones as required.

Finally, you are asked to change the logging back-end.

After confirmation, PostSharp will download the required NuGet packages and will add a [Log] custom attribute to a new file named GlobalAspects.cs.

[assembly: Log(AttributeTargetMemberAttributes = MulticastAttributes.Public,
AttributeTargetTypeAttributes = MulticastAttributes.Public)]

Of course, you can use the full power of aspect multicasting to fine-tune the set of methods that you want to trace.

If you build and run the application, and if you have included a trace listener, you will see that all public methods of public types have been traced!

High-Performance

The Logging Application Block is a bit different from other logging frameworks in that there is no concept of “trace source”. Instead, there is a a concept of extensible log record and a concept of filters that can match any property of log records, including custom properties. This design makes Enterprise Library more flexible than other logging frameworks, but is at first sight less suitable for massive tracing because of the expense of building a log record object. Fortunately, intelligent code generation can make Enterprise Library as fast as other frameworks by sharing some read-only data structures and assuming that filters do not change when the application is executing (i.e., that a change requires an application restart).

Hierarchical categories

Another limitation, critical for automated tracing, is the lack of support for hierarchical categories. As a workaround, PostSharp will enlist each log record in several categories, one for each part of the type name and namespace.

Generated Code

For those who want to see what’s under the hood, the following snippet shows the code generated from a simple “Hello, world” method with full tracing enabled.

public static void Main(string[] args)
{
    if (<>z__LoggingImplementationDetails._3)
    {
        object[] CS$0$0__args0 = new object[] { args };
        <>z__LoggingImplementationDetails.Write((TraceEventType) TraceEventType.Verbose,
"Entering: ConsoleApplication39.Program.Main({{{0}}})", CS$0$0__args0,
<>z__LoggingImplementationDetails._2.Categories); } try { Console.WriteLine("Hello, world."); if (<>z__LoggingImplementationDetails._3) { object[] CS$0$1__args1 = new object[] { args }; <>z__LoggingImplementationDetails.Write((TraceEventType) TraceEventType.Verbose,
"Leaving: ConsoleApplication39.Program.Main({{{0}}})", CS$0$1__args1,
<>z__LoggingImplementationDetails._2.Categories); } } catch (Exception) { if (<>z__LoggingImplementationDetails._5) { Exception CS$0$2__ex; object[] CS$0$3__args3 = new object[] { args, CS$0$2__ex }; <>z__LoggingImplementationDetails.Write((TraceEventType) TraceEventType.Warning,
"Exception in ConsoleApplication39.Program.Main({{{0}}}):\n{1}",
CS$0$3__args3, <>z__LoggingImplementationDetails._4.Categories); throw; } } }

As you can see, there is a lot of references to the class LoggingImplementationDetails. This class is generated by PostSharp. The static constructor configures prototype log entries and evaluates the filters. The Write method acts as a re-entrance guard, preventing infinite recursions typically induced by ToString when arguments get included in the logged text.

internal static class <>z__LoggingImplementationDetails
{
    // Fields
    public static readonly object[] _1 = new object[0];
    public static readonly LogEntry _2;
    public static readonly bool _3;
    public static readonly LogEntry _4;
    public static readonly bool _5;
    [ThreadStatic]
    private static bool isLogging;

    // Methods
    static <>z__LoggingImplementationDetails()
    {
        LogEntry CS$0$0__logEntry0 = new LogEntry();
        CS$0$0__logEntry0.set_Severity((TraceEventType) TraceEventType.Verbose);
        CS$0$0__logEntry0.Categories.Add("ConsoleApplication39");
        CS$0$0__logEntry0.Categories.Add("ConsoleApplication39.Program");
        _2 = CS$0$0__logEntry0;
        _3 = Logger.ShouldLog(_2);
        LogEntry CS$0$1__logEntry1 = new LogEntry();
        CS$0$1__logEntry1.set_Severity((TraceEventType) TraceEventType.Warning);
        CS$0$1__logEntry1.Categories.Add("ConsoleApplication39");
        CS$0$1__logEntry1.Categories.Add("ConsoleApplication39.Program");
        _4 = CS$0$1__logEntry1;
        _5 = Logger.ShouldLog(_4);
    }

    public static void Write(TraceEventType severity, string messageFormat, 
object[] messageArgs, ICollection categories) { if (!isLogging) { isLogging = true; try { LogEntry CS$0$0__logEntry0 = new LogEntry(); CS$0$0__logEntry0.set_Severity(severity); CS$0$0__logEntry0.Message = string.Format(messageFormat, messageArgs); CS$0$0__logEntry0.Categories = categories; Logger.Write(CS$0$0__logEntry0); } finally { isLogging = false; } } } }

In theory, the JIT compiler could see that the tracing block code depends on the read-only static field whose value is false, and could completely avoid to generate the logging code, resulting in zero cost in case that a given trace category is disabled.

Limitations

Perhaps the main feature that I regret is missing from the current version is support for the Tracer facility, which may be more appropriate for the low-level massive tracing we are trying to achieve. We will have to consider, in a next version, how we can make this concept fit with the current architecture of the PostSharp Diagnostics Toolkit.

Summary

Detailed tracing with Enterprise Library Logging Application Block is now easier than ever. In just a few clicks, you can add tracing to thousands of methods, with no impact or your source code and minimal impact on run-time performance.

Happy PostSharping!

Annoucements
9 January 2013

A few days after Phil Haack described how to implement a null-checking aspect with PostSharp 2, it’s a good time to introduce a new feature of the refreshed PostSharp 3 CTP: validation of parameters, field, and properties.

First, you need to have PostSharp 3 CTP (3.0.5) installed.

To add a contract to to a parameter, just position the caret to the parameter name and select the relevant smart tag:

After you click on the action, PostSharp will download and install the relevant NuGet packages to your project, and add a [Required] custom attribute to the parameter. The same works for fields and properties.

It could not be easier. Of course, you can also introduce contracts without the user interface by installing the package PostSharp.Toolkit.Domain and adding the custom attribute yourself.

public void Foo( [Required] string bar ) 

(Make sure to allow pre-releases if you install the package manually.)

Ready-Made Contracts

The following contracts are available in the PostSharp.Toolkit.Contracts namespace, depending on the type of the field, property or parameter:

NotNull Requires a non-null value
NotEmpty Requires a non-null and non-empty string or collection
Required Requires a non-null object or a non-whitespace string
CreditCard Requires a valid credit card number
EmailAddress Requires a valid email address
Phone Requires a valid phone number
RegularExpression Requires a match of a regular expression
StringLength Requires a string of a given length
EnumDataType Requires a valid value for an enumeration (can be applied to strings and integers)
GreaterThan Requires a value greater than a threshold.
LessThan Requires a value less than a threshold.
Positive Requires a value greater or equal to 0.
StrictlyPositive Requires a value strictly greater than 0.
Range Requires a value within a range.

High Performance and Flexibility

Unlike previous validation aspects based on OnMethodBoundaryAspect, the new aspects result in compact and fast code, with almost no overhead compared to hand-written code.

Yet, they are based on an abstraction that you can extend to develop your own contracts: ILocationValidationAspect<T> is a new aspect primitive designed specifically for the task. It works transparently for fields, properties, and parameters.

If you want to create your own contract, you can derive a class from System.Attribute, or preferably PostSharp.Extensibility,MulticastAttribute (which supports inheritance, see below), and ILocationValidationAspect<T>, where T is the type of values to be validated, as many times as necessary. Note that the aspect does not know any standard type conversion (other than down-casting, which is not a conversion), so you will need a lot of these Ts, for instance for int, int?, long, long?, and so on if you want to target numbers.

Contract Inheritance

If you apply a contract to a parameter of an interface, abstract or virtual method, any the contract will be implemented in any derived method, for instance:

interface IFoo
{
   void Bar( [Required] string fooBar );
}

class Foo : IFoo
{
   public void Bar( string fooBar ) 
   {
      // PostSharp will inject the [Required] contract at the top of this method body.
   }
}

Note that inheritance is a feature of MulticastAttribute and not just contracts, so you can use it with just any aspect.

Limitations

I already mentioned that the aspect does not support any type conversion, which could be annoying if you need to develop contracts that work on numbers.

Also note that the aspect is not yet able to validate output argument and return values. It is purely a precondition checker.

Finally, note that all contracts are opt-in. There is no “not-null by default”. It would be fairly easy to develop such a policy using an assembly-level IAspectProvider, but currently you have to do it yourself.

Summary

PostSharp 3 introduces a new aspect primitive that is optimized to validate fields, properties, and parameters with high run-time efficiency. The PostSharp Domain Toolkit contains a set of standard contracts that you can add to your code easily – just using the smart tags in Visual Studio.

Happy PostSharping!

-gael

Annoucements
26 November 2012

The PostSharp team is excited to announce today the first public release of PostSharp 3, available for download on the Visual Studio Gallery and NuGet (make sure to allow prereleases).

This release marks an important turning point in the way we talk about PostSharp. During the last 8 years, we have successfully positioned PostSharp as the leading framework for aspect-oriented programming in Microsoft .NET. We provided an abstract construction kit and told customers they could build “whatever they wanted” with it. However, we became increasingly aware that the vast majority of our customers were all re-implementing the same aspects.

In addition to just providing a wonderful framework, we now offer more value to our customers by delivering ready-made implementations of the most common design patterns that hang over application development today:

  • Logging for System.Diagnostics, NLog, Log4Net (Enterprise Library coming soon);
  • Design patterns for safe multithreading;
  • INotifyPropertyChanged beyond the obvious;
  • Architectural validation;
  • Change tracking and undo/redo (coming soon);
  • Value validation: not null, regular expression, range, custom rules, … (coming soon);

Long-time PostSharpers know that we already started building on this vision nearly a year ago with our PostSharp Toolkits, published as free add-ons to PostSharp 2.1 Pro Edition. Although the toolkits have always been an important part of our vision for PostSharp 3, we wanted to nurture these projects jointly with our community and release them continuously. The incubation period is now over, and we are happy to announce that PostSharp toolkits will join our product line as first-class members.

With PostSharp 3, not only do we provide ready-made solutions to top problems, but we also make these solutions much more accessible than ever. With the new content-sensitive smart tags and wizards, you will be able to implement design patterns in a matter of minutes, without need to read extensive documentation.

So, beyond the new orientation, what’s new in PostSharp 3?

Smart tags and wizards in Visual Studio

The single most striking feature of PostSharp 3 is its deeper integration with Visual Studio.

For instance, move the caret to the name of a class or a method. Visual Studio will display a smart tag proposing actions that make sense in the current context: apply a threading model, add logging, implement INotifyPropertyChanged, …

A wizard-like user interface then collects all relevant settings and performs the required operations, such as installing a NuGet package and adding a custom attribute to your code.

Support for Visual Studio 2012

Visual Studio 2012 is now fully supported. Windows Store projects are supported too (see below). Visual Studio 2010 is still supported at an equal level of features, but support for Visual Studio 2008 has been discontinued.

First-Class Support for Windows Store Apps, Silverlight, and Windows Phone

Silverlight and Windows Phone (previously .NET Compact Framework) have been supported since PostSharp 1.5, but only a small subset of features was actually available for these platforms. This limitation was due to the inability of previous versions of PostSharp to execute, at build-time, code that was linked to exogenous platforms. Concretely, this affected features such as CompileTimeValidate, CompileTimeInitialize, IAspectProvider and MethodPointcut.

Thanks to some significant engineering effort, this limitation is now removed and all PostSharp features are now equally available on all supported platforms.

Support for Portable Class Libraries

Exogenous platforms are now supported through a single Portable Class Library that can target .NET 4.0, Silverlight 4, Windows Phone 7, and Windows Store 8. Therefore, it is now possible to create portable aspect libraries.

Note that a separate version of PostSharp.dll is still available for .NET 2.0. Unlike the portable version, this one supports serialization of aspects through the BinaryFormatter and provides backward compatibility not only with previous versions of .NET, but also with previous versions of PostSharp.

Because the BinaryFormatter is not portable, we had to develop our own portable serializer. Unlike other formatters readily available with the portable class library, and just as the BinaryFormatter, our implementation serializes the internal object structure (i.e. fields, and not public properties) and supports cyclic object graphs. To use the portable serializer, just use [PSerializable] instead of [Serialiable] and [PNonSerialized] instead of [NonSerialized]. This alone is already a pretty piece of software!

In order to provide support for portable class libraries, we had to do some breaking changes in PostSharp.dll. Specifically, the interface _Assembly is now replaced everywhere by the class Assembly. We had to use the interop interface _Assembly in previous versions of PostSharp because the class Assembly used to be sealed. Since _Assembly is not portable and Assembly is now portable and abstract, we decided to make this breaking change.

Practically, it means that PostSharp 3 won’t compile aspects linked to a previous version.

Unified Deployment Experience

As industry has evolved since PostSharp’s debuts in 2004, we decide to embrace Microsoft’s new vision of development tools deployment. PostSharp distribution is now clearly split into two parts: the compiler is now only distributed as a NuGet package and published on the NuGet Gallery, and the user interface is shipped as a VSIX package and published on the Visual Studio Gallery.

Feature Scavenging

It’s sometimes necessary to make difficult choices and discontinue support for scenarios that seem no longer central. That’s what we did with the following features:

  • Support for Mono as a build platform,
  • Support for Visual Studio 2005 and .NET 3.5 as a build platform (.NET 2.0 is still supported as a runtime platform),
  • Support for .NET Compact Framework (Windows Phone 7 is supported through the Portable Class Library),
  • Support for Silverlight 3 (Silverlight 4 is supported through the Portable Class Library),
  • Diagnostic build,
  • Diagnostic console,
  • Windows Installer distribution,
  • Zip package distribution.

Customers who rely on these features have the possibility to keep using PostSharp 2.1, which is still maintained. Also, note that the user interface of PostSharp 3 is compatible with the compiler of PostSharp 2.1, so side-by-side usage is possible.

Commercial customers who are severely affected by these deprecations are invited to contact us directly.

Continuous Delivery and Subscription-Based Maintenance

As of PostSharp 2.1 we officially switched to a continuous delivery process. We abandoned the distinction between “milestone releases” and “hotfixes” to assure that our customers will always have the latest build from the download page on our website, as well as on NuGet.

All paid PostSharp 3 licenses will come with subscription-based maintenance including 1 year of free updates, web-based technical support, phone support, remote assistance and issue escalation. Maintenance subscriptions are renewed annually with multi-year subscriptions available. Pricing for all PostSharp 3 editions will be announced shortly.

Conditions for Free Upgrade

Those who recently purchased PostSharp 2.1 without support subscription will be eligible for a free upgrade to PostSharp 3, with 6 months of free maintenance from the original date of purchase. This offer is valid only for customers who purchase PostSharp 2.1 within 6 months of the official PostSharp 3 release, scheduled for Q1 2013.

Current PostSharp 2.1 customers with support subscription can upgrade to PostSharp 3 and will receive an additional 6 months of maintenance to their subscription – at no cost.

Limitations

Note that PostSharp is currently in pre-release quality. It comes with several minor issues and the following limitations:

  • All new APIs are still subject to change.
  • Support for obfuscation is not yet available for portable class library.

Summary

Starting today, you will hear much less about aspect-oriented programming from us and much more about patterns. Engineers need patterns because they have been proven to reduce complexity and PostSharp provides ready-made implementations of some of the most common patterns found in .NET applications. Furthermore, PostSharp helps you to build custom design patterns of your own, implement them automatically, and validate that they have been implemented properly. AOP remains at the heart of PostSharp as one of the enabling technologies, but now PostSharp adds even more value to software engineering.

Happy PostSharping!

-gael

Annoucements
19 July 2012

We’ve all experienced, with great frustration, desktop application freeze: the user interface becomes unresponsive and, after a while, the message “Not Responding” is displayed in the title bar and the only escape is to kill the process. Typically, application freezes are the result of a deadlock where the foreground thread, instead of processing the message loop, waits for some resource to be released by a background thread, which in turn waits for the foreground thread to release some other resource.

Deadlocks Defined

A deadlock is a situation in which two or more competing actions are waiting for each other to finish, and thus neither ever does. Whenever you’re using locks there is a risk of deadlocks.

There are four main conditions necessary for a deadlock to occur:

a) A limited number of instances of a particular resource. In the case of a monitor in C# (what you use when you use the lock keyword), this limited number is one, since a monitor is a mutual-exclusion lock.

b) The ability to hold one resource and request another. In C#, this can be done by locking on one object and then locking on another before releasing the first lock, for example:

lock(a)
{
   lock(b)
   {…}
}

c) No preemption capability. In C#, this means that one thread can't force another thread to release a lock.

d) A circular wait condition. In C#, this means that thread 1 is waiting for thread 2, thread 2 for 3 and the last one is waiting for thread 1. This makes a cycle that results in deadlock.

If any one of these conditions is not met, deadlock is not possible.

Avoiding Deadlocks

So simple solution to deadlock problem would be to ensure that at least one of above condition is not met at any time in your application. Unfortunately all above conditions are met in any large-scale application using C#.

In theory, deadlocks could be defeated by aborting one of the threads involved in the circular relationship. However, interrupting a thread is a dangerous operation unless its work can be fully and safely rolled back as is the case with database stored procedures.

Some advanced techniques such as lock leveling (link) have been proposed to prevent the apparition of deadlocks. With lock leveling, all locks are assigned numeric value and a thread can acquire only locks with number greater than those it already holds. As you can imagine, this would stop you from using pretty much anything from the .NET Framework, so it is not a practical solution.

Detecting Deadlocks

Since we can’t prevent deadlocks, we can try to detect them and, if we find one, we can eliminate it. Since application code is typically not transactional, the only safe action we can take to eliminate a deadlock is to terminate the application after having written appropriate diagnostic information that will help developers understanding and resolving the deadlock. The rationale here is that it is better to terminate an application properly than to let it remain in a frozen state. This rationale is true for both client and server applications.

In order to detect deadlocks we have to track all blocking instructions used in user code and build threads dependency graph from them. When deadlock is suspected all we have to do is check if there is a cycle in the graph.

It sounds simpler than it really is. Tracking all locking instructions using hand-written C# code would be very tedious. Normally one would write a wrapper for all synchronization primitives such as Monitor and use these wrappers instead of standard sync objects. This generates a couple of problems: a need to change existing code, introduction of boilerplate code and clutter to your codebase.

Moreover, there are some synchronization primitives, such as semaphore or barrier, which are hard to track because they can be signaled from any thread.

Detecting Deadlocks using the PostSharp Threading Toolkit

PostSharp Threading Toolkit features a drop-in deadlock detection policy that tracks use of thread synchronization primitives in transparent way without requiring any change in your code. You can use locks, monitors, mutexes and most common primitives in the usual way and PostSharp Threading Toolkit will track all resources for you.

When a thread waits for a lock for more than 200ms, the toolkit will run a deadlock detection routine. If it detects a deadlock, it will throw DeadlockException in all threads that are part of the deadlock. The exception gives a detailed report of all threads and all locks involved in the deadlock, so you can analyze the issue and fix it.

In order to use deadlock detection mechanism, all you have to do is:

  1. Add the PostSharp-Threading-Toolkit package to your project using NuGet.

  2. Add the following line somewhere in your code (typically in AssemblyInfo.cs):

[assembly: PostSharp.Toolkit.Threading.DeadlockDetectionPolicy]

 

In order to be effective, deadlock detection should be enabled in all projects of your application.

Supported Threading Primitives

Here’s the list of synchronization methods supported by DeadlockDetectionPolicy:

  • Mutex: WaitOne, WaitAll, Release
  • Monitor: Enter, Exit, TryEnter, TryExit (including c# lock keyword; Pulse and Wait methods are not supported)
  • ReaderWriterLock: AcquireReaderLock, AcquireWriterLock, ReleaseReaderLock, ReleaseWriterLock, UpgradeToWriterLock, DowngradeToReaderLock (ReleaseLock, RestoreLock not supported)
  • ReaderWriterLockSlim: EnterReadLock, TryEnterReadLock, EnterUpgradeableReadLock, TryEnterUpgradeableReadLock, EnterWriteLock, TryEnterWriteLock, ExitReadLock, ExitUpgradeableReadLock, ExitWriteLock,
  • Thread: Join

When using deadlock detection you can use all above methods in normal manner and threading toolkit will do the rest. In the current version of the Threading Toolkit we assume that waits with timeout don’t cause deadlocks (eventual deadlock will be broken when timeout expires). Due to performance issues deadlock detection is enabled only when DEBUG or DEBUG_THREADING debugging symbols are defined.

Limitations

Although PostSharp Threading Toolkit detects a large class of deadlocks, we cannot detect deadlocks involving any of the following elements:

  • Livelocks, i.e. situation when threads alternate acquiring resources not advancing in execution (A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time);
  • Asymmetric synchronization primitives, i.e. primitives such as ManualResetEvent, AutoResetEvent, Semaphore and Barrier, where it is not clear which thread is responsible for “signaling” or “releasing” the synchronization resource. There are some sophisticated algorithms that can detect deadlocks involving semaphores and other asymmetric synchronization mechanisms but these require advanced static code analysis, have enormous computation cost and some even argue that they cannot be implemented in languages with delegates and virtual methods at all.

Even in the case of supported threading primitives some methods make deadlock detection hard or impossible:

  • Getting a SafeWaitHandle of a Mutex is dangerous, because there is a risk that it gets exposed to unmanaged code, which is not tracked by the toolkit.
  • Methods ReleaseLock/RestoreLock of ReaderWriterLock are not supported.
  • Methods Pulse/Wait of Monitor are not supported.

What we need to avoid at any cost, is any kind of false positive, i.e. reporting a deadlock when there is none. In order to avoid such cases we construct a list of ignored resources which are not considered during deadlock detection routine. Additionally, if ignored resources list expands too much, deadlock detection becomes inefficient, so when ignored list contains more than 50 objects we disable deadlock detection mechanism and issue a debug trace informing about it.

Summary

If you’ve ever experienced a deadlock in production, you know how hard it is to diagnose. Not anymore. By adding the PostSharp-Threading-Toolkit NuGet package to your project and adding a single line of code to your codebase, you can get nice exception messages whenever a deadlock occurs.

In case you’re interested how this works under the hood, simply have a look at the source code in the Github repository (https://github.com/sharpcrafters/PostSharp-Toolkits).

Happy PostSharping!

Annoucements
16 March 2012

With all the good reasons mentioned by Ayende, we decided to officially switch PostSharp 2.1 to a continuous deployment process. We are abandoning the distinction between “milestone releases” and “hotfixes”. Since today, you will know always download the latest revision from the principal download page, as well as on NuGet.

Ayende’s article came at a time when we were frustrated with our release cycle. Although we released dozens of hotfixes, the front-page download was still the initial 2.1 RTM release because we constantly deferred the SP1. Clearly, the majority of people were not downloading the best-quality release, and were therefore hitting bugs that have already been solved for a long time. Not the best user experience!

Technically, the difference is quite small. PostSharp’s build and test processes have always been automated. It takes about 50 minutes to build and test all components. Uploading to our download manager is very easy too – copy the build output to a network share and execute a script that synchronizes with Amazon S3. Therefore, the time-to-market of a bug fix has always been very short – a couple of hours, typically. The fact that deployment is now integrated with the build script does not really change this fact.

Thus, the most significant difference is that we will actually publish hotfixes as front-page downloads.

Unlike “hotfixes”, “milestone releases” got additional manual testing on virtual machines, where the later got only automated testing. Installation tests are still not automated, so there’s a slight chance to get a regression in a front-page release. We bet that these defects will be infrequent and quickly detected by the community.

Bottom line: we bet that the overall quality will be higher by switching to continuous development.

Happy PostSharping, now with a fresh version!

-gael