Category Archives: nifty

Bring back the types!

When you’re working with C# and reflection, you might end up in a situation where you have “lost” the type. For example, if you’ve deserialized an incoming message of some kind, you might have code that needs to do this:

void HandleTheMessage(object message)
{
    // ... nasty reflection code in here
}

Usually, when you want to do different stuff depending on the type of an object, you just call that object and let it do what it deems reasonable. That’s a good object-oriented way of delegating behavior to objects, totally anti-if campaign compliant and all. But in cases where the object you need to act upon is an incoming DTO, it’s usually not a good approach to put logic on that DTO.

This is a good time to do a “handler lookup” 1 in your IoC container for something that can handle an object of the given type. It goes like this: Given message: T, find handler: IHandle<T> and invoke handler with message.

In C#, that might look like this:

void HandleMessage(object message)
{
    var messageType = message.GetType();
    var handlerType = typeof(IHandler<>).MakeGenericType(messageType);
    var handlerInstance = container.Resolve(handlerType);
 
    handlerInstance.GetType()
        .GetMethod("Handle")
        .Invoke(handlerInstance, new object[] { message });
}

That’s not too bad I guess, but working at this untyped level for longer than this turns out to be cumbersome and hard to read and understand. It wouldn’t take more than a few lines more of invoking things via reflection before the dispatch of the message has turned into a mess! And then add the fact that exceptions thrown in method invocations made with reflection will be wrapped in TargetInvocationExceptions.

Consider this alternative approach where I use reflection to invoke a private generic method, closing it with the type of the message:

static readonly MethodInfo OpenDispatchMethod
    = typeof(TheClassWeAreIn).GetMethod("Dispatch", BindingFlags.NonPublic | BindingFlags.Instance);
 
void HandleMessage(object message)
{
    var messageType = message.GetType();
    var closedDispatchMethod = OpenDispatchMethod.MakeGenericMethod(messageType);
    closedDispatchMethod.Invoke(this, new object[] { message });
}
 
void Dispatch<TMessage>(TMessage message)
{
    // whee, we can work with TMessage in here!
    var handler = container.Resolve<IHandle<TMessage>>();
    handler.Handle(message);
}

This way, the Dispatch method can have the bulk of the logic and it does not need to bother with the reflection API. Nifty!

  1. I don’t know if there’s a better name for this pattern. I tried to ask Twitter, but I mostly got “it’s usually not a good idea to do that” – well, most patterns are usually not a good idea: all patterns should be applied only in cases where they make sense </stating-the-obvious>

Domain events salvation example

One of the immensely awesome things that Udi Dahan has – if not invented, then at least brought to my attention – is the awesome “domain events – salvation” pattern.

If you’re familiar with the onion architecture, you’ve probably more than once experienced the feeling that you had the need to pull something from your IoC container some place deep in your domain model. In my experience, that often happens when you have a requirement on the form “when something happens bla bla, then some other thing must happen bla bla” where “something” and “some other thing” aren’t otherwise related.

An example could be when a new account (a.k.a. a customer that we mean to do business with) is registered in the system, we should make sure that our credit assessment of the account is fresh enough that we dare do the businesss.

I’ve found that the “domain events – salvation” provides a solution to that problem. Check this out:

public class Account
{
    public void Register()
    {
        // ... do stuff that marks this account as registered
 
        DomainEvents.Raise(new AccountRegistered(this));
    }
}

“Whoa, what was that?” you might ask… that was a domain object that did some stuff, and in the end it raised a “domain event”, telling to the world what just happened. And yes, that was a domain object calling out to some static nastiness – but I promise you, it isn’t as nasty as you may think.

I’d like to assure you that the Account class is fully unit testable – i.e. it can be tested in isolation, just like we want. And that’s because we can abstract the actual handling of the domain events out behind an interface, IHandleDomainEvents, which is what actually gets to take care of the domain events – something like this:

public class DomainEvents
{
    public static IHandleDomainEvents Current = new DevNullDomainEventsHandler();
 
    public static void Raise(T domainEvent)
    {
        Current.Handle(domainEvent);
    }
}

and then IHandleDomainEvents can be implemented in several flavors and “injected” into the domain as a static dependency, e.g. this bad boy for testing:

public class TestDomainEventsHandlers : IHandleDomainEvents
{
    readonly List raisedDomainEvents = new List();
 
    public IEnumerable RaisedDomainEvents { get { return raisedDomainEvents; } }
 
    public voic Handle(T domainEvent)
    {
        raisedDomainEvents.Add(domainEvent);
    }
}

which can be used by installing a new instance of it in the setup phase of each test, and then running assertions against the collected domain events in the assert phase.

The coolest part though, is the production implementation of IHandleDomainEvents – it may look like this:

public class CastleWindsorDomainEventDispatcher : IHandleDomainEvents
{
    readonly IWindsorContainer container;
 
    public CastleWindsorDomainEventDispatcher(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public void Handle(T domainEvent)
    {
        var subscribers = container.ResolveAll<ISubscribeTo<T>>().ToList();
 
        try
        {
            subscribers.ForEach(s => s.Handle(domainEvent));
        }
        finally
        {
            subscribers.ForEach(s => container.Release(s));
        }
    }
}

thus delegating the handling of domain events to all implementors of ISubscribeTo<TDomainEvent>. This way, if I have registered this guy in my container:

public class EnsureCreditAssessmentIsFresh : ISubscribeTo<AccountRegistered>
{
    public EnsureCreditAssessmentIsFresh(ILookMaADependency lookMaADependency)
    {
        this.lookMaADependency = lookMaADependency;
    }
 
    public void Handle(AccountRegistered accountRegistered)
    {
        // possibly initiate new credit assessment in here...
    }
}

I can kick off a new credit assessment workflow when a new account is registered, and everything is wired together in a way that is semantically true to the domain. Also, my domain object suddenly get to pull stuff from the container (albeit in an indirect fashion), without even knowing about it!

Developing .NET applications very rapidly

In my current position as an agile .NET dude at d60, I have already found myself in need of rapidly building several small applications and services from scratch.

This way of working reminds me a lot about some of the things that Dan North talked about in his “From months to minutes – upping the stakes” talk at GOTO Aarhus 2010.

In the talk, Dan described how he was part of a team that would rapidly prototype and deliver working systems to some stock exchange or something, and in doing this they would often start from scratch and replace the existing applications, instead of adapting old ones. The advantage is that you get to take some shortcuts when you’re making fairly short-lived applications, you don’t have to carry the burden of old legacy crap, you get to re-do, possibly undo(?) almost every decision some time, and you become really good at building stuff from scratch!

So, this is cool, and I think he said a lot of things that really make sense. But how can you build stuff very rapidly when you’re a .NET developer in a Microsoft shop, and your customer has based everything on Microsoft technology? You would think that a .NET developer would be slow compared to the hip coders working with Node.js, Clojure and [insert hip new technology here]…?

Well, it just so happens that .NET developers are actually pretty lucky in that regard. In this post, I’d just like to go through a few of the things that enable us to deliver stuff really quickly, both .NET and not-necessarily-.NET-things.

Git and GitHub

Like all sensible coding teams, we have moved to distributed source control. We have some pretty skilled Git-people among our developers, so Git was the natural choice. And since we’re not really interested in maintaining our own servers, it makes the most sense to have some hosted Git repositories somewhere – and for that, we got a company account at GitHub, because it’s a great place to host Git repositories.

Git’s branching model is just so extremely fast and lightweight that I’m wondering how I ever managed to get anything done in Subversion. Well, I guess I just didn’t update & commit that often then.

Is anyone still using Subversion? Why?

TeamCity

We have our own locally hosted TeamCity server to check out our code from GitHub, build it, run tests, create NuGet packages etc. Configuring and maintaining TeamCity is really easy compared to CruiseControl.NET, which I used to use – and with the extremely cool feature branch support of TeamCity 7.1, our build server will automatically check out, build, and test my branch if I name it feature-whatever_I_am_working_on when I push it to GitHub!

NuGet

When you want to build stuff rapidly in .NET, there’s really no way you can ignore NuGet – this is how we get to quickly pull down all of the open source libraries and frameworks that we’re using to build cool stuff.

In addition to the free open source stuff, we also NuGet-pack all of our purchased libraries if they’re not already in a .nupkg. And finally, we pack our own shared libraries as NuGet packages as well (actually, TeamCity does this for us automatically on every successful build…), which is how we distribute shared assemblies like e.g. assemblies with Rebus messages.

NuGet has been really easy and smooth in this regard. I’m sorry that I never tried OpenWrap, though – I’m wondering if anyone is using that, or if everybody has moved to NuGet?

Our own NuGet package repository

In order to reduce the friction with NuGet, we have our own NuGet package repository. NuGet.org is just damn slow, and it doesn’t host all of our 3rd party and home-rolled packages.

At first, we used TeamCity to do this, but the NuGet extension in Visual Studio doesn’t remember your credentials, so you have to constantly punch in your username and password if you’ve enabled authentication. This was just too tedious.

Then we hosted our own stand-alone NuGet Server, which would have been OK if it weren’t for the fact that we’re often working outside of our office, and often on other companies’ VPNs. This doesn’t go well with a privately hosted NuGet server.

But then someone had the crazy idea that we should use DropBox as our NuGet repository! This is as crazy as it is ingenious, because we’re already using DropBox to share documents and stuff, so it didn’t really require anything to just throw all of our NuGet packages into a shared folder… which is what TeamCity also does whenever it has packed up something for us, immediately synchronizing the new package to everyone who’s connected to a network.

This way, we can always get to include our NuGet packages, even when we’re building new stuff on a train with a flaky internet connection. As I said: Crazy, yet ingenious!

Free choice of frameworks and tools

Last, but not least, I think a key to rapidly building stuff is to free developers’ hands so that they can use the tools they like to use best and feel are best for the given task.

It seems many companies are afraid that developers might pollute their applications with questionable libraries and bad decisions, but my feeling is that most developers are totally capable of handling this freedom and will respond with a sense of responsibility and care.

Conclusion

These were a couple of things that I could think of that help us build cool stuff and deliver often. As I may have already insinuated, I’m not sure this way of working would work on large monolithic applications that must live for very long.

But then again, in my experience many systems live for too long because they’ve become too huge, and thus too big and expensive to replace – it is often very healthy for systems to be divided into smaller applications that are well integrated, but each application in itself is fairly small and decoupled and thus doesn’t constitute a huge risk and equally huge endavour to replace.

Locking oneself out of SQL Server and the good old registry diff trick

Probably one of the oldest tricks in the book, but definitely one that should not be forgotten, is the Good Old Registry Diff Trick. You see, the other day I accidentally locked myself out of my local SQL Server by making a classic mistake: I deleted my own login!

Well, actually I had created a SQL login that I planned on using after having deleted the login used by my Windows account, but I had forgotten til enable the “Mixed mode authentication” setting, and thus only Windows authentication was allowed.

A little bit of Googling revealed a blog post that mentioned a “LoginMode” key somewhere in the machine’s registry, but my registry did not contain the branch mentioned in the blog post.

Good Old Registry Diff Trick to the rescue!

I went into another machine with a functional SQL Server that I could access, and made sure that only Windows authentication was allowed. Then I used Regedit to export the entire contents of the HKEY_LOCAL_MACHINE hive into a file called “before.reg”. Then I went in and changed authentication mode to “Mixed mode”, and repeated the export into another file, “after.reg”.

Then I loaded a diff tool with the following two files, giving me this:

which revealed that the [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQLServer] branch had the “LoginMode” key, which I could then change from “1″ to “2″ in order to allow “Mixed mode authentication” on my almost-impenetrable SQL Server, allowing me to log in.

Thank you, Good Old Registry Diff Trick.

Little nifties #1

Almost always, the first extensions methods I add to a system are these:

public static class EnumerableExtensions
{
    public static string JoinToString<T>(this IEnumerable<T> enumerable, Func<T, object> selector, string separator)
    {
        return enumerable.Select(selector).JoinToString(separator);
    }
 
    public static string JoinToString<T>(this IEnumerable<T> enumerable, Func<T, object> selector)
    {
        return enumerable.Select(selector).JoinToString(", ");
    }
 
    public static string JoinToString(this IEnumerable enumerable, string separator)
    {
        var strings = enumerable.Cast<object>()
            .Select(e => e == null ? "(null)" : e.ToString())
            .ToArray();
 
        return string.Join(separator, strings);
    }
}

which allows me to format any sequence of stuff sensibly, easily, and inline, e.g. like so:

Log.WarnFormat("Some stuff happened to stuff with these names: {0}", names.JoinToString(", "));

and so:

Log.WarnFormat("Some stuff happened to things with these names: {0}", things.JoinToString(t => t.Name));

and so:

catch(ReflectionTypeLoadException exception)
{
    Log.ErrorFormat(@"ZOMG!!111something happened!!
 
 
{0}", exception.LoaderExceptions.JoinToString(Environment.NewLine));
}

Nifty!

Assuring that those IWantToRunAtStartup can actually run at startup

When building NServiceBus services based on the generic host, you may need to do some stuff whenever your service starts up and shuts down. The way to do that is to create classes that implement IWantToRunAtStartup, which will be picked up by the host and registered in the container as an implementation of that interface.

When the time comes to run whoever wants to run at startup, the host does a

container.ResolveAll<IWantToRunAtStartup>()

to get all the relevant instances (or something similar if you aren’t using Windsor…).

If, however, one or more instances cannot be instantiated due to missing dependencies, you will get no kind of warning or error whatsoever! 1 This means that the service will silently ignore the fact that one or more IWantToRunAtStartups could not be instantiated and run.

In order to avoid this error, I have written a test that looks somewhat like this:

[Test]
public void WhoeverWantsToRunAtStartupCanActuallyRun()
{
  var container = new WindsorContainer();
 
  PerformTheUsualRegistration(container);
 
  var typesThatWantToRun = from type in typeof (MyService.EndpointConfiguration).Assembly.GetTypes()
                         where typeof(IWantToRunAtStartup).IsAssignableFrom(type) 
                             && !type.IsAbstract && !type.IsInterface 
                         select type;
 
  ManuallyRegister(container, typesThatWantToRun);
  RegisterFakeBus(container);
 
  var typesThatCouldRun = container.ResolveAll<IWantToRunAtStartup>().Select(c => c.GetType());
  var typesThatCouldNotRun = typesThatWantToRun.Except(typesThatCouldRun);
 
  if (typesThatCouldNotRun.Any())
  {
    Assert.Fail(string.Join(Environment.NewLine + Environment.NewLine,
          typesThatCouldNotRun.Select(t => GenerateErrorDetailsFor(t, container)).ToArray()));
  }
}
 
string GenerateErrorDetailsFor(Type type, IWindsorContainer container)
{
  // first, register the class as itself if is has not already been done
  if (!container.Kernel.HasComponent(type))
  {
    container.Register(Component.For(type).Named(type.name + " that wants to run"));
  }
 
  // next, make Windsor throw an exception with all the nasty details...
  var exceptionText = "";
 
  try
  {
    container.Resolve(type);
  }
  catch (HandlerException e)
  {
    exceptionText = e.Message;
  }
 
  return string.Format(@"Class: {0}
 
Reason:
 
{1}", type.Name, exceptionText);
}
 
void PerformTheUsualRegistration(IWindsorContainer container)
{
  container.Install(FromAssembly.Containing<MyService.EndpointConfiguration>());
}
 
void ManuallyRegister(IWindsorContainer container, IEnumerable<Type> typesThatWantToRun)
{
  container.Register(typesThatWantToRun
                        .Select(t => Component.For<IWantToRunAtStartup>().ImplementedBy(t))
                        .ToArray());
}
 
void RegisterFakeBus(IWindsorContainer container) 
{
  container.Register(Component.For<IBus>().Instance(MockRepository.GenerateMock<IBus>());
}

I admit that the code is kind of clunky even though I distilled the interesting parts from some of the plumbing in our real test… moreover, our real test is iterating through all the possible configurations our container can have – one for each environment – so you can probably imagine that it’s not pretty :)

But who cares??? The test has proven almost infinitely useful already! Whenever something that wants to run at startup cannot run at startup, TeamCity gives us error messages like this:

Class: RunSomething
 
Reason:
 
Can't create component 'RunSomething that wants to run'  as it has dependencies to be satisfied. 
RunSomething that wants to run is waiting for the following dependencies: 
 
Services: 
- OneOfOurProjects.Api.ISomethingElse which was not registered.
  1. At least this is the case when using Castle Windsor – I don’t know if this is also the behavior of other IoC containers… Maybe someone can clarify this…?

Shouldly – better assertions

Today I came across Shouldly, as I followed a link in a tweet by Rob Conery. I have a thing for nifty mini-projects, so I immediately git clone http://github.com/shouldly/shouldly.git‘d it, and pulled it into a small thing I am building.

What is Shouldly? Basically, it’s just a niftier way of writing assert statements in tests. It fits right in between NUnit and Rhino Mocks, so you will get the most out of it if you are using those two for your unit tests. Check out this repository test – first, arrange and act:

var notes = new Notes{Artist="Josh Rouse", Title="Winter In The Hamptons"};
repo.Save(notes);
var id = notes.Id;
 
var loadedNotes = repo.FindOne(id);

and then, usually the assert would look something like this:

Assert.AreEqual("Joe Rouse", loadedNotes.Artist);
Assert.AreEqual("Winter In The Hamptons", loadedNotes.Title);

- yielding error messages like this:

NUnit.Framework.AssertionException:   Expected string length 9 but was 10. Strings differ at index 2.
  Expected: "Joe Rouse"
  But was:  "Josh Rouse"
  -------------^

which is probably OK and acceptable, because how would NUnit know any better than that?

Check out what Shouldly can do:

loadedNotes.Artist.ShouldBe("Joe Rouse");
loadedNotes.Title.ShouldBe("Winter In The Hamptons");

- yielding error messages like this:

NUnit.Framework.AssertionException: loadedNotes.Artist
        should be
    "Joe Rouse"
        but was
    "Josh Rouse"

which IMO is just too nifty to ignore!

Shouldly takes advantage of the fact the the current StackTrace has all the information we’re after when the assert is an extension method, which is extremely cool and well thought out.

Moreover, it integrates with Rhino Mocks, yielding better messages when doing AssertWasCalled stuff: Instead of just telling that the test did not pass, it tells you exactly which calls were recorded and which one was expected – a thing that Rhino Mocks has always been missing.

Conclusion: YourNextProject.ShouldContain("Shouldly")

Castle Windsor debugger visualization

A while ago, I noticed that Krzysztof Ko?mic was tweeting regularly about adding debugger visualization to Windsor. At the time, I wasn’t really paying attention, so I didn’ t actually understand what he was doing.

Today, I was coding some stuff, and I downloaded the latest and greatest Windsor 2.5 (from August 2010), and after a while I found myself stepping through some code in a small web application I was building from scratch – and that’s when I found out what he was rambling about…. check this out:

Windsor debugger visualization

See how the container renders itself as a list of all the components it contains, followed by a list of “Potentially Misconfigured Components”…?

How cool is that? (pretty cool, that’s how cool it is!)

Not a ground-breaking earth-shaking feature on the grand scale of cool stuff, but sometimes it’s the little things…

(I’m puzzled, however, as to why the headline says “Count = 4″ in the “Potentially Misconfigured Components” section when the count is clearly 2…?)

Scheduling recurring tasks in NServiceBus

A while ago, on a project I am currently involved with which is based on NServiceBus, we needed to publish certain pieces of information at fixed intervals. I was not totally clear in my head on how this could be implemented in an NServiceBus service, so I asked for help on Twitter, which resulted in a nifty piece of advice from Andreas Öhlund: Set up a timer to do a bus.SendLocal at the specified interval.

That’s exactly what we did, and I think we ended up with a pretty nifty piece of code that I want to show off :)

PS: bus.SendLocal(message) effectively does a bus.Send(((UnicastBus)bus).Address, message) – i.e. it puts a message, MSMQ and all, in the service’s own input queue.

First, we have an API that looks like this (looking a little funny, I know – wait and see…):

public interface ISchedule
{
    void Every(TimeSpan interval, Func<IMessage> messageFactoryMethod);
}

- which is implemented like this (registered as a singleton in the container):

public class ServerBasedTimerSchedule : ISchedule, IDisposable
{
    readonly IBus bus;
    readonly List<System.Timers.Timer> timers = new List<System.Timers.Timer>();
 
    public ServerBasedTimerSchedule(IBus bus)
    {
        this.bus = bus;
    }
 
    public void Every(TimeSpan interval, Func<IMessage> messageFactoryMethod)
    {
        var timer = new System.Timers.Timer();
        timer.Elapsed += (_, __) => bus.SendLocal(messageFactoryMethod());
        timer.Interval = interval.TotalMilliseconds;
        timer.Start();
        timers.Add(timer);
    }
 
    public void Dispose()
    {
        timers.ForEach(timer => timer.Dispose());
    }
}

The System.Timers.Timer is a timer which uses the thread pool to schedule callbacks at the specified interval. It’s pretty easy to use, and it fits nicely with this scenario.

Now, in combination with this nifty class of extension goodness:

public static class TimeSpanExtensions
{
    public static TimeSpan Seconds(this int seconds)
    {
        return TimeSpan.FromSeconds(seconds);
    }
 
    public static TimeSpan Minutes(this int minutes)
    {
        return TimeSpan.FromMinutes(minutes);
    }
 
    // ... etc + for doubles as well
}

- we can schedule our tasks like so:

public class ScheduleRealTimeDataPublishing : IWantToRunAtStartup
{
    public ScheduleRealTimeDataPublishing(ISchedule schedule)
    {
        this.schedule = schedule;
    }
 
    public void Run()
    {
        schedule.Every(5.Seconds(), () => new PublishRealTimeDataMessage());
    }
 
    public void Stop()
    {
    }
}

Now, why is this good? It’s good because the actual task will then be carried out by whoever implements IHandleMessages<PublishRealTimeDataMessage> in the service, processing the tasks with all the benefits of the usual NServiceBus message processing pipeline.

Nifty, huh?

Looking over the simplicity and elegance of this solution, I’m kind of embarassed to tell that my first take on this was to implement the timer almost exactly like above, except instead of bus.SendLocal in the Elapsed-callback, we had a huge event handler that simulated most of our message processing pipeline – including NHibernateMessageModule, transactions, and whatnot….

Please note that ScheduleRealTimeDataPublishing is not re-entrant – in this form its Every method should only be used from within the Run and Stop methods of implementors of IWantToRunAtStartup, as these are run sequentially.

Code golf

The result of Kodehoved’s code golf competition has been found, and I got a shared 5th place.

The task was to add two large integers together by representing the integers with arrays of their digits, thus allowing them to become extremely large.

My contribution looks like this (weighing in at 138 characters):

public static int[] Mookid8000_Add(int[] a,int[] b){
   var r="";
   for(int n=a.Length,m=b.Length,s,c=0;n+m+c>0;c=s/10)
      r=(s=(n>0?a[--n]:0)+(m>0?b[--m]:0)+c)%10+r;
   return r.Select(t=>t-48).ToArray();
}

Asger‘s and Lars‘ contribution looks like this (135 characters):

public static int[] AsgerHallasOgLarsUdengaard_Add(int[] a,int[] b){
   var r="";
   for(int c=0,x=a.Length,y=b.Length;x+y>0|c>9;)
      r=(c=(x>0?a[--x]:0)+(y>0?b[--y]:0)+c/10)%10+r;
   return r.Select(s=>s-48).ToArray();
}

And the winners’ (Mads and Peter Sandberg Brun) contribution looks like this (weighing in at an incredibly compact, but almost unreadable, 132 characters :) ):

public static int[] MadsOgPeterSandbergBrun_Add(int[] a,int[] b){  
   var c="";  
   for(int o=a.Length,p=b.Length,s=0;-o-p<(s=s/10+(0<o?a[--o]:0)+(0<p?b[--p]:0));)  
      c=s%10+c;  
   return c.Select(i=>i-48).ToArray();  
}

I usually don’t compete in competitions like this, because I’ve always thought of myself as pretty lame when it comes to solving coding puzzles, but this time it was great fun – especially since I was pretty motivated by my desire to beat Asger (my little sister’s boyfriend), who pushed me several iterations further than I would have gone on my own. He ended up beating me though, but I am still pretty satisfied with my fairly compact and almost readable solution.