Workaround for combining a factory method and Lifetime Manager with Unity

Today I encountered a pretty basic scenario that Unity can’t support out of the box: one NHibernate ISession per HttpContext.

The problem is that ISessions are provided by a factory method NHibernateHelper.OpenSession(), and I need to store them in a custom HttpContextLifetimeManager. Unity won’t let me use the two together because no RegisterFactory() overload allows you to specify a LifetimeManager.

Rupert Benbrook has posted a solution to this problem that overrides part of the Unity build-up pipeline (and even goes as far as emitting op codes directly). For simple applications, however, a plain extension method might suffice:

public static IStaticFactoryConfiguration RegisterFactory<T>(    this StaticFactoryExtension extension,     FactoryDelegate factoryMethod, LifetimeManager lifetimeManager){    FactoryDelegate wrappedFactoryMethod = delegate    {        LifetimeManager manager = lifetimeManager;        FactoryDelegate method = factoryMethod;        IUnityContainer container = extension.Container;        object o = manager.GetValue();        if (o == null)        {            o = factoryMethod(container);            manager.SetValue(o);        }        return o;    };    return extension.RegisterFactory<T>(wrappedFactoryMethod);}

This simply wraps the real factory method in a closure that checks a LifetimeFactory first. I can then do:

container.Configure<StaticFactoryExtension>()    .RegisterFactory<ISession>((c) => NHibernateHelper.OpenSession(),     new HttpContextLifetimeManager<ISession>());

This seems to work pretty well.

Free Typemock Isolator licenses

Free Typemock Isolator licenses

Typemock are giving away free licenses of their new ASP.NET Typemock bundle if you blog about it:

Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle – and for the launch will be giving out FREE licenses to bloggers and their readers.

The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

Go ahead, click the following link for more information on how to get your free license.

This bundle normally costs USD $599, and includes a full version of Typemock Isolator. Definitely a must have if you’re doing TDD with SharePoint.

The marvel of externally-hosted javascript and CSS

Before:

~/content/stylesheets/reset.css~/content/stylesheets/site.css~/content/scripts/jquery.min.js~/content/scripts/jquery-ui-1.7.1.custom.min.js~/content/stylesheets/smoothness/jquery-ui-1.7.1.custom.css~/content/scripts/site.js

After:

http://yui.yahooapis.com/2.7.0/build/reset/reset-min.css~/content/stylesheets/site.csshttp://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.jshttp://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.jshttp://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/smoothness/jquery-ui.css~/content/scripts/site.js

My app is now using Google and Yahoo’s content delivery networks (CDNs) to host most of its javascript and CSS files. This will improve client load times, and browsers can cache and share between all other sites that use them. Much better I think!

Links:

  • Serving YUI Files from Yahoo! Servers
  • Developer’s Guide – Google AJAX Libraries API

WPF: How to Combine Multiple Assemblies into a Single exe

At work, I am currently working on a small WPF app that we want to keep as a simple standalone exe. However, it has dependencies on several third-party assemblies: SharpZipLib, Unity, ServiceLocator, etc.

Microsoft has handy tool called ILMerge that merges multiple .NET assemblies into a single dll or exe. Unfortunately, it doesn’t support WPF applications, because of the way XAML is compiled.

Instead, you can use another approach — include all your referenced third-party assemblies as embedded resources of the exe:

 

public partial class App : Application
{
    private void OnStartup(object sender, StartupEventArgs e)
    {
        AppDomain.CurrentDomain.AssemblyResolve +=
            new ResolveEventHandler(ResolveAssembly);
        // proceed starting app...
    }
    static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
    {
        Assembly parentAssembly = Assembly.GetExecutingAssembly();
        var name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";
        var resourceName = parentAssembly.GetManifestResourceNames()
            .First(s => s.EndsWith(name));
        using (Stream stream = parentAssembly.GetManifestResourceStream(resourceName))
        {
            byte[] block = new byte[stream.Length];
            stream.Read(block, 0, block.Length);
            return Assembly.Load(block);
        }
    }
}

Whenever .NET can’t find a referenced assembly, it will call our code and we can provide an Assembly instance ourselves. Note this code expects a sane DLL-naming convention 🙂

TDD: Helper for checking PropertyChanged event gets raised

Today I am working on my first WPF app, using the WPF Model-View-ViewModel (MVVM) Toolkit. Naturally, we are using TDD — like ASP.NET MVC, WPF ViewModels and ICommands lend themselves very nicely to unit testing, even around difficult dependencies like OpenFileDialog.

Anyway, one problem I am seeing repeated is writing tests for PropertyChanged events firing at the correct time. This is required so that WPF views can display updated values when something changes. For a test helper, I wrote a quick disposable event listener and extension method for this:

[TestMethod]public void Should_raise_pack_path_property_changed_event(){    viewModel.AssertRaisesPropertyChangedFor("PackPath");    viewModel.OnFileSelected(@"C:foo.zip");}

An assertion will fail if the PropertyChanged event does not fire with the correct property name. Here is the extension method:

public static class INotifyPropertyChangedExtensions{    public static void AssertRaisesPropertyChangedFor(this INotifyPropertyChanged obj,        string propertyName)    {        new PropertyChangedEventListener(obj, propertyName);    }}

… and the event listener:

/// <summary>/// Helper class for asserting a PropertyChanged event gets raised for a particular/// property. If it hasn't been called by the time this object is disposed, an /// assertion will fail.</summary>public class PropertyChangedEventListener : IDisposable{    bool wasRaised = false;    readonly string expectedPropertyName;    bool IsDisposed = false;    readonly INotifyPropertyChanged obj;    public PropertyChangedEventListener(INotifyPropertyChanged obj, string propertyName)    {        if (obj == null)            throw new ArgumentNullException("obj");        if (propertyName == null)            throw new ArgumentNullException("propertyName");        this.obj = obj;        this.expectedPropertyName = propertyName;        obj.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);    }    void OnPropertyChanged(object sender, PropertyChangedEventArgs e)    {        if (this.expectedPropertyName.Equals(e.PropertyName))            this.wasRaised = true;    }    public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    protected void Dispose(bool Disposing)    {        if (!IsDisposed)        {            if (Disposing)            {                // Cleanup references...                this.obj.PropertyChanged -= new PropertyChangedEventHandler(OnPropertyChanged);                // Assert we got called                Assert.IsTrue(this.wasRaised,                    String.Format("PropertyChanged was not raised for property '{0}'",                        this.expectedPropertyName));            }        }        IsDisposed = true;    }    ~PropertyChangedEventListener()    {        Dispose(false);    }}

It’s not fancy, and it’s probably not thread-safe, but it does the trick for our app.

TDD: How to Supersede a Single System Library Call

This morning I read an article this morning by Karl Seguin on allowing clients to replace system calls with delegates (function pointers) for testing purposes — making the untestable testable.

It is a pattern I have used myself recently, but under a different name with a more formalized syntax. Imagine, for example, you have created an interface to decouple e-mail sending dependencies:

1
2
3
4
public interface IMailSender
{
    void Send(MailMessage message);
}

This allows me to swap out my IMailSender (via Dependency Injection) with a fake implementation for testing purposes – e.g. FakeMailSender or a mock.

Otherwise, production code uses SmtpMailSender, a concrete class I wrote that implements IMailSender via a call to System.Net.Mail.SmtpClient.Send():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SmtpMailSender : IMailSender
{
    // The MailSent event is raised every time an email is sent.
    public event EventHandler<MailSentEventArgs> MailSent;
    public void Send(MailMessage message)
    {
        if (message == null)
            throw new ArgumentNullException("message");
        // Send the message using System.Net.Mail.SmtpClient()
        new SmtpClient().Send(message);
        // Notify observers that we just sent a msg.
        MailSent(new MailSentEventArgs(message));
    }
}

Note this class is a little bit special — it also has an event MailSent that gets raised every time a message is sent. This lets me attach stuff like global e-mail logging very easily, but how can we write a unit test that asserts this event gets raised at the correct time? Because of the dependency on SmtpClient.Send(), my SmtpMailClient class is now facing the exact same problem IEmailSender was designed to solve. For this issue you can check out this article as well.

Injecting an Action in the constructor

System.Net.Mail.SmtpClient.Send() isn’t virtual, so we can’t mock it, and I don’t really want another interface just for this situation. One solution Karl suggests is injecting an Action that does the actual sending:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class SmtpMailSender : IMailSender
{
    // The MailSent event is raised every time an email is sent.
    public event EventHandler<MailSentEventArgs> MailSent;
    // method that actually sends the message.
    readonly Action<MailMessage> send;
    public SmtpMailSender(Action<MailMessage> send)
    {
        this.send = send;
    }
    public void Send(MailMessage message)
    {
        if (message == null)
            throw new ArgumentNullException("message");
        // Send the message using System.Net.Mail.SmtpClient()
        send(message);
        // Notify observers that we just sent a msg.
        MailSent(new MailSentEventArgs(message));
    }
}

This solves the dependency problem effectively and without creating new classes and interfaces. However, now users of the SmtpMailSender class are forced to provide the send action in the constructor.

1
2
var sender = new SmtpMailSender(new SmtpClient().Send);
sender.Send(...);

If you have a good IoC container it can take care of this, but other users may not be so lucky. There are a few other things that I didn’t like as well:

  • 99% of this class’s functionality lies in this single action. A class where 99% of it’s functionality is injected in a single parameter raises the question why it really needs to exist at all.
  • The default implementation, SmtpClient.Send(), only needs to be overriden in a few test cases. Everyone else shouldn’t have to care about it.
  • Putting random delegates in a constructor makes me feel uncomfortable. Unless it is an intention-revealing named delegate, I don’t think this is a good pattern to be promoting.

Using Supersede Instance Variable instead

In Working Effectively with Legacy Code, Michael Feathers discusses a pattern called Supercede Instance Variable. Although it is used for technical reasons (replacing global dependencies in non-virtual C++ classes, where methods cannot be overridden via subclassing), I believe the pattern fits this usage example well.

Really, the only difference is that, here, is that unless a user performs the optional step of overriding the action via a special SupersedeSendActionmethod, a default is used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class SmtpMailSender : IMailSender
{
    public event EventHandler<MailSentEventArgs> MailSent;
    Action<MailMessage> send;
    public Action<MailMessage> DefaultSend
    {
        get return new SmtpClient().Send; }
    }
    public SmtpMailSender()
    {
        this.send = DefaultSend;
    }
    public void Send(MailMessage message)
    {
        if (message == nullthrow new ArgumentNullException("message");
        this.send(message);
        MailSent(new MailSentEventArgs(message));
    }
    /// <summary>
    /// Supersede the method that is used to send a MailMessage for testing
    /// purposes (supersede static variable to break dependency on non-
    /// mockable SmtpClient.Send() method).
    /// </summary>
    public void SupersedeSendAction(Action<MailMessage> newSend)
    {
        this.send = newSend;
    }
}

It is only a small difference, but as Feathers states, using the supersede term indicates it is a rare deviation from default behaviour, and for special cases only:

One nice thing about using the word supersede as the method prefix is that it is kind of fancy and uncommon. If you ever get concerned about whether people are using the superceding methods in production code, you can do a quick search to make sure they aren’t.

Only supersede when you can’t inject

Remember though, that Supersede Instance Variable should only be used for very special cases like individual system library calls in low-level wrapper classes. Dependency Injection and intention-revealing interfaces is still a much better pattern, and should still be your primary tool in all other situations.

Mocking out AutoMapper with Dependency Injection

Mocking out AutoMapper with Dependency Injection

I’m a big fan of AutoMapper, an open-source object/object mapper for .NET. One thing I’ve noticed, however, is that all the examples I’ve seen all talk to the static Mapper class. This becomes a real pain when you need to test something that uses AutoMapper, because you can’t swap it out for testing purposes:

public class ReadingListService : IReadingListService{    IValidator<ReadingListForm> validator; // injected    ReadingListRepository repository; // injected    ...    public ReadingList SaveReadingList(ReadingListForm form)    {        this.validator.ValidateAndThrow(form);        // ugly global dependency :(        ReadingList readingList = Mapper.Map<ReadingListForm, ReadingList>(form);                this.repository.Save(readingList);        return readingList;    }

I don’t want to have to set up the Mapper when I’m testing ReadingListService’s interaction with the repository, validator, etc — especially because this particular mapping scenario uses custom resolvers which in have services injected into them as well (yawn).

Instead, I can break this dependency by replacing the Mapper reference with an instance of IMapperEngine, which has methods with the same signature as Mapper.Map:

public class ReadingListService : IReadingListService{    IValidator<ReadingListForm> validator; // injected    ReadingListRepository repository; // injected    IMappingEngine mapper; // injected!    ...    public ReadingList SaveReadingList(ReadingListForm form)    {        this.validator.ValidateAndThrow(form);        // now mockable just like validator and repository :)        ReadingList readingList = this.mapper.Map<ReadingListForm, ReadingList>(form);                this.repository.Save(readingList);        return readingList;    }

I can now mock out AutoMapper, and use it A) to test that AutoMapper gets called in the appropriate scenarios B) to streamline other tests by just returning a known value etc.

The Mapper class holds a singleton to IMapperEngine in its Engine property, so you can register this with your IoC container etc.

Wanted: A kickass .NET API for CouchDB

Wanted: A kickass .NET API for CouchDB

CouchDB logo

Over the past couple of weeks I’ve been playing with Apache CouchDB. If you haven’t seen it yet, you should check it out — it’s a document database that stores data as a flat collection of JSON objects (aka documents) with no schema, no normalization, no indexes, and no JOINs.

Communication is via RESTful HTTP commands — for example:

GET http://127.0.0.1:5984/books/42

…for retrieving a document ID ’42′ from a database named ‘books’. This would return the following JSON document:

{  "_id":"some_doc_id",  "_rev":"946B7D1C",  "Title":"Harry Potter",  "Author":{    "Initials":"JK",    "Surname":"Rowling"  },  "Pages":"436",  "Tags":["wizards", "children", "magic"]}

It sounds pretty crazy if you’re used to big relational databases, but it’s an important shift that is becoming more and more popular with the likes of Google BigTable and Amazon SimpleDB. The fact is, if you’re not writing a transactional application where normalization is a priority, do you really need all the complexity of a relational database? Many common web applications like blogs and CMSs and Twitter could work quite happily with databases like CouchDB. Check out these two great articles that explain it further:

  • Assaf Arkin: CouchDB: Thinking beyond the RDBMS
  • Infoworld: Slacker databases break all the old rules

Anyway, CouchDB is still quite young, and hasn’t seen a lot of attention outside the Ruby and Python communities. This sucks. I would like to see a well-designed open-source library for .NET applications using CouchDB for persistence. Here are some features such a library might provide over and above raw HTTP WebRequests:

Requirement #1: Generics and automatic serialization/deserialization of .NET objects

At time of writing, I can only find one CouchDB available for .NET. It’s called SharpCouch, and only works at the string level:

string json = db.GetDocument("127.0.0.1", "books", "42");

Instead, it shouldn’t be too hard to use something like JSON.NET and generics to automatically map between JSON strings and live .NET objects:

Book book = db.GetDocument<Book>("127.0.0.1", "books", "42");

Requirement #2: mapping RESTful HTTP error codes to .NET exceptions

Being a REST app, CouchDB uses HTTP status codes to indicate different states of success or failure, e.g. 404 when a document doesn’t exist. Such errors should be mapped from raw WebExceptions into nicer types like DocumentNotFoundException and DocumentConflictException.

Requirement #3: Implicit Offline Optmistic Lock via document revisions

Offline Optimistic Lock is a pattern used to prevent concurrency problems when two people edit the same piece of data at the same time. Basically, instead of locking an object while one person uses it, you allow multiple users access at the same time, but each user checks to see if it has changed before they modify it.

Optimistic Offline Lock is usually implemented via versioning. As well as an ID, each object has a version number that gets automatically incremented each time the object is modified. Before a client saves changes to the object, it checks to see if the version number has changed since it retrieved it. If it has, then you know someone else has modified the object in the mean time, and your copy is now stale.

While this is optional in most relational databases (for example, if you use a rowversion column in SQL Server), document versioning is a non-negotiable feature of CouchDB: to update a document, you have to know its ID and it’s revision number.

The easiest way of keeping track of this would simply be to add a _rev property to all your domain entities:

public class Book{    public string Title { get; set; }    public string Author { get; set; }    public string Publisher { get; set; }    public string _rev { get; set; } // hmm}

Actually though, I’d prefer not to worry about revision numbers at all. They are only required by CouchDB, and I don’t want to let such concerns leak into my domain model. Instead, document revision numbers should be stored in a separate Identity Map — a list of references to all hydrated database objects currently active in my application.

Requirement #4: LINQ expressions for Map/Reduce functions

CouchDB uses map/reduce functions expressed in javascript to define its views. For example:

map: function(book) {    emit(doc.NumberOfPages, doc);  }}reduce: function(keys, values) {   return sum(values);}

This seems like a pretty good fit for LINQ expressions, no? Perhaps something like:

public BooksByNumberOfPages : IMapReduce<Book, int>{    public IEnumerable<int> Map(IEnumerable<Book> books)    {        return books.select(b => b.NumberOfPages);    }    public int Reduce(IEnumerable<int> keys, IEnumerable<Books> values)    {         return keys.Sum();    }}

This is not strictly required, and indeed probably wouldn’t get used that much because CouchDB views are very static, but could be a nice bit of syntactic sugar.

Requirement #5: ID generators like NHibernate

CouchDB encourages you to provide your own IDs for documents — otherwise it will give you big fat ugly GUIDs. I would like to see ID generators similar to NHibernate’s hi/lo algorithm, which produces human-readable and approximately-sequential IDs.

Final words

From these ideas, clearly revision tracking with an identity map is the most important — in fact this was the reason I decided not to use CouchDB for a recent project to which it was well suited (because I didn’t have time to write a persistence framework for it first). Long term, however, CouchDB has a lot to offer the .NET community, and combined with officially-maintained ports for Windows, a well-supported CouchDB .NET library could bring benefit to many projects.

Spotted in the wild…

Spotted in the wild…

CREATE     FUNCTION [dbo].[fnGetInitialDate] (       @Month               int = null,        @Year         int = null,       @CurrentDate datetime)  RETURNS intAS  BEGIN       Declare @ReportDate datetime       Declare @InitialMonth      int           if @month IS null              set @month = Month(Dateadd(m, -1, @CurrentDate))       if @Year IS null              set @Year = Year(Dateadd(m, -1, @CurrentDate))-- NORMALISE Date/*       Select               @Date = StartDateTime,              @DateDiff = AgeInMonths       from              (                     select top 1                           StartDateTime,                           AgeInMonths                     from                           dbo.<censored>                     where                            StartDateTime is not null              ) TA*/       set @ReportDate      = Cast(@Year AS VARCHAR(4)) + '-' +  Right('00' + Cast(@month AS VARCHAR(2)),2) + '-01'       set @InitialMonth = datediff(m, @CurrentDate, @ReportDate)       return @InitialMonthEND

This SQL Server function features:

  • A name that doesn’t tell you anything ✔
  • Comments indicating non-existent functionality ✔
  • Big sections commented out with no explanation ✔
  • Using strings for date arithmetic ✔

After much thought I concluded that this code is functionally equivalent to DATEDIFF(MONTH, GETDATE(), @ReportDate), except you can choose a different year or month for the current time.

This function is still at large on a production database server (names have been suppressed to protect the innocent). Developers are recommended not to approach it as it is considered dangerous, and extremely confusing.