Friday, 8 July 2011

Screencast: Modular WPF with MEF & MVVM Tutorial Part 1

A while ago I began to write a blog tutorial about how to create a modular WPF application using MVVM and MEF. I have decided to present it as a screencast instead, so here is the first part. It uses WPF, but a lot of the techniques I show apply equally well to Silverlight.

My approach is not to start off using MVVM and MEF (or any of the more fully featured WPF frameworks), but to introduce these libraries and design patterns at the point at which they make sense. Hopefully this will make it clearer why we might actually want to use them in the first place.

In this first video I create a very simple application with a menu allowing you to switch between two modules, and show how MEF enables us to work around violations of the “Open Closed Principle”.

I’ve got at least one more episode planned which hopefully will appear shortly and introduce MVVM to make our application more easily testable. If there is demand, I may also post my notes and upload my mercurial repository to bitbucket.

Another reason for presenting this as a screencast is that I am planning to create some NAudio screencasts in the future, and so I need to get some practice in. This one is a little raw as I didn’t do a practice beforehand, but I have tried to keep things flowing along at a reasonable pace. I also know the sound quality isn’t brilliant. Let me know if you think the resolution is acceptable.

Wednesday, 6 July 2011

One Language to Rule them All

You may have heard the story of the “tower of Babel”. The story goes that one day, the people of the earth decided to build a great tower. It would be a monument to the greatness of humanity. But God objected to their pride and intervened to thwart their building program. His technique was not to strike the tower down with an earthquake, or strike the builders down with illness. Instead, he opted for a simple yet effective solution: he “confused the language” and the building project was soon abandoned. Inability to communicate doomed the project to failure.

This ancient tale is a remarkably fitting parable for the state of modern programming. Even the smallest of miscommunications, such as requirements not properly understood, or two components in the system using different units of measure can cause the premature demise of entire software projects.

The analogy works on a wider scale too. Imagine what we as a software development community could build if we shared a common programming language. All the wastage of ‘porting’ libraries from one framework to another would be eliminated. Instead of reinventing the same development tools over and over for every new language, we could focus on genuine innovation.

The Last Programming Language

And this is the point made by Robert C Martin at the NDC 2011 conference, in a fascinating talk entitled “Clojure – The Last Programming Language”.

He begins by arguing that we’ve already fully explored the domain of programming languages. In other words, we have experimented with all the types of languages that there are. Or to put it another way, the new languages we keep inventing are just refinements or rearrangements of ideas from existing languages. It’s a slightly depressing thought in some ways – expect no new revolutionary paradigms – we’ve tried it all already.

Whether or not he is right about his first claim, his proposal for the development community to standardise on a single language certainly grabbed my attention. Before dismissing it out of hand as a pipe dream, it is worth pondering the many benefits it would bring.

  • You would not need to hire a C#/Java/Ruby/C programmer. You’d just need to hire a programmer.
  • All platforms and frameworks would be built in that language. No need for all this NUnit, JUnit, PyUnit, Runit business. We’d build on top of what had gone before instead of continually having to reinvent it for every new language.
  • Articles with example code would be immediately understandable to all developers

Can we agree on anything?

But could developers really agree on one programming language? The idea seems almost preposterous. Uncle Bob counters that other industries have gone through the same transition (e.g. biologists, chemists, medicine, mathematics). Eventually the benefits of a lingua franca win through despite the attachment people inevitably feel to their native tongue.

He also points out that this already happened once with C, which is one of those few languages that can genuinely be used to develop on almost every platform. This for me is the big sticking point in seeing Uncle Bob’s vision become a reality. The one language must be able to develop for every platform, server, client, embedded, handheld. It must be usable for every type of development – desktop apps, websites, games, services, device drivers, nuclear power stations. I’m not sure such a language exists.

Features of the final language

But let’s suspend disbelief for a moment and ask what features the final language should have. Uncle Bob’s wishlist included features such as:

  • Not controlled by a corporation.
  • Garbage collected. (I have mixed feelings on this one given .NET’s inability to do low latency audio well)
  • Polymorphic
  • Runs on a virtual machine
  • Able to modify itself at runtime like Ruby (homoiconic)
  • Pared down syntax
  • Functional
  • Hybrid, i.e. Multi-paradigm (support, don’t enforce paradigms)
  • Simple
  • Provide access to existing frameworks
  • Structured (no goto)
  • Fast
  • Textual
  • Dynamically typed (the talk includes an interesting discussion on this).

His proposed language was Clojure. It seems an interesting enough language, although I can’t say I warm to all the parentheses.

A step in the right direction…

In any case, I think that if his vision were to become a reality, we would first have to pick a virtual machine. The two most obvious candidates are the JVM and the CLR, both of which now support a whole host of languages (Clojure can run on either). The CLR may even have the upper hand due to products like Mono which makes it a genuine open source option and available on a very broad range of platforms, although I suspect its ties with Microsoft would generate a lot of resistance.

Libraries that are compiled for a virtual machine like the CLR effectively appear as native libraries for all languages that compile to the same byte code, meaning that there is at least some reduction in the amount of reinvention and relearning required when you switch languages – the libraries can come with you even if the language syntax doesn’t. Another benefit is that often the byte code for a VM can be translated into other languages by a tool, allowing at least some level of automated translation between languages. Maybe someone could invent a browser plugin that automatically converts any code you view in a web-page into the language of your choice – a kind of Google translate for programming languages.

What do you think? Could we agree on a virtual machine, and then get to work on picking a smaller subset of languages to program it with? Or is Uncle Bob’s idea a pipedream? Will we ever get to one common language or will God step in and mix it all up again, just to keep us humble.

Tuesday, 5 July 2011

Test Resistant Code #5–Threading

I want to wrap up my test-resistant code series with one final type of code that proves hard to test, and that is multi-threaded code. We’ll just consider two scenarios, one that proves easy to test, another that proves very complex.

Separate out thread creation

A common mistake is to include the code that creates a thread (or queues a background worker) in the same class that contains the code for the actual work to be performed by the thread. This is a violation of “separation of concerns” In the following trivial example, the function we really need to unit test, DoStuff, is private, and the public interface is not helpful for unit testing.

public void BeginDoStuff()
{
    ThreadPool.QueueUserWorkItem((o) => DoStuff("hello world"));
}

private void DoStuff(string message)
{
    Console.WriteLine(message);
}

Fixing this is not hard. We separate the concerns by making the DoStuff method a public member of a different class, leaving the original class simply to manage the asynchronous calling and reporting of results (which you may find can be refactored into a more generic threading helper class).

Locks and race conditions

But what about locking? Consider a very simple circular buffer class I wrote for NAudio. In the normal use case, one thread writes bytes to it while another reads from it. Here’s the current code for the Read and Write methods (which I’m sure could be refactored down to something much shorter):

/// <summary>
/// Write data to the buffer
/// </summary>
/// <param name="data">Data to write</param>
/// <param name="offset">Offset into data</param>
/// <param name="count">Number of bytes to write</param>
/// <returns>number of bytes written</returns>
public int Write(byte[] data, int offset, int count)
{
    lock (lockObject)
    {
        int bytesWritten = 0;
        if (count > buffer.Length - this.byteCount)
        {
            count = buffer.Length - this.byteCount;
        }
        // write to end
        int writeToEnd = Math.Min(buffer.Length - writePosition, count);
        Array.Copy(data, offset, buffer, writePosition, writeToEnd);
        writePosition += writeToEnd;
        writePosition %= buffer.Length;
        bytesWritten += writeToEnd;
        if (bytesWritten < count)
        {
            // must have wrapped round. Write to start
            Array.Copy(data, offset + bytesWritten, buffer, writePosition, count - bytesWritten);
            writePosition += (count - bytesWritten);
            bytesWritten = count;
        }
        this.byteCount += bytesWritten;
        return bytesWritten;
    }
}

/// <summary>
/// Read from the buffer
/// </summary>
/// <param name="data">Buffer to read into</param>
/// <param name="offset">Offset into read buffer</param>
/// <param name="count">Bytes to read</param>
/// <returns>Number of bytes actually read</returns>
public int Read(byte[] data, int offset, int count)
{
    lock (lockObject)
    {
        if (count > byteCount)
        {
            count = byteCount;
        }
        int bytesRead = 0;
        int readToEnd = Math.Min(buffer.Length - readPosition, count);
        Array.Copy(buffer, readPosition, data, offset, readToEnd);
        bytesRead += readToEnd;
        readPosition += readToEnd;
        readPosition %= buffer.Length;

        if (bytesRead < count)
        {
            // must have wrapped round. Read from start
            Array.Copy(buffer, readPosition, data, offset + bytesRead, count - bytesRead);
            readPosition += (count - bytesRead);
            bytesRead = count;
        }

        byteCount -= bytesRead;
        return bytesRead;
    }
}

The fact that I take a lock for the entirety of both methods makes me confident that the internal state will not get corrupted by one thread calling Write while another calls Read; the threads simply have to take it in turns. But what if I had a clever idea for optimising this code that only involved me locking for part of the time. Maybe I want to do the Array.Copy’s outside the lock since they potentially take the longest. How could I write a unit test that ensured my code remained thread-safe?

Short of firing up two threads reading and writing with random sleep times inserted here and there, I’m not sure I know how best to prove the correctness of this type of code. Locking issues and race conditions can be some of the hardest to track down bugs. I once spent a couple of weeks locating a bug that only manifest itself on a dual processor system (back in the days when those were few and far between). The code had been thoroughly reviewed by all the top developers at the company and yet no one saw the problem.

Here’s another example, based on some code I saw in a product I worked on. A method kicks off two threads to do some long-running tasks and attempts to fire a finished event when both have completed. We want to ensure that the SetupFinished event always fires, and only fires once. You might be able to spot a race condition by examining the code, but how would we write a unit test to prove we had fixed it?

private volatile bool eventHasBeenRaised;

public void Init()
{    
    ThreadPool.QueueUserWorkItem((o) => Setup1());
    ThreadPool.QueueUserWorkItem((o) => Setup2());    
}

private void Setup1()
{
    Thread.Sleep(500);
    RaiseSetupFinishedEvent();
}

private void Setup2()
{
    Thread.Sleep(500);
    RaiseSetupFinishedEvent();
}

private void RaiseSetupFinishedEvent()
{
    if (!eventHasBeenRaised)
    {
        eventHasBeenRaised = true;
        SetupFinished(this, EventArgs.Empty);
    }
}

The only tool for .NET I have heard of that might begin to address this shortcoming is Microsoft CHESS. It seems a very promising tool although it seems to have stalled somewhat – the only integration is with VS2008; VS2010 is not supported. I’d love to hear of other tools or clever techniques for unit testing multi-threaded code effectively. I haven’t delved too much into the C# 5 async stuff yet, but I’d be interested to know how well it plays with unit tests.

Monday, 4 July 2011

Visualizing TFS Repositories with Gource

I recently came across the gource project, which creates stunning visualizations of your source control history. It doesn’t include built-in support for TFS repositories, but its custom log file format makes it quite simple to work with.

Since the project I worked on recently hit 1,000,000 lines of code (yes, I know that means it needs to be mercilessly refactored), I thought I would create a gource visualization. My example code below has a regular expression to allow me to filter out the bits in source control I am interested in. It also deals with the fact that we imported our solution from SourceSafe, so it needs to get the real commit dates for early items out of the comments.

public void CreateGourceLogFile(string outputFile)
{
    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("http://mytfsserver:8080/"));
    tpc.EnsureAuthenticated();
    VersionControlServer vcs = tpc.GetService<VersionControlServer>();
    int latestChangesetId = vcs.GetLatestChangesetId();
    Regex regex = new Regex(sourceFileRegex); // optional - a regular expression to match source files you want to include in the gource visualisation
    Regex sourceSafeImportComment = new Regex(@"^\{\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d\}");
    int lines = 0;
    using (var writer = new StreamWriter(outputFile))
    {
        for (int changesetId = 1; changesetId < latestChangesetId; changesetId++)
        {
            var changeset = vcs.GetChangeset(changesetId);
            var devEdits = from change in changeset.Changes
                           where
                           ((change.ChangeType & ChangeType.Edit) == ChangeType.Edit
                           || (change.ChangeType & ChangeType.Add) == ChangeType.Add
                           || (change.ChangeType & ChangeType.Delete) == ChangeType.Delete)
                           && regex.IsMatch(change.Item.ServerItem)
                           select change;
            foreach (var change in devEdits)
            {
                DateTime creationDate = changeset.CreationDate;
                var commentMatch = sourceSafeImportComment.Match(changeset.Comment);
                if (commentMatch.Success)
                {
                    creationDate = DateTime.ParseExact(commentMatch.Value,"{dd/MM/yyyy HH:mm:ss}", CultureInfo.InvariantCulture);
                }

                int unixTime = (int)(creationDate - new DateTime(1970, 1, 1)).TotalSeconds;
                writer.WriteLine("{0}|{1}|{2}|{3}", unixTime, changeset.Committer,
                    GetChangeType(change.ChangeType), change.Item.ServerItem);
            }
        }
    }
}

private string GetChangeType(ChangeType changeType)
{
    if ((changeType & ChangeType.Edit) == ChangeType.Edit)
    {
        return "M";
    }
    if ((changeType & ChangeType.Add) == ChangeType.Add)
    {
        return "A";
    }
    if ((changeType & ChangeType.Delete) == ChangeType.Delete)
    {
        return "D";
    }
    throw new ArgumentException("Unsupported change type");
}

Once you have your log file created, just run gource to see an amazing replay of the history of your project:

gource custom.log

Here’s a screenshot:
Gource screenshot 

Sunday, 3 July 2011

Silverlight Music Rating App for KVR One Synth Challenge

After Spotify announced that you only got 10 hours free listening a month, I went in search of some new and interesting sources of music, and one of the things I stumbled across was the monthly KVR One Synth Challenge. Basically the idea is that you have to create an entire track using a single freeware virtual instrument – a different one each month. Despite this limitation, the quality of submissions is consistently impressive.

Voting is done by the community – you have to list your top five tracks. Each month I would download all the tracks and gradually eliminate them from a playlist, making notes on what I liked about each one as I went. This made me wonder if I could create a simple rating tool in Silverlight to help me do this – storing my comments and ratings, and allowing me to easily eliminate tracks from my shortlist.

So I created a simple application called “MusicRater”. At the moment the paths for each KVR OSC contest are hard-coded and I update it each month to point to the new one, but I have plans to make it more configurable in the future. The application makes use of my Silverlight star rating control.

Here’s a screenshot:

MusicRater

You can try it out here, and install it as an out of browser app if that is convenient for you. As of the time of posting, the version at this address is set up to return the tracks for OSC 29, which uses a synth called String Theory, which poses an interesting challenge to the contestants since it is a physical modelling synth. If you enjoy listening, make sure you head over to the voting thread and cast your votes.

Saturday, 2 July 2011

Yahtzee Kata in IronPython

I did another simple kata in IronPython recently, to refresh my memory since I haven’t done much with Python recently. I used my AutoTest for IronPython utility again, and again found myself wanting to invent an equivalent of NUnit’s [TestCase] attribute for Python. The kata is to implement the Yahtzee scoring rules, although the specific instructions I followed describe a different scoring scheme than the most familiar one (seems to be a Scandinavian version).

import unittest

#helpers
def Count(dice, number):
    return len([y for y in dice if y == number])

def HighestRepeated(dice, minRepeats):
    unique = set(dice)
    repeats = [x for x in unique if Count(dice, x) >= minRepeats]
    return max(repeats) if repeats else 0

def OfAKind(dice, n):
    return HighestRepeated(dice,n) * n

def SumOfSingle(dice, selected):
    return sum([x for x in dice if x == selected])

#strategies
def Chance(dice):
    return sum(dice)

def Pair(dice):
    return OfAKind(dice, 2)

def ThreeOfAKind(dice):
    return OfAKind(dice, 3)

def FourOfAKind(dice):
    return OfAKind(dice, 4)
    
def SmallStraight(dice):
    return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0

def LargeStraight(dice):
    return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0

def Ones(dice):
    return SumOfSingle(dice,1)

def Twos(dice):
    return SumOfSingle(dice,2)

def Threes(dice):
    return SumOfSingle(dice,3)

def Fours(dice):
    return SumOfSingle(dice,4)

def Fives(dice):
    return SumOfSingle(dice,5)

def Sixes(dice):
    return SumOfSingle(dice,6)

def Yahtzee(dice):
    return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0

class YahtzeeTest(unittest.TestCase):
    testCases = (
        ((1,2,3,4,5), 1, Ones),
        ((1,2,3,4,5), 2, Twos),
        ((3,2,3,4,3), 9, Threes),
        ((3,2,3,4,3), 0, Sixes),
        ((1,2,3,4,5), 0, Pair), # no pairs found
        ((1,5,3,4,5), 10, Pair), # one pair found
        ((2,2,6,6,4), 12, Pair), # picks highest
        ((2,3,1,3,3), 6, Pair), # only counts two
        ((2,2,6,6,6), 18, ThreeOfAKind), 
        ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found
        ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three
        ((6,2,6,6,6), 24, FourOfAKind), 
        ((2,6,4,6,6), 0, FourOfAKind), # no fours found
        ((5,5,5,5,5), 20, FourOfAKind), # only counts four
        ((1,2,5,4,3), 15, SmallStraight),
        ((1,2,5,1,3), 0, SmallStraight),
        ((6,2,5,4,3), 20, LargeStraight),
        ((1,2,5,1,3), 0, LargeStraight),
        ((5,5,5,5,5), 50, Yahtzee),
        ((1,5,5,5,5), 0, Yahtzee), 
        ((1,2,3,4,5), 15, Chance),
        )

    def testRunAll(self):
        for (dice, expected, strategy) in self.testCases:
            score = strategy(dice)
            self.assertEquals(expected, score, "got {0} expected {1}, testing with {2} on {3}".format(score, expected, strategy.__name__, dice))
        print 'ran {0} test cases'.format(len(self.testCases))
        
if __name__ == '__main__':
    unittest.main()

Friday, 1 July 2011

Blogger Users Beware - Google+ Can Delete Your Blog Images

I was given an invite to Google+ today. I thought it would be interesting to see what the fuss is about, so I signed up. It asked me if I wanted to import any pictures from Picasa. I didn’t think I had any pictures on there – I certainly never visit the site, but I clicked yes anyway just in case there was some stuff I had forgotten about on there. And indeed there was. It imported a couple of random photos I had taken of door hinges to email to my dad, plus a whole bunch of screenshots.

Obviously, that’s not the kind of stuff I want on my Google+ profile, so I deleted the photo albums from my profile page. What I hadn’t realised is that Picassa was where Windows Live Writer had been storing all the images for this blog. And instead of just deleting the albums from my Google+ profile, it also deleted them from Picassa. Not into some kind of recycle bin. Deleted permanently.

Clearly Google have committed a cardinal sin of user interface design – don’t make it easy to accidentally and irrevocably delete all your data. And the data stored on Picassa should only be deleteable from Picassa, not from another completely separate website, even if it is run by the same company.

They have also committed the cardinal sin of customer support – utter unresponsiveness. I guess they can get away with this because they are so big and I’m not paying them any money. Even if they can’t recover my data, a response of some kind would be nice. I’ve already come across several other people who’ve done similar things, leaving blogs that have been running several years completely broken.

Update: they have now responded to say:

Our team can't undelete your photos, but we'll make it clearer that your Picasa photos themselves are displayed on Google+ and not copied. It's the same backend, so photos you upload in Picasa are visible from Google+, and vice versa.

The upshot of that is that this blog is missing all its screenshots and diagrams, almost 100 of them. Some of them I might be able to recover from my PC, although my usual way of taking screenshots and adding them through Windows Live Writer only involves the clipboard so there is no physical file on my machine that I can use to recover the images with. I can only apologise, particularly if you came here to read the NAudio documentation, only to find it missing its architecture diagrams.