It has been a few weeks since the release of PostSharp 4.2 Preview 1. Today, I’m happy to announce new features and improvements to PostSharp. If you want to discover them, you can download PostSharp from our website or from NuGet (make sure to enable pre-releases).

What was new in PostSharp 4.2

In the previous blog post, I already announced the following improvements included in PostSharp 4.2 Preview 1:

  • Support for Visual Basic
  • Amazing performance improvements in ready-made patterns
  • Other improvements in threading models

Today, I’m announcing the following new features:

  • Thread-safety policy
  • Ready-made patterns: support for System.Collections.Immutable
  • Ready-made patterns: support for rules
  • Module initializers
  • Support for INotifyPropertyChanging
  • OnAspectsInitialized advice

How we dogfooded our own threading models

Most of the improvements we are publishing in this release stem from dogfooding our threading models into PostSharp Tools for Visual Studio. I’m proud to say that we now have a multithreaded VS extension without a single lock or event. Now that all threading assumptions have been made explicit and declarative, the code is much cleaner and easier to understand.

Frankly, the experience was both exciting and awkward. Exciting because the result is amazing. Awkward because we filed more than 50 bugs, enhancements and user stories in the process – principally usability issues or improvements. Most of these tickets are addressed in PostSharp 4.2 Preview 3.

Thread-safety policy

Suppose that you have a large solution with hundreds of classes and you want to apply PostSharp thread safety to it. Typically, you would go through all classes and apply one of the PostSharp threading models. But how do you know you didn’t forget anything?

The short answer:

[assembly: ThreadSafetyPolicy]

When added to a project, the thread-safety policy shall emit a warning whenever it detects:

  • A class without threading model
  • A static field that is mutable or of a non thread-safe type.

Having none of these warnings is not a 100% guarantee that your application is thread-safe. However, it catches the most common omissions. Once a class is assigned to a threading model, thread safety becomes the responsibility of the threading model itself, not of the thread-safety policy.

The thread-safety policy is built using PostSharp Architecture Framework.

Ready-made patterns: support for System.Collections.Immutable

Let’s face it: immutability is a great concept. It allows for excellent runtime performance and, most importantly, makes it easier to think about the semantics of your API. PostSharp provides the [Immutable] threading model to ensure your custom classes are immutable. Previously, you should have used an AdvisableCollection inside your immutable objects. However, the AdvisableCollection class is far from being as fast and convenient as immutable collections. That’s why we added genuine support for System.Collections.Immutable in PostSharp ready-made patterns.

So you can now mix PostSharp’s threading models with Microsoft’s immutable collections to build code that’s thread-safe, highly readable, and still fast enough.

Here is an example of class that has been ported to [Immutable]. Note that we did not completely refactor the solution to use immutable collections, that’s why inputs and outputs of the class are still mutable arrays.

[Immutable]
public class BasicWizardProcess : IWizardProcess
{
    [Child(ItemsRelationship = RelationshipKind.Reference)]
    private ImmutableArray wizardParts;

    public BasicWizardProcess( params IWizardPart[] wizardParts ) 
    {
        this.wizardParts = ImmutableArray.Create(wizardParts);
    }
        
    public IWizardPart[] GetParts( IWizardController controller )
    {
        foreach ( IWizardPart part in this.wizardParts )
        {
            part.Controller = controller;
        }
        return this.wizardParts.ToArray();
    }
}

Ready-made patterns: support for rules

Threading models and undo/redo require you to annotate your object model with a parent-child structure using the [Child] and [Reference] attributes. When you have a reference-type field, PostSharp needs to know whether it is a reference or a child (i.e. whether it is an association or an aggregation/composition). As a design decision, PostSharp does not assume that unannotated fields are automatically references.

There are times when this design is unusable. For instance, there is no way to annotate fields generated by the WinForms or XAML designers.

Starting from PostSharp 4.2, it becomes possible to assign the role of a field programmatically, by rule. A rule is simply a class derived from FieldRule. You need to register the rule using the [RegisterFieldRule] custom attribute.

The following code shows our internal rules for WinForms. Note that this rule is automatically registered so there’s no need for [RegisterFieldRule] in this specific case.

internal sealed class WinFormsFieldRule : FieldRule
{
    public override RelationshipKind? GetRelationshipKind(FieldInfo field)
    {
        if ( IsDerivedFrom(field.DeclaringType, "System.Windows.Forms.Control") && ( field.Name == "components" 
|| IsDerivedFrom( field.FieldType, "System.Windows.Forms.Control") )) { return RelationshipKind.Reference; } else { return null; } } }

The benefits of rules is that you don’t have to explicitly use custom attributes everywhere. We will continue to require custom attributes if no rule is defined because we believe it’s a good practice to force developers to think about the role of a field. However, you can now easily implement a rule that makes all fields references by default. Note that custom attributes always have priority over rules.

Note also that rules are not yet integrated with the UI.

Module initializers

Ever wanted to execute code immediately when an assembly is loaded? Static constructors are not enough: you need a module initializer. VB has them, but C# does not. PostSharp 4.2 fixes this with the [ModuleInitializer(int)] custom attribute.

Just add the custom attribute to a static public/internal void parameterless method. Here is an example. It also demonstrates how we test PostSharp internally:

public static class Program
{
    static StringBuilder trace = new StringBuilder();

    public static int Main()
    {
        if (trace.ToString() != "0;1;2;")
            return 1;

        return 0;
    }

    [ModuleInitializer(0)]
    public static void Method0()
    {
        trace.Append("0;");
    }

    [ModuleInitializer(1)]
    public static void Method1()
    {
        trace.Append("1;");
    }

    [ModuleInitializer(2)]
    public static void Method2()
    {
        trace.Append("2;");
    }

}

Support for INotifyPropertyChanging

PostSharp has supported INotifyPropertyChanged for a long time now. It now also supports INotifyPropertyChanging.

The feature is a bit tricky because INotifyPropertyChanging is not portable, but our [NotifyPropertyChanged] aspect is. Here is how to proceed:

  1. Your target class needs to implement INotifyPropertyChanging manually and it has to define a void OnPropertyChanging(string) method (typically protected). PostSharp will emit the event through the OnPropertyChanging method.
  2. If you want to support dependencies of objects that implement INotifyPropertyChanging but do not have the [NotifyPropertyChanged] aspect, you need to implement an INotifyPropertyChangingAdapter and register it using NotifyPropertyChangedServices.PropertyChangingAdapter.

The procedure is a bit cumbersome so we (or you) could create a non-portable [NotifyPropertyChanging] aspect that would encapsulate this for a specific platform.

OnAspectsInitialized advise

How can you execute code after all aspects on a class have been initialized? Previously, you could not do that in a simple and reliable way. We decided to fix that, simply, because we needed it to fix a few bugs :) The solution is now to use [OnAspectsInitializedAdvice]:

[OnAspectsInitializedAdvice]
public void OnAspectsInitialized(AspectInitializationReason reason)
{
}

Summary

PostSharp 4.2 makes threading models usable in complex, real-world applications. We ate our own dogfood. We were scared by the number of small usability issues we encountered, but so relieved that our initial design was correct and robust.

Happy PostSharping!

-gael

It’s a pleasure to announce the first preview release of PostSharp 4.2, available for download on our website and on NuGet (make sure to enable pre-releases).

PostSharp 4.2 Preview 1 brings the following improvements:

  • Support for Visual Basic (ready)
  • Runtime performance improvement in ready-made patterns (ready)
  • Threading models improvements (ready)
  • INotifyPropertyChanging and support for Xamarin Forms
  • Code saving metrics

In this post, I will just describe the improvements that are already integrated in PostSharp 4.2 Preview 1.

Visual Basic Support

Initially, PostSharp was equally available to C# and VB because they both compile to MSIL, the level at which PostSharp works. However, with time, we developed language-specific features, and made them available only for C#. Today, thanks to the Roslyn project, we are able to bring these features to VB as well:

  • File/line/column positioning of error messages now works also for VB.
  • PostSharp Tools for Visual Studio now supports VB, but only under Visual Studio 2015.
  • The PostSharp compiler now contains more tests that are specific to VB.

VB is now equally supported as C#. Again, I would like to remind that this is thanks to the Roslyn project, which makes it much easier for everybody to support the VB language. No, VB is not dead, Roslyn gives it a second life.

Amazing performance improvement in ready-made patterns

Amazing means, really, a huge difference. In the case of INotifyPropertyChanged, we are now 10 times faster than PostSharp 4.1. This seems a bit embarrassing and requires a few words of explanation.

As we at PostSharp are writing more and more complex aspects, we have been hitting the performance barrier of the current design of the PostSharp Aspect Framework. This design, dating from 2010, did not envision aspects that would include so many transformations. So, its runtime performance was good (even excellent) for the scenarios it was designed for, but with PostSharp 4.0 we seriously started to reach its limits. The root cause of performance limitations is that the PostSharp currently requires a context object (typically OnMethodBoundaryArgs or LocationInterceptionArgs) to be passed from the target code to the aspect code, and this object is allocated on the heap. This creates significant pressure on garbage collection if the aspect is applied to methods called very often, for instance on property getters. Although this technique is way faster than PostSharp’s competition and by the scenarios targeted by this competition (like logging or transaction handling), this is too slow to serve our new ambitions of bringing a solution to thread safety or INotifyPropertyChanged.

So, we are currently investing in PostSharp Aspect Framework so that aspect code receives its context on the stack (as parameters) and not on the heap. The performance gain is just amazing.

Let me be very clear here: we are not advertising our work on PostSharp Aspect Framework as a feature of PostSharp 4.2. This is a huge work, and we will not finish it in PostSharp 4.2. We only developed and tested the features required by our own ready-made pattern implementations. The “modern” aspect framework will not be documented in PostSharp 4.2, and will justify its own major version, probably PostSharp 5.0. In the meantime, you can try the new undocumented APIes, but at your own risks, and without right to support or bug fixes.

Threading models improvements

In PostSharp 4.2, we would like to finish a few items that did not fit into the 4.0 releases. Threading models were a huge innovation and required a massive amount of work and testing. In the rush to close the 4.0 release (because releasing is a feature, too), we reserved a few work items for later, and now it’s time to go back to them.

The most significant improvement is that we no longer block on async methods. So, if you have an async method in a [Synchronized] or [ReaderWriterSynchronized] class, we will now await for the lock. Previously, we would wait for it synchronously, and you would partially lose the benefit of having an async method. This was a very complex work, relying both on some improvements of PostSharp Aspect Framework that will be made public in PostSharp 5.0, and on awaitable threading primitives. The good thing is that we did the hard work so that you can focus on business code.

Note that there is still a case when we wait synchronously instead of asynchronously, but this is a minor one: after executing a [Yielder] method in a [ReaderWriterSynchronized] class.

The second improvement is that we now have an AdvisableHashSet class in addition to AdvisableCollection, AdvisableKeyedCollection and AdvisableDictionary.

Finally, runtime performance of threading models is now dramatically better as described in the previous section.

Summary

Besides support for Visual Basic and code metrics (yet to be released), PostSharp 4.2 is an incremental improvement release. Yet, its runtime performance improvements are so huge that you will want to give it a try.

More at the end of next iteration.

Happy PostSharping!

-gael

PostSharp Technologies is pleased to announce the release of PostSharp 4.1, the latest version of the #1 compiler extension for .NET, adding support for design patterns and thread safety to C# and Visual Basic.

PostSharp 4.1 focuses on extending the set of supporting platforms by adding Xamarin (both iOS and Android), Visual Studio 2015, Visual Studio Universal Apps to the list of compatible products, and by improving the level of support of Windows 8 and Windows Phone. PostSharp 4.1 will also support new minor platform updates automatically, without requiring any update of PostSharp itself.

Xamarin Support

This is definitively our biggest headline. PostSharp 4.1 now supports Xamarin at the same level of feature as Windows Phone or Windows Store. Excepted the diagnostics pattern library, all PostSharp features are now strictly cross-platform and have been tested on several physical devices.

PostSharp 4.1 is an excellent choice to build large and complex applications for mobile devices and will deliver the same economies of scale as for desktop or server applications, possible saving thousands of lines of codes and hundreds of defects.

Note that Xamarin Studio is not supported. You must build your application on Windows using Visual Studio in order to use PostSharp with Xamarin.

There’s no specific tutorial on how to use PostSharp with Xamarin. It just works as usually: open your project in Visual Studio, move your caret on a class and add an aspect from the smart tag (in VS 2013) or light bulb (in 2015).

Visual Studio 2015 Support

PostSharp Tools have been fully rewritten to take advantage of the new architecture of Visual Studio 2015.

Improvements include:

  • Light bulbs are used instead of the smart tags: not only it looks better, but it also better integrates with other vendors such as Microsoft, Resharper or CodeRush.
  • Real-time code analysis detects the most common errors in seconds so you don’t even have to recompile.
  • Real-time coding guidance shows you what’s the next step to implement more complex patterns like threading models or undo/redo.
  • More accurate parsing of C# code, resulting in higher reliability of PostSharp editor integration.

PostSharp Tools Improvements

Besides VS 2015 support, PostSharp 4.1 includes other significant improvements in the tooling for Visual Studio:

  • Universal apps, the marketing name for shared projects, are now properly supported.
  • PostSharp Explorer is now much more usable and accurate than before.
  • Conservative NuGet Versioning prevents unwanted updates of your NuGet packages. PostSharp will always try to match the version that you’re already using in your solution and will politely ask if an update is needed.

Other Improvements

  • Windows Phone Get Threading. Additionally to Xamarin, PostSharp Threading Pattern Library now becomes available for Windows and Windows Phone (both Silverlight and WinRT), so you can build apps that are both thread-safe and cross-platform.
  • Code Contracts Localization. You can now customize the text of exception messages. Please see the documentation for details.
  • No Strong-Name Verification at build-time. It does not affect strong names at run-time.
  • Automatic support of minor platform updates. Minor updates (like from 4.5 to 4.5.1) should now be automatically supported without any PostSharp update.

Summary

PostSharp 4.1 is all about new platforms. With complete support for Windows Phone, Android and iOS, you can leverage the boilerplate-cutting power of PostSharp to your mobile applications. And we proved we’re ready for Visual Studio 2015, with exciting new features that will improve your productivity.

Happy PostSharping!

-gael