PostSharpin’ – Part 1

I’ve been intrigued with PostSharp for some time. PostSharp is an AOP platform and works its magic at build time (for the most part). You apply an aspect and PostSharp does the IL weaving, via integration with MSBuild, to output an assembly with the injected functionality. The goal, as their home page banner says: “Eradicate boilerplate. Raise abstraction. Enforce good design.”

I worked on the DevForce framework for a number of years and we’d written several custom aspects to implement certain product features, but I’d never had a chance to play with some of the “ready-made” implementations in the PostSharp patterns library. Writing your own aspects can range from fairly easy to quite hard, but many of the out-of-the-box aspects in the patterns library seem to combine great functionality and ease of use. Of particular interest to me are the ready-made patterns for INotifyPropertyChanged support and threading. The patterns library also includes support for logging, exception handling and a few other patterns, but I’ll save those for another day.

To get started with PostSharp, install the package(s) from NuGet. You’ll also be prompted for license information during the install, but since I’m using the 3.2 alpha I signed up for a 45 day free trial of PostSharp Ultimate.

NotifyPropertyChanged

Nothing screams boilerplate more than INotifyPropertyChanged. In any .NET environment, data bound objects must implement INotifyPropertyChanged (or the PropertyChanged pattern) for changes to be seen by UI controls. This means raising the PropertyChanged event, and more importantly, losing the simplicity of automatic properties since property setters must raise PropertyChanged. This gets irritating quickly.

With PostSharp the solution is simple: just decorate the class with the NotifyPropertyChanged aspect, found in the Model Pattern Library.

You can decorate a base class too, and get the functionality you expect across its sub-types. If you’ve both implemented INotifyPropertyChanged and added the aspect (maybe in a complex inheritance hierarchy), PostSharp handles that too. PostSharp will add the PropertyChanged logic to the setters of all public properties, but you can opt-out too by decorating a property with the IgnoreAutoChangeNotification aspect.

Here’s a simple class and sub-class with full INotifyPropertyChanged functionality:

[NotifyPropertyChanged]
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return string.Format("{0} {1}", FirstName, LastName); }
    }

    [IgnoreAutoChangeNotification]
    public DateTime LastContactDate { get; set; }
}

public class GoldCustomer : Customer 
{
     public int Points { get; set; }
}

Under the hood the aspect will inject the INotifyPropertyChanged logic into your IL. Actually, it implements a PostSharp interface called INotifyChildPropertyChanged, which in turn extends INotifyPropertyChanged.

This simplicity does come with a performance penalty, however. In my tests setting a single string property on a class implementing INotifyPropertyChanged (INPC) versus one using the NotifyPropertyChanged aspect, the INPC implementation was about 100x faster. So, while the aspect is a great solution for eliminating the boilerplate, for classes which won’t be data bound in the UI or which have strict performance requirements, it’s not an ideal solution.

Threading

The PostSharp Threading Pattern Library contains several interesting aspects, with more coming in the 3.2 release.

Background and Dispatched

The Background aspect can be applied to any method to dispatch it to the background. Under the hood PostSharp does a Task.Start to invoke your method on a background thread. With the async/await support in .NET 4.5 this may not be all that handy, but if you’re using a BackgroundWorker or working directly with the Thread or ThreadPool classes it may make your code a bit cleaner. Likewise, the Dispatched aspect will ensure the decorated method is invoked on the UI thread. Background and Dispatched don’t need to be used together, and using Dispatched can clean up some ugly BeginInvoke logic.

Coincidentally, I was just reading the April issue of MSDN Magazine and Laurent Bugnion’s article Multithreading and Dispatching in MVVM Applications, so switched his simple non-MVVM starting solution to use Background and Dispatched. Bugnion uses the DispatchHelper from MvvmLight in his MVVM samples; you can use these PostSharp aspects in your view models too, but unlike some of the other PostSharp libraries which have portable class library support, the threading library is available for .NET 4 and above only.

Here’s a snippet of the sample code from the article using Background and Dispatched:

[Background]
private void StartSuccessClick(object sender, RoutedEventArgs e)
{
    // This is a background operation!

    var loopIndex = 0;

    while (_condition)
    {
        // Do something

        // Notify user
        UpdateStatus(string.Format("Loop # {0}", loopIndex++));

        // Sleep for a while
        Thread.Sleep(500);
    }
}

[Dispatched]
private void UpdateStatus(string msg)
{
    StatusTextBlock.Text = msg;
}

These are handy but not all that compelling, since an InvalidOperationException is thrown immediately when you try to access a UI control on a background thread, and therefore easy to diagnose and fix. Much more insidious are thread safety problems. In a multi-threaded environment, safely working with mutable objects can be challenging: thread safety issues generally appear as odd “random” errors and deadlocks, often only under load, and are very difficult to reproduce and debug.

PostSharp defines three threading models or patterns and corresponding aspects: Thread Unsafe, Read-Writer Synchronized and Actor. (I’ll take a look at Actor in a follow-on post.)

ThreadUnsafe
If a single instance of a class should never be accessed concurrently, decorate the class with the ThreadUnsafe aspect. Should you access the object across concurrent threads, you’ll receive an immediate ConcurrentAccessException from PostSharp.

Markup is easy:

[ThreadUnsafe]
public class Booking
{
    public string CustomerName { get; set; }
    public DateTime StartTime { get; set; }
    public int NumberOfPersons { get; set; }
}

The ThreadUnsafe aspect also allows you to set a ThreadUnsafePolicy, such as ThreadAffine, which gives thread affinity to your objects and will cause a ThreadMismatchException to be thrown if the object is used on any thread other than the creating thread. Also baked into ThreadUnsafe is some compile-time validation and support for opting out to perform your own explicit synchronization.

Most classes aren’t designed to be thread safe, and don’t need to be, but if you have any globally shared objects or need to pass an object around among threads, or alternately, ensure it’s never shared across threads, this aspect is far easier to use than performing your own locking. I didn’t look at performance here, but I’ll take a quick exception over data corruption any day.

ReaderWriterSynchronized

Finally, dealing with thread-safe objects. When you do have objects which truly must be shared in a multi-threaded environment dealing with thread safety can be a big pain. First deciding on whether to use a lock, a mutex, a ReaderWriterLock, Interlocked variables, etc., and then what the scope should be. Once it’s finally working correctly a later modification “forgets” to lock the resource, and you don’t discover this until you’re in production under heavy load.

PostSharp handles this declaratively with its ReaderWriterSynchronized aspect. Under the hood it’s an implementation of ReaderWriterSynchronizedSlim, and provides for concurrent reads and exclusive writes. Here you decorate the class with ReaderWriterSynchronized, but must also mark methods, getters and setters with either Reader or Writer aspects. (Prior to PostSharp 3.2 these aspects were called ReaderLock and WriterLock.) The advantage of the aspect, other than the removal of all the locking code, is that PostSharp will immediately detect when a resource is accessed without a lock and throw a LockNotHeldException.

Here’s an example of the .NET sample for a SynchronizedCache using PostSharp aspects:

[ReaderWriterSynchronized]
public class SynchronizedCache
{
    private Dictionary innerCache = new Dictionary();

    [Reader]
    public string Read(int key)
    {
        return innerCache[key];
    }

    [Writer]
    public void Add(int key, string value)
    {
        innerCache.Add(key, value);
    }

    [UpgradeableReader]
    public AddOrUpdateStatus AddOrUpdate(int key, string value)
    {
        string result = null;
        if (innerCache.TryGetValue(key, out result))
        {
            if (result == value)
            {
                return AddOrUpdateStatus.Unchanged;
            }
            else
            {
                innerCache[key] = value;
                return AddOrUpdateStatus.Updated;
            }
        }
        else
        {
            innerCache.Add(key, value);
            return AddOrUpdateStatus.Added;
        }
    }

    [Writer]
    public void Delete(int key)
    {
        innerCache.Remove(key);
    }

    public enum AddOrUpdateStatus
    {
        Added,
        Updated,
        Unchanged
    };
}

In part 2 I plan to take a look at PostSharp’s Actor support, along with the new Recordable aspect for undo/redo and the Immutable and Freezable aspects, available in the upcoming 3.2 release.

What I’ll do for a free t-shirt

One of the more exciting things from the recent Build conference was the frequent mention of Xamarin. Whenever Microsoft noted its embrace of cross platform, there was Xamarin providing the capability:
xam x platIt seemed that every .NET-oriented session mentioned Xamarin, and Miguel de Icaza, CTO of Xamarin, made an appearance in the Day 2 keynote and gave an excellent presentation, Go Mobile with C# and Xamarin .

I played with Xamarin a bit last year, and although there were some rough edges, I thought then, and still do, that it has great potential. C#, .NET, Android, iOS? What’s not to love? As de Icaza noted, people expect great experiences from their mobile devices and “C# fits like a glove for mobile development”. It’s been about 6 months since I last took a look, but since I really wanted the “snazzy” C# t-shirt seen at Build, thought I’d give it another spin.
xam shirt

Not that there still aren’t rough edges.

Since it had been six months, I first wanted to update to a more recent Xamarin version. Within Visual Studio 2013 I tried to login to my Xamarin account, and got this helpful dialog:
xamerror

Hmm, was my account no longer valid? Nope, my credentials still worked on their web site, and I was able to download the latest installer from there.

Since I don’t have a Mac, I haven’t yet tried out Xamarin.iOS. A Xamarin.Android install will also install the Android SDK, Xamarin Studio, and the Java SDK and Android NDK if not present. So it can take some time. The installation completed with this message:
xam info
Great, except I’m running VS2013. Thankfully it was just a bad message, and Xamarin.Android 4.12 installed OK.

But, ah, I still got the same error when trying to login to my Xamarin account from VS. Since I couldn’t get past the error in VS I switched over to Xamarin Studio. Xamarin Studio is a nice IDE, but a bit of a step sideways after VS. It is improving though; I found that some of my favorite shortcut keys which hadn’t worked in an earlier version were now working.

There’s a Xamarin Updater built into both the VS tooling and Xamarin Studio and I’d previously set it to automatically check for and download updates from the “stable” channel, so this popped up when I opened Xamarin Studio:
xam updates

After this, I was finally ready to open the XamarinStore app, the sample application shown at Build which introduces you to Xamarin and gets you the snazzy t-shirt.

Just press “play”.

Building the XamarinStore sample application requires that you login to your Xamarin account:
xam login
Xamarin comes in several editions, and I’m currently using the Business edition from my former employer but will soon switch to the free Starter edition. Unfortunately that means no more VS integration.

You’ll need to rebuild after successfully entering your credentials. Also be sure to check the Tasks window for TODO items Xamarin has left for us.

If you haven’t started and selected an emulator, you’re prompted with a list of device emulators. If you’re not up on your Android API levels this will appear confusing, and reminds you that there is a learning curve to developing with Xamarin.Android. The Android developer documentation is a good resource and they’ve helpfully mapped API levels to platform releases.

I chose level 15 (Ice Cream Sandwich) since Jelly Bean and KitKat device emulators weren’t listed. Afterwards I found that although the Android SDK had been updated with my Xamarin installation, the packages for these API levels weren’t also automatically installed. I’ll have to do that later using the Android SDK Manager:
xam sdk

You can also view and edit the devices using the Android Emulator Manager available from the Xamarin Studio Tools menu. (The actual window opened is called the Android Virtual Device Manager.) The size of the emulator screen made using the virtual keyboard difficult, so to add keyboard support I had to edit the AVD to add it:
avd editor

And without further ado the app was running and the t-shirt ordered!
xam done

There’s much to learn in Xamarin, and their Developer Center has a lot of great content. I hope to dig in deeper soon.

Fizzy Bizzyness

FizzBuzz is an interview question which supposedly helps “filter out the 99.5% of programming job candidates” who can’t program.  I find this assertion very hard to believe, unless those tested are non-coding managers.  But anyway, the problem statement is simple:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”.  For numbers which are multiples of both three and five print “FizzBuzz”.

A simple implementation in C# might look like this:

[TestMethod]
public void FizzBuzzSimple()
{
   string s;
   for (int i = 1; i < 101; i++)
   {
      s = string.Empty;

      if (i % 3 == 0) s += "Fizz";
      if (i % 5 == 0) s += "Buzz";
      if (s.Length == 0) s = i.ToString();

      Console.WriteLine(s);
   }
}

Since the algorithm here truly is straightforward and simple a more interesting exercise might be to consider the ways in which this code might change as the requirements change over time.  Something like a kata. (For a fun “simple” problem description from a non-programmer’s point of view, this is hilarious, and all too true: http://failblog.cheezburger.com/share/59643393.)

We’re all familiar with code where the conditional expressions have become both ugly and impenetrable. In fact, we’ve probably “contributed” to these codebases at some point too.  Something that may have started with a relatively simple “if ((A and !B) or C)” grows over time to a rat’s nest of and’s, or’s, not’s, etc. So what might change here, and can we, or should we, try to “future proof” against it?

  • What if the range changes?  Instead of 1 to 100 the user now wants 1 to 1000, or maybe 50 to 100.  Maybe the range needs to be user configurable.
  • What if our output strings change?  Instead of “Fizz” and “Buzz” the user wants “Buzz” and “Feed”.  Should we continue to hardcode magic strings?  Maybe we want something entirely different than the “FizzBuzz” concatenation when a multiple of 15 is found.   What if we need to localize the strings based on the user’s language?
  • What if the test conditions change, or new conditions are added?  In practice, this is often the most likely change agent.  What if more complex conditions are needed, such as special processing for multiples of 10?   How can we make the code easy to read and maintain over time?
  • What if the test conditions, in the real world, are expensive in terms of performance?  Instead of testing numbers maybe we’re calling functions which make database or service calls.  How do we make this performant?
  • What if our user no longer wants to “print” the output?  Maybe the output will go to a diagnostics window, log, or screen.  Could dependency injection help here?

There are probably myriad more possibilities, but I’m already feeling analysis paralysis.

It’s Not About the Code

Since Lance Armstrong’s first autobiography, It’s Not About the Bike, which explored his journey as a promising young rider, through cancer and on to a Tour de France win, cyclists have bandied about the phrase and its opposite, “It is about the bike.”  When not about the bike, it might be about the journey, with the bike as a means to an end; when about the bike, it may be about the elegant beauty and simplicity of the machine, or still too, the bike may serve as a symbol of the freedom and athleticism of cycling.  In either case, they’re both right.

As software engineers, it’s often all about the code.  The code is usually what lured us into the profession.  It’s what we zealously protect in source code repositories; what we review for correctness; what we refactor for simplicity and even elegance.  We love new, and sometimes old, programming languages.  We love to talk about code, and we love to write code.

But, is it really all about the code?  Should we spend every moment of our working day coding, and only coding?  If so, we run the risk of being nothing more than a commodity coder, or “just a programmer,” and viewed, quite rightly, as simply a necessary evil to our employers.  With the commodity view of coding, it’s easy for an organization to outsource its software development.  When an organization wants only low-wage commodity coders, it’s also easy to proclaim a shortage of “qualified” candidates and lobby for H-1B reform

Except at the most junior levels, what does a software engineer or developer typically do?  Code, yes, but also analyze, design, architect, estimate, test, debug, mentor, write, teach, schedule, document, learn, coach, plan, prioritize, coordinate, evaluate, review, hire, … the list goes on.  Are these activities trivial and incidental to the purity of our calling, or an integral part of the art and science of software engineering?

Fortunately, many organizations do recognize the skills, both broad and deep, that are expected of their software engineers.  We engineers, in turn, need to ensure we’re more than simply coders.

Shock Jocks

The other week I read this:  Software Developers Are Terrified Of What Happens When They Hit 30.  The latest breaking news from CNN?  A supermarket tabloid alongside Shocking Proof that Obama is a Muslim!? No, this from the supposedly respectable Business Insider.  Has the dystopian world of Logan’s Run finally arrived, or is serious journalism on a holiday?

The author mostly cites a thread on Hacker News, which to my reading did not contain hordes of frightened 20-somethings agonizing over their imminent departures from relevancy in the tech world.  Instead, the thread contains many thoughtful comments from software engineers of varying ages and experience, mostly all saying they love what they do and the key to career longevity is to keep learning.

A more insightful article appeared in the New Republic a few weeks later, The Brutal Ageism of Tech.  This too focused on a fetishism with youthfulness – in the Silicon Valley – to the point of visiting a plastic surgeon to appear young and therefore relevant.

Articles such as these aren’t new, but why the steady drumbeat to spread fear, uncertainty and doubt?  Ageism certainly exists, but outside of the dorm room VR bubble of Silicon Valley it should not be sparking terror.  Young adults can bring energy and enthusiasm to a team, but despite what Mark Zuckerberg thinks they aren’t by definition smarter, yet the media is all too happy to accept this arrogant naiveté as fact.

Certainly 30 is usually a watershed year in one’s life, as the realization finally comes that You Are No Longer a Kid, as Mr. Zuckerberg may learn when he turns 30 next month.  Unless you’re a professional athlete, or a prodigy, most 30 year olds, regardless of profession, will just be hitting their stride both personally and professionally.  Why would this be true for a doctor or lawyer, but not for a software engineer?

On a related note, I’ve been listening to some of Shawn Wildermuth’s Hello World podcasts with various tech professionals, all of whom do seem to be older than 30.  They must not yet have encountered the terrifying and brutal truth.