Don’t blame Paula!

Posted by Chris on June 13, 2007

Do not point fingers I used to subscribe to the blog Worse Than Failure (formerly The Daily WTF), but it got removed when I was trimming the number of blogs in my reader. If you have not seen it, they post examples of code that is really badly written or designed. Most often there is also a funny story to go with the code. One of the most absurd posts that I remember was one called The Brillant Paula Bean.

It is a very short post, so go read it if you want. For the even shorter summary, it tells the story of a company that brought in a contractor, Paula, to help with a Java project. She was apparently handed some work to do, and for a few months she reported good progress during the weekly status meetings. However when the deadline came closer she asked for some help to finish it in time, and then it became clear that all she had produced was a couple lines of code that could do nothing more than return a misspelled string.

I guess all posts at WTF has to be taken with a grain of salt, but for now let us consider this one to actually be true. Like I said, it is really absurd, but what is it actually that is most absurd here? While there is no question that Paula was not a very good programmer, can we really blame her for this mess? If the story is true, this is clearly an example of a process problem. Why did no one notice there were no commits from her? Why did no one review her code? How did she ever get hired? There are so many ways this mess could have been avoided. For instance if Paula would have been pair-programming, her lack of skills would have been noticed at day one. With smaller tasks it would have been clear that she where having problems much earlier.

Unfortunately, even if the story turns out to be untrue, I do not think it is that uncommon. Change a few of the extremes of the story (the ridiculously low amount of code produced, the quite long time period, the insanely large task she must have been working on to be given so much time) into more realistic ones and I think most of us will recognise situations that we have been in. Maybe not situations that ended up the same way, but definitely situations that had the potential to do so. Things such as not testing the code and application enough, not having code reviews, and working on too large tasks with individual responsibility for the programmer that is given them all have the potential to end up in disasters such as The Brillant Paula Bean. When they do, instead of just pointing fingers at the person who screwed up, ask how it happened. Find out what is the root cause and eliminate it.

Ruby-style iterations in C# 3.0

Posted by Chris on May 10, 2007

While Ruby does have a for-loop, it is not commonly used in idiomatic Ruby code. Instead, to loop a number of times and do something in each run you would write code like this:

5.times do |i|
  print i
end

# equivalent for loop over a range
for int i in 0...5
  print i
end

I do not know about you, but I definitely like the 5.times way better. With the new C# 3.0 (as part of Linq) feature extension methods it is a trivial thing to make it possible to write very similar code in C#:

// using a lambda function, also a C# 3.0 feature
5.Times( i => Console.WriteLine(i) );

// or using a "simple" C# 2.0 delegate
5.Times(delegate (int i)
{
  Console.WriteLine(i);
});

So how does this work? By creating an extension method for int and bringing that into scope (with a using statement) all ints will now be extended with the method Times. Actually, int has of course not really been modified “on the fly” to include a new method, it is really only syntactic sugar for a method call such as IntExtensions.Times(5, i => Console.WriteLine(i));. Here is the simple extension method:

public static class IntExtensions
{
  public static void Times(this int count, Action<int> block)
  {
    for (int i = 0; i < count; i++)
    {
      block.Invoke(i);
    }
  }
}

So what do you think? Am I crazy for even thinking about writing my C# (3.0) code in this way? Would you get confused and angry by looking at the code?

Freedom fosters responsibility

Posted by Chris on May 04, 2007

Intersection in Drachten, Holland

Take a look at the photo to the right. Notice anything specific about it? Here is a hint: think about enforcing rules. See it now? That is right, there are no lanes, road signs, pedestrian crossings or similar. Other than the give-way markings on the ground, the intersection is completely clear of anything that rules how you should act here.

The photo shows a “traffic calmed” roundabout in the city of Drachten, Holland. Most of the city centre is actually completely free of the traffic ruling items mentioned above. But does this not lead to a lot of incidents? Surely there is some meaning behind this idea, but how can this possibly work? The simple answer is that the lack of road signs and such leads people to such a crazy thing as to actually take eye contact with each other. Instead of taking an “I have the right to do this”-attitude, people actually take responsibility and work together to avoid incidents. How many accidents involving cars and pedestrians are not the result the pedestrian simply walking straight out onto a pedestrian crossing expecting any cars to stop. The fact that there is a sign that says it is a pedestrian crossing combined with a law that says cars should stop for pedestrians does not mean that every car will automatically stop! The only thing that this really means is that cars have a responsibility to stop for pedestrians, but pedestrians do not have a right to walk right out into the street.

Although I know analogies can be dangerous, the reason I mention this is that I came to think about it after having a discussion over lunch regarding programming languages and how the code turns out in different ones. The discussion started with Martin talking about how he writes better code in C++ than he does when using C#. And I can vouch for his abilities in both languages, so it is not as simple as that. The reason, he said, was that C++ was more complex than C# and it is easier to get things wrong, so therefore he paid more attention to what he does when coding in C++. Instead of relying on the (sometimes dubiously) safe environment to help you, taking a step back to actually think for a second or two and make sure that what you just wrote not only solves whatever it should but is also meaningful to someone reading it later makes a huge difference.

The fears and skepticism people have about the lack of road signs in the Drachten intersections can be noted when developers skeptic to dynamic languages describe how they feel about them. “Does not the lack of structure make people do all sorts of crazy things? If someone can just open up a class at any time and modify a method (or add new ones), how can it possibly work out in a collaborative environment such as a typical software development project?” For the same reasons as the Drachten intersections lead to fewer accidents. By removing the “secure” environment of compile-time checking, people are actually forced to think and talk to eachother. Developers use better names for classes and methods, and also use tests to specify their intentions, both to the test runner and to other developers.

I want to use one last example. One practice common in agile development (and elsewhere of course) is continuous integration (CI). The idea is simple, integrate whenever any changes to the system are saved. Unfortunately it is also quite common to see this interpreted as “set up some CI server software, then we are done”. While a CI server can definitely be of use, people forget that CI is really just an attitude and has nothing to do with having a CI server. The CI server becomes the road signs of the intersection. Instead of thinking in terms of what your responsibilities are when checking in, you trust the CI server to solve all problems for you.

To summarize: Be sure to not allow yourself or your team to get a false sense of security from processes and rules. Instead focus on the social parts of software development. Individuals and interactions over processes and tools is what it is all about.

Photo downloaded from sociate’s flickr account, used under a Creative Commons Attribution-ShareAlike 2.0 license.

Testing events with unit tests

Posted by Chris on March 13, 2007

How to test events seem to be a question that sometimes comes up regarding unit testing. There are three different things that we want to test when using events.

* Verify that an event subscriber really wires up a listener to an event
* Verify that an event subscriber does what it should when that event is fired
* Verify that an event publisher fires an event when it should

The first two are basically the same. If we can verify that some action that should be taken when an event is fired really does happen then we have of course also verified that the subscriber does listen to the event. But I prefer to start simple with my tests and therefore often end up with a small test like the following one for testing the wiring only:

using System;
using NUnit.Framework;

namespace TestingEvents
{
  [TestFixtureAttribute]
  public class EventsFiringTests
  {
    [Test]
    public void SubscriberWiresListenerToListenToMeEvent()
    {
      FakePublisher publisher = new FakePublisher();

      new SubscriberUnderTest(publisher);

      Assert.AreEqual(1, publisher.ListenToMeSubscriberCount);
    }
  }

  public interface Publisher
  {
    event EventHandler ListenToMe;
  }

  public class FakePublisher : Publisher
  {
    public event EventHandler ListenToMe;

    public int ListenToMeSubscriberCount
    {
      get { return ListenToMe.GetInvocationList().Length; }
    }

    public void FireListenToMe()
    {
      ListenToMe.Invoke(this, EventArgs.Empty);
    }
  }

  public class SubscriberUnderTest
  {
    private string message;

    public SubscriberUnderTest(Publisher publisher)
    {
      message = null;

      publisher.ListenToMe += IAmListening;
    }

    private void IAmListening(object sender, EventArgs args)
    {
      message = "I heard that!";
    }

    public string Message
    {
      get { return message; }
    }
  }
}

This test only tests that the subscriber actually does wire up a listener to the ListenToMe event of the publisher it is instantiated with. The next step is to verify what it does when the event is fired from the publisher. The next test takes care of that.

  [Test]
  public void MessageIsSetWhenListenToMeIsFired()
  {
    FakePublisher publisher = new FakePublisher();
    SubscriberUnderTest subscriber = new SubscriberUnderTest(publisher);

    publisher.FireListenToMe();

    Assert.AreEqual("I heard that!", subscriber.Message);
  }

That takes care of testing that a subscriber does what we expect it to when the event it subscribes to is fired. The final thing that needs to be tested is that a publisher actually fires an event when we expect it to. Lets add a new class, PublisherUnderTest, and another test.

  [Test]
  public void PublisherFiresListenToMeWhenAngry()
  {
    PublisherUnderTest publisher = new PublisherUnderTest();

    bool listenToMeWasCalled = false;
    publisher.ListenToMe += delegate { listenToMeWasCalled = true; };

    Assert.AreEqual(true, listenToMeWasCalled);
  }

  public class PublisherUnderTest : Publisher
  {
    public event EventHandler ListenToMe;

    public void GetAngry()
    {
      if (ListenToMe != null)
      {
        ListenToMe.Invoke(this, EventArgs.Empty);
      }
    }
  }

The test simply assigns an anonymous method to listen to the event from the publisher. In the anonymous method a boolean value is set to true to indicate that the event was fired.

Back from SQL Server Open World 2007

Posted by Chris on March 11, 2007

From thursday evening until saturday afternoon I was at the SQL Server Open World in Denmark. SSOW turned out to be an excellent conference. There where about 140 attendees and speakers and there was a lot of interaction between people. Networking is always important and of course happens at all conferences, but I do believe that SSOW had a couple of things helping make networking very easy. How about these examples?

  • During the first evening after the opening introduction and “technical” presentation they moved everyone into “the party house”. This was where the unfortunate latest employees of Miracle (the conference organizers) happened to live. Note that everyone means about a hundred people, in one small house meant for 4-8 people.
  • The party house had free beer, brewed by Miracle themselves (or rather their sister company that is in the beer brewing business).
  • Friday night was beach party. The conference was held at Lallandia, a vacation resort in Denmark with a big indoors waterland. Networking is just so much easier in a jacuzzi with a beer in your hand.
  • Most conferences try for a 80/20 mixture of serious stuff (sessions) and fun stuff. At SSOW they go for a 50/50 mix. That does not mean there is less serious stuff, just a lot less time to sleep. :)

I gave two presentations. The first one was a completely new one called Working with SQL Server in an agile development environment (though I think I will change that to Agile Data Practices if I give it again). Even though there where only a few attendees I still had a good time, since it was easier to get a good discussion going.

The other presentation was Understanding CLR Integration which I did for the fourth time. I think it went very well, with a lot of good interaction from the audience. I think it was the atmosphere at the conference that encouraged this, I know I saw it in other presentations as well. Two specific things where mentioned in the talk, which I promised to address here:

  • Regarding user-defined aggregates (UDAggs) that can be created as CLR objects, we discussed the problem of the 8000 bytes limitation for MaxByteSize. As I said, this limitation really makes it impossible to use UDAggs for a lot of cases where they would otherwise be an option, for instance the often used examples of calculating a median or concatening strings. However, the really interesting bit is that I posted a feedback item regarding this to Microsoft Connect during the SQL Server 2005 beta testing period. What I said was that the maximum needs to be higher, possibly even indefinite. As the feedback item shows the response from Microsoft was that this was a reasonable request but since it was a non-trivial change it would not make it into SQL Server 2005 (RTM). Wednesday evening however this feedback item was closed and marked as fixed! Unfortunately it does not say how it was fixed or in which version (future service pack of SQL Server 2005, or Katmai the next version of SQL Server?) it is fixed. I am hoping that this gets clarified in the feedback item and also discussed it with Mark Souza from Microsoft who was there (with Lubor Kollar) as speakers and Microsoft representatives.
  • The other thing was a question regarding the fact that not all system assemblies can be loaded in SQLCLR. The question was if the list of approved assemblies is available somewhere. I found this blog post by Bob Beauchemin to be a good answer.

Download the presentations (as PDFs):

All in all I had a great time. If you are a SQL Server speaker I would definitely recommend putting in an abstract for a session next year.

Public fields vs properties and a bit of YAGNI

Posted by Chris on February 24, 2007

A month ago or so a friend of mine IM:d me and said they were having a discussion regarding properties, if they should always be used to access fields or if you could sometimes just make the fields public. My response was instant (it was IM after all): Always use properties

Actually, even though I really think that public fields should not even be allowed by the language, I confessed that I do sometimes use them in test doubles that I create for my unit tests (for instance for setting a value that I want some method to return when it is called in a test). But this is the only time I use public fields and I am trying to get away from it.

My friend did not agree with me and pointed me to a post by Jeff Atwood. We did discuss this further that evening over a couple of beers, but I am not sure if I managed to persuade him. Probably not. :)

Some other smart people at least seem to agree with Jeff and my friend, but I do not buy into the arguments. It seems there are three main arguments given by proponents of public fields:

* Performance: Rico Mariani, performance guru at Microsoft, discusses performance differences between public fields and properties (as a part of a larger performance quiz on using value types for performance) in two posts. This is the only reason that I can actually sometimes accept. It is of course impossible to argument against it since the numbers are pretty clear, but in general most applications do not see any real difference from these issues. And if the language, and VM of course, did not even allow public fields I think more work could be done there to avoid problems.

* Trivial properties are just meaningless wrapper code: I really do not understand this argument. I guess these are the same people who name a variable of type Window to wnd instead of window, or a method that inserts a new value into some container to InsVal. Sure, silly examples, but my point is that typing is not really an issue with modern IDEs. Type prop and hit tab and you have got a property backed by a private field. More lines to read with properties? Sure, but seriously, how is that an issue? Personally I think the code is more readable and understandable with consistent use of properties for accessing an objects internals. And again, if the language did not allow public fields and instead had some syntactic sugar for easily creating properties backed by private fields, like public property string Name;, this would not even be an issue. C# 3.0 by the way seems to have something similar, as you can use public string Name { get; set; } to accomplish this, although I think the previous one would be better.

* Creating a trivial property is a premature decision because they will most often stay trivial forever: I do not like this. Even if you think trivial properties makes it more difficult to understand the code, calling YAGNI on the decision to create one instead of using a public field to me is a misinterpretation or misuse of YAGNI. What it says that “you should defer making a decision until the latest responsible moment“, not simply “defer it until the latest possible moment”. What happens if you create a public field and then later change it into a property when it is used by clients? That is a breaking change and clients will need to recompile from source. Not a very responsible thing to do.

Even if I would agree with the above arguments, there are enough quirks and problems that you might get into from using public fields that I still recommend avoiding them. These include problems with parts of the .NET framework (databinding and reflection for instance), naming convention questions, and of course most importantly how changing from a public field to a property can break code in several ways, requiring recompiling from source. See the comments to Jeff Atwood’s post above (also summarized by himself in the updated part of the post), and the comments Eric Gunnerson’s post (summarized in a follow-up post) for more info.

Databinding a WPF control to something else than a static property

Posted by Chris on February 21, 2007

A couple of days ago I was trying to solve a problem with databinding in WPF. What I was trying to do was to create columns for a ListView (with a GridView set for it’s view). Creating columns was no problem, neither was binding the columns to some property of the objects in the list that was set as the ItemsSource of the ListView. The problem was however that the “properties” that I wanted to bind the columns to was not really properties (in the C#/.NET vocabulary).

To create a binding on a normal statically declared property, code like the below would work:

Binding binding = new Binding();
binding.Path = new PropertyPath("SomeProperty");
binding.Mode = BindingMode.OneWay;

FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);

DataTemplate template = new DataTemplate();
template.VisualTree = textElement;

GridViewColumn column = new GridViewColumn();
column.CellTemplate = template;

With this code in place I now have a column containing a single textblock. The Text property of that textblock will contain the value of the property SomeProperty for each object in the collection that is set as the ItemsSource of the listview. However, as I mentioned above, the problem was that my object (or rather, the object’s type) did not have a static property called SomeProperty. Instead it has a property called Properties, which is a Dictionary containing a “dynamic” set of objects each representing some property (in the general meaning of the word, not in the C#/.NET vocabulary) of the object I am showing on the current row of the listview.

public class ShownInList {
  ...

  public Dictionary<string, PropertyObject> Properties {
    ...
  }
}

public class PropertyObject {
  ...

  public string Name {
    ...
  }

  public object Value {
    ...
  }
}

As seen above, each property has a name and a value. What I now want to do is to create a column and bind it to a property with a specific name, so that it will show the value of that property. The intuitive thing to try was to create the binding with a PropertyPath initialized with a string such as “Properties['SomeProperty']“. This did not work however, and neither did the different ways I tested to write the property path string.

Some Googling later I found the solution. Instead of binding to a property using a PropertyPath I could skip setting up the path at all and instead use a custom converter. Here is what I did:

Binding binding = new Binding();
binding.Converter = new PropertyObjectConverter();
binding.ConverterParameter = "SomeProperty";
binding.Mode = BindingMode.OneWay;

...

public class PropertyObjectConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      ShownInList obj = (ShownInList)value;

      string key = (string)parameter;
      return obj.Properties.ContainsKey(key) ?
        obj.Properties[key].Value :
        null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      throw new NotImplementedException();
    }
}

The binding is set up to call a converter to get a value to show. The converter is called with the object, of type ShownInList, that is the source for the current row, and a parameter describing which property in the dictionary I want to bind to. If the dictionary contains a propertyobject with the name as key then it returns the Value property of that object, otherwise it returns null.

If anyone has a better solution than mine then please add a comment about it.

Strange card games and methodology discussions

Posted by Chris on February 09, 2007

One of the most demoralizing and improductive things that can happen to a project and team are endless discussions about methodology.

Do not get me wrong here, how we work should definitely not be a once-and-for-all decision that we can never change. Quite the contrary, we must reflect regularly on the process and how we work, make changes as necessary and then follow up on those changes. But the point here is that we make these changes from some known base and we make them based on experiencing that something does not work for us. Most importantly changes are introduced at regular points in time (after an iteration), and we try them for some period of time long enough to be able to measure and decide whether they help us or not. What I am referring to with endless discussions about methodology is when a team starts out without having a process that they collectively agree upon and understand.


Executive summary: Before the start of a project, gather all the team members and collectively discuss and decide upon the process that the team will follow.


This reminds me of a card game we played in school at a class in Organizational/Group Theory (or something similar). The teacher started by telling us that starting now, we were not allowed to talk to each other. No oral communication whatsoever was allowed.

We were then divided into groups, I think there were five groups of five people each (but it’s not important). Each group were placed at a table that had a sheet of paper and a deck of cards. On the paper she had written down the rules for the card game we were going to play. Silently the paper was passed around between the five people at the table so that everyone knew the rules. I do not remember the rules exactly, but it was a very basic kind of trick-taking game. The person who took the highest number of tricks was the winner.

When everyone at the table had read the rules she collected all the papers and told us to start playing. There were no “official” scoring (we had nothing to write on) so it was mostly for fun, but as always the winning instinct in people set in and we had a good time playing. Sometimes you would win a trick and throw your hands in the air in triumph, but noone was allowed to say anything or make any noise. After playing for a while we were stopped and one person from each table were instructed to move counter-clockwise to the next table.

Play then commenced again and everyone was happy. Until it happened for the first time that this new person and someone else reached for the trick to collect it at the same time. Confusion arose, the two “winners” looked at each other in anger (maybe not that much anger), and everyone wondered what was going one. Was this new guy trying to cheat? No talking was allowed, so after a while of looking and gesturing someone more or less just grabbed the trick and play continued. This problem was intensified when another person from each table was moved to a new one, this time clockwise. Now it was suddenly a very chaotic game of trick-taking with a lot of silent arguing going on. I think we switched one more time before we finished and discussed what had happened.

What did happen was of course that each table started out with slightly different variations of the same rules. When we were not allowed to discuss them then everyone, especially the “stronger” ones, just did things their way. Some “weaker” individuals just did not care and gave up their wins, even though they knew they had won, when someone else reached for the cards. I seem to remember that there were even someone who after figuring it out just started faking a win by reaching for the cards, bullying the others away from them.

The reason we did this exercise was to understand and experience the dynamics of team membership and disagreement. The strong natural leaders often came out winners while others did not win anything. But the reason I compare this with methodology discussions is the fact that we had different sets of base processes (rules) that we tried to follow. Sure, if we would have been allowed to talk about it I think we would eventually have decided upon some common rules that we could all follow. But the person that had to give up a trick that he thought he had won would not be happy, and the discussions would most likely be lengthy and tiresome. What we should have done was of course to make sure that before we started the game everyone agreed upon the same rules.

This is how it needs to be done in our projects as well. Before starting a new project a team should sit down and decide how they want to work, and make sure everyone commits to following the process decided upon. This might be as simple as saying “we will follow XP by the book” or you can go the Crystal way of deciding which practices to use. The important thing is that it is perfectly clear what is decided upon and that everyone commits to following it. Even if someone does not agree that a certain practice is a good one they should commit to following it if the team collectively decides to include it. After a couple of iterations the practice can be evaluated and changed if it did not work out. And this process of pinning down the methodology needs to be done before the project starts. Just like in the card game, having these discussions when everyone is busy doing Real Work unfortunately guarantees that they will be lengthy and tiresome, and some people will get run over and feel bad about it.

To sum up: Before starting a project, make sure that everyone in the team understands and commits to the process the team is going to follow. But do not forget to reflect regularly and change the process as the team sees necessary.

Article about CLR integration posted

Posted by Chris on February 02, 2007

About a year ago I wrote an article for the SQL Server Standard magazine called Understanding CLR integration in SQL Server 2005. This article is now also available here at my site, in the Articles section. It is an overview of how the CLR and SQL Server work together and tries to show how this is a much safer and better way to extend SQL Server than using extended stored procedures.

Instantiating a WPF control from an NUnit test

Posted by Chris on January 08, 2007

If you try to run a test like the following from NUnit, you will find that it does not work. You get an InvalidOperationException telling you that “The calling thread must be STA, because many UI components require this”.

[Test]
public void CanCreateAndShowWpfWindow()
{
  Console.WriteLine(Thread.CurrentThread.GetApartmentState());

  System.Windows.Window window = new System.Windows.Window();
  window.Show();
}

NUnit (both the GUI and console version) by default runs it’s threads in a multithreaded apartment (MTA), which can be verified by looking at the Console.Out tab. As the message says, instantiating a WPF Window requires that the calling thread is running in a single-threaded apartment (STA).

The simplest way to make this work is to configure NUnit to run tests in an STA thread. Create a config file for NUnit to use (see the docs for info on how to name it) and add the following XML configuration (or just add to your existing one):

<configuration>
  <configsections>
    <sectiongroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler">
      </section>
    </sectiongroup>
  </configsections>
</configuration>

<nunit>
  <testrunner>
    <add key="ApartmentState" value="STA"></add>
  </testrunner>
</nunit>

This tells NUnit to run all tests in STA threads. However, if you just want a single test (or some but not all) to run in STA (or MTA, if you have used the above configuration to set the default to STA) you have to resort to code. You need to start a new thread and set the apartment state you want, and then run your unit test in that thread. I used CrossThreadTestRunner (from Peter Provost) and just added support to choose which apartment state to create and run a thread in. The following code example shows how to use it:

[Test]
public void CanCreateAndShowWpfWindow()
{
  CrossThreadTestRunner runner = new CrossThreadTestRunner();
  runner.RunInSTA(
    delegate
    {
      Console.WriteLine(Thread.CurrentThread.GetApartmentState());

      System.Windows.Window window = new System.Windows.Window();
      window.Show();
    });
}

My modified CrossThreadTestRunner class looks like this:

using System;
using System.Reflection;
using System.Security.Permissions;
using System.Threading;

namespace UnitTestThreadApartmentState
{
  public class CrossThreadTestRunner
  {
    private Exception lastException;

    public void RunInMTA(ThreadStart userDelegate)
    {
      Run(userDelegate, ApartmentState.MTA);
    }

    public void RunInSTA(ThreadStart userDelegate)
    {
      Run(userDelegate, ApartmentState.STA);
    }

    private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
    {
      lastException = null;

      Thread thread = new Thread(
        delegate()
        {
          try
          {
            userDelegate.Invoke();
          }
          catch (Exception e)
          {
            lastException = e;
          }
        });
      thread.SetApartmentState(apartmentState);

      thread.Start();
      thread.Join();

      if (ExceptionWasThrown())
        ThrowExceptionPreservingStack(lastException);
    }

    private bool ExceptionWasThrown()
    {
      return lastException != null;
    }

    [ReflectionPermission(SecurityAction.Demand)]
    private static void ThrowExceptionPreservingStack(Exception exception)
    {
      FieldInfo remoteStackTraceString = typeof(Exception).GetField(
        "_remoteStackTraceString",
        BindingFlags.Instance | BindingFlags.NonPublic);
      remoteStackTraceString.SetValue(exception, exception.StackTrace + Environment.NewLine);
      throw exception;
    }
  }
}

A final note: As opposed to NUnit, both TestDriven.Net and Resharper’s Unit Test Runner run tests in STA threads. I got bitten by this recently when all the tests where green on my machine, but when I committed the build server went red on me. I was using Resharper to run the tests, while NUnit-Console was used on the server. Hope this might help someone else in the same situation.