This book is exactly what its title says: a quick introduction to ASP.NET MVC. A natural implication is that it cannot cover that much material, and it seems Maarten went for breadth instead of depth.

In my opinion, when a book chooses to be a “quick guide”, it should focus more on showing the preferred ways to do stuff. Instead, this book seems to have too much ViewData["stuff"] = fluff going on. Why bother wasting pages showing all the tedious, error-prone, hard-to-maintain ways to do stuff when there is so little space?

asp.net.mvc.quickly.quickly

If I were to author a book on ASP.NET MVC, I would focus on explaining ASP.NET MVC from the extensibility points and out. For example, System.Web.Mvc.Controller is just one way to implement the IController interface, and so on. I think that would provide a much more wholistic image of the framework, and the extensibility points is where ASP.NET MVC shines. I don’t think Maarten’s book really shows where the framework shines.

I enjoyed the chapter on using existing ASP.NET features though, and, not being an ASP.NET guy at all, I think I learned some stuff there.

My conclusion is that this book is absolutely for beginners, and that the code samples in the book should not be taken literally, because almost none of them are examples on what the community considers best practice.

Title: ASP.NET MVC 1.0 Quickly
Author: Maarten Balliauw
ISBN 10/13: 184719754X / 978-1847197542
Publisher: Packt Publishing

Another simple place to hook your stuff into the framework is action filters. An action filter is an attribute that derives from ActionFilterAttribute which is a convenience class containing the following methods for you to override:

void OnActionExecuting(ActionExecutingContext context);
void OnActionExecuted(ActionExecutedContext context);
void OnResultExecuting(ResultExecutingContext context);
void OnResultExecuted(ResultExecutedContext context);

A lot of the examples around the internet show how to use action filters to restrict access to controller actions or how to apply caching. I won’t do that here, because those concerns are boring. No, we care about how to make life easy for ourselves and how to write testable, non-breakable, maintenance-and-wrist-friendly code. That is, we reserve the right to be lazy.

A fine example on how to be lazy is by letting action filters fetch data for you to avoid repetitive repository gymnastics in every controller action – and I am actually going to be very lazy right now, because I wrote two posts on this topic earlier:

  1. How to avoid duplicate data fecthing with ASP.NET MVC
  2. Another way to avoid duplicate data fetching with ASP.NET MVC

My favorite hook in the ASP.NET MVC framework is the controller factory. I like it so much because it serves as a very simple entry point to the application, thus providing the perfect place to insert an IoC container. My container of choice is Castle Windsor – not because I have tried any other container – I really can’t say that I have – but because I just happened to be introduced by a colleague to Windsor, and I have yet to experience anything it can’t do for me!

An ASP.NET MVC controller factory is an implementation of the IControllerFactory interface – a simple interface with two methods: one that provides an IController given a string and some more stuff, and one that allows the controller to clean up any resources it might have allocated. The interface looks like this:

public interface IControllerFactory
{
    IController CreateController(RequestContext requestContext, string controllerName);
    void ReleaseController(IController controller);
}

As you can see, it provides a means to return a controller, given all sorts of information about the current request and what could be resolved as the controllerName from the request URL.

ASP.NET MVC accesses the controller factory via the ControllerBuilder class – so if we want to provide our own controller factory, we must install the factory before any requests get served. An obvious place to do this, is the Application_Start method inside the global.asax.cs file. This way our controller factory will be installed every time the web application starts up.

The controller factory can be set in two ways: 1) By providing the type of the factory, and 2) By providing an instance of the factory. Then it’s up to you if you want to let ASP.NET MVC instantiate the factory. I usually do it like this:

public void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
 
    ControllerBuilder.SetControllerFactory(typeof(MyControllerFactory));
}

- and let ASP.NET MVC instantiate and store a singleton instance of my factory.

My controller factory implementation looks like this:

public class MyControllerFactory : IControllerFactory
{
    IWindsorContainer container = CreateWindsorContainer();
 
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        return container.Resolve<IController>(controllerName.ToLowerInvariant());
    }
 
    public void ReleaseController(IController controller)
    {
        container.Release(controller);
    }
 
    static IWindsorContainer CreateWindsorContainer()
    {
        return new WindsorContainer("windsor.config");
    }
}

Very simple. It takes the string, that was resolved as the controller name – e.g. “home”, “hOme”, “HOME” or whatever – and converts it to lower case, and then it uses that to look up a controller in my container. This means that all my controllers are registered in the container, and they will have all their dependencies automatically resolved when the container creates each instance.

A controller registration might look like this:

<castle>
    <components>
        <component id="home" type="WebSite.Controllers.HomeController, WebSite" />
 
        <!-- more registrations here... -->
 
    </components>
</castle>

Simple – yet incredibly effective!

Just wanted to share my experiences regarding the super cool mini framework, Topshelf – a bi-product from the development of MassTransit. When Dru and the other guys were working on MassTransit, they needed to create Windows services a lot, which led to the separation of the Windows service stuff from the other stuff – and now they call it Topshelf.

You use Topshelf by creating a console application. In the Main method, you create a configuration, which you hand over to Topshelf. Then, everything just works as expected.

Topshelf requires that you to use an IoC container hidden behind the common service locator interface, which is neat because then it’s up to you to decide which container to use. In this example, I am using Windsor.

Creating a service is as simple as this:

namespace SomeService
{
  public class Program
  {
    [STAThread]
    public static void Main(string[] args)
    {
      const string serviceName = "some_service";
 
      var cfg = RunnerConfigurator.New(
        x =>
        {
          x.BeforeStart(
            s =>
              {
                Console.WriteLine("Starting {0}...", serviceName);
                ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(CreateWindsorContainer()));
              });
 
          x.AfterStop(
            s =>
              {
                Console.WriteLine("Stopping {0}...", serviceName);
                ((WindsorServiceLocator) ServiceLocator.Current).Dispose();
              });
 
          x.ConfigureService<SomeService>(
            c =>
            {
              c.WithName(serviceName);
 
              c.WhenStarted(s => s.Start());
              c.WhenStopped(s => s.Stop());
              c.WhenPaused(s => { });
              c.WhenContinued(s => { });
            });
 
          x.SetDisplayName("My funky service");
          x.SetDescription("This is a funky service that depends on MSMQ");
          x.SetServiceName(serviceName);
 
          x.DependencyOnMsmq();
        });
 
      Runner.Host(cfg, args);
    }
}

Everything in the snippet above works as expected. Note how I create my Windsor container and store it behind WindsorServiceLocator, which is my trivial implementation of the IServiceLocator interface. This way, Topshelf will pull the specified service type(s) (SomeService in the sample) from the container, and call the specified methods to start/stop (and possibly pause/resume) the service.

Note also how I specify that my service has a dependency on message queueing – neat!

Running and debugging the service is as easy as executing the .exe.

Installing/uninstalling can be done with

SomeService.exe /install
SomeService.exe /uninstall

Nifty!

When two things are orthogonal, it means that the angle between them is 90 degrees – at least in spaces with 3 dimensions or less. So when two vectors are orthogonal, they satisfy the property that there is no way to use the first one to express even the tiniest bit of what the other one expresses.

That is also how we should write our application code: methods and classes should be orthogonal to one another – i.e. no class should try to express what another class already expresses either in part or whole – therefore each class and each method should have only one responsibility, and thus one reason to change.

And test code is real code.

The corollary is that our tests should have only one single reponsibility as well.

That is why I hate tests that look like this:

public void CanRecordPayment()
{
    CreateMortgageDeed(1, new DateTime(2003, 3, 11));
    CreateMortgageDeed(2, new DateTime(2003, 6, 11));
    CreateMortgageDeed(3, new DateTime(2003, 3, 11));
    CreateMortgageDeed(4, new DateTime(2003, 3, 11));
    CreateMortgageDeed(5, new DateTime(2003, 9, 11));
 
    var mortgageDeeds = new DueTermsFinder(new MortgageDeedRepository())
        .FindDueTermsBefore(new DateTime(2003, 4, 1));
 
    Assert.AreEqual(3, mortgageDeeds.Count);
 
    mortgageDeeds = mortgageDeeds.OrderBy(m => m.CaseNo);
 
    Assert.AreEqual(1, mortgageDeeds[0].CaseNo);
    Assert.AreEqual(3, mortgageDeeds[1].CaseNo);
    Assert.AreEqual(4, mortgageDeeds[2].CaseNo);
 
    var result = new TermDebitRecorder()
        .CreateAndRecordTermDebits(mortgageDeeds);
 
    Assert.AreEqual(3, result.RecordedTermDebits.Count);
 
    Assert.AreEqual(new DateTime(2003, 3, 11), result.RecordedTermDebits[0].TermDate);
    Assert.AreEqual(new DateTime(2003, 3, 11), result.RecordedTermDebits[1].TermDate);
    Assert.AreEqual(new DateTime(2003, 3, 11), result.RecordedTermDebits[2].TermDate);
    // .... etc!
}

Notice how this test is actually fairly decently structured – at least that’s what it initiallt looks like… but it actually tests a lot of things: it checks that the output of the DueTermsFinder is what it expects, testing the MortgageDeedRepository indirectly as well – and then it goes on to test the TermDebitRecorder … sigh!

If (when!) one of these classes changes at some point, because the requirements have changed or whatever, the test will break for no good reason. The test should break because you have introduced a bug, not because you made a change in some related functionality.

That is why I usually follow the pattern of AAA: Arrange, Act, Assert. Each test should be divided into discrete steps corresponding to 1) Arranging some data, 2) Triggering a computation or some state change, 3) Asserting that the outcome was what we expected. And if I am feeling idealistic that day, I also follow the principle of putting only one assertion at the end of each test.

I try to never do AAAAA (Arrance, Act, Assert, Act Assert) or AAAAAA, or AAAAAAA which is even worse.

Every test should have only one reason to break.

When writing code, I often end up introducing a layer supertype – i.e. a base class with functionality shared by all implementations in that particular layer in my application.

This also holds for my test code – and why shouldn’t it? Test code is as real as real code, so the same rules apply and it should benefit from the same pain killers as we implement in our application code.

For example when testing repositories and services that need to query the database, I can save myself a lot of writing by stuffing all the boring NHibernate push-ups in a DbTestFixture supertype – this includes building a configuration that connects to a test database, building a session factory, storing that session factory somewhere, re-creating the entire database schema in the test fixture setup, and running each test in a transaction that is automatically rolled back at the end of each test + a few convenience methods that allow me to flush the current session etc.

The DbTestFixture might look something like this (note that all my repositories take an instance of ISessionProvider in their ctor – that’s how they obtain the currently ongoing session, which is why I have a TestSessionProvider to inject into repositories under test):

public class DbTestFixture
{
	TestSessionProvider currentSessionProvider;
	ISession currentSession;
	ITransaction currentTransaction;
	bool commit;
 
	[TestFixtureSetUp]
	public void TestFixtureSetUp()
	{
		SessionFactoryHolder.Instance.CreateSchema();
 
		using (currentSession = OpenSession())
		{
			DoTestFixtureSetUp();
			currentSession.Flush();
		}
	}
 
	[SetUp]
	public void SetUp()
	{
		currentSession = OpenSession();
		currentTransaction = currentSession.BeginTransaction();
		currentSessionProvider = new TestSessionProvider(currentSession);
 
		DoSetUp();
 
		currentSession.Flush();
	}
 
	[TearDown]
	public void TearDown()
	{
		DoTearDown();
 
		if (commit)
		{
			currentTransaction.Commit();
		}
		else
		{
			currentTransaction.Rollback();
		}
 
		currentTransaction.Dispose();
		currentSession.Dispose();
	}
 
	protected ISession OpenSession()
	{
		return SessionFactoryHolder.Instance.SessionFactory.OpenSession();
	}
 
	protected ISessionProvider SessionProvider
	{
		get { return currentSessionProvider; }
	}
 
	protected virtual void DoTestFixtureSetUp() { }
	protected virtual void DoSetUp() { }
	protected virtual void DoTearDown() { }
 
	protected ISession CurrentSession
	{
		get { return currentSession; }
	}
 
	protected T Reload<T>(T t) where T : Base
	{
		SaveAndFlushAndClear(t);
		return CurrentSession.Get<T>(t.Id);
	}
 
	protected void SaveAndFlushAndClear(object obj)
	{
		CurrentSession.Save(obj);
		CurrentSession.Flush();
		CurrentSession.Clear();
	}
 
	protected void SaveAndFlush(object obj)
	{
		CurrentSession.Save(obj);
		CurrentSession.Flush();
	}
 
	protected void Save(object obj)
	{
		CurrentSession.Save(obj);
	}
 
	protected void Flush()
	{
		CurrentSession.Flush();
	}
 
	protected void DoNotRollBack()
	{
		commit = true;
	}
 
	protected class TestSessionProvider : ISessionProvider
	{
		readonly ISession currentSession;
 
		public TestSessionProvider(ISession currentSession)
		{
			this.currentSession = currentSession;
		}
 
		public ISession GetCurrentSession()
		{
			return currentSession;
		}
 
		public void Commit()
		{
			throw new System.NotImplementedException();
		}
 
		public void RollBack()
		{
			throw new System.NotImplementedException();
		}
	}
}

Then a fictional repository test might look as simple as this:

[TestFixture]
public class TestMessageRepository : DbTestFixture
{
	MessageRepository repo;
	Guid messageId;
 
	protected override void DoTestFixtureSetUp()
	{
		var message = new Message
		              	{
		              		CreatedAt = new DateTime(2003, 11, 11),
		              		Subject = "some subject",
		              		Body = "some body",
		              	};
 
		CurrentSession.Save(message);
 
		messageId = message.Id;
	}
 
	protected override void DoSetUp()
	{
		repo = new MessageRepository(SessionProvider);
	}
 
	[Test]
	public void CanLoadSingleMessage()
	{
		var message = repo.Find(messageId);
 
		Assert.AreEqual(new DateTime(2003, 11, 11), message.CreatedAt);
		Assert.AreEqual("some subject", message.Subject);
		Assert.AreEqual("some body", message.Body);
	}
}

Note how DbTestFixture flushes in all the right places so I don’t need to worry about that.

This test fixture supertype can be used for all my database access tests, as well as integration testing. But what about unit tests? I am using Rhino Mocks, so my unit test fixture base looks like this:

public class UnitTestFixture
{
	protected readonly MockRepository mocks = new MockRepository();
 
	protected T Stub<T>(params object[] paramsForConstructor) where T : class
	{
		return mocks.Stub<T>(paramsForConstructor);
	}
 
	protected T Mock<T>(params object[] paramsForConstructor) where T : class
	{
		return mocks.DynamicMock<T>(paramsForConstructor);
	}
}

Real simple – it just stores my MockRepository and gives me a few shortcuts to the mocks I care for. Then I inherit this further to ease testing e.g. my ASP.NET MVC controllers like this:

public abstract class ControllerTestFixture<T> : UnitTestFixture where T : Controller
{
	protected T controller;
 
	[SetUp]
	public void SetUp()
	{
		controller = CreateController();
	}
 
	protected abstract T CreateController();
}

As you can see, I make it a real “fixture” – the controllers I am about to test will fit into this fixture like a glove, and I will certainly never forget to instantiate my controller only once, because I start out by implemeting that part in the implementation of the CreateController method.

A controller test might look like this:

 
[TestFixture]
public class TestAuthenticationController : ControllerTestFixture<AuthenticationController>
{
	ISessionContext sessionContext;
	IAuthenticationService authenticationService;
 
	protected override AuthenticationController CreateController()
	{
		sessionContext = mocks.DynamicMock<ISessionContext>();
		authenticationService = mocks.DynamicMock<IAuthenticationService>();
 
		return new AuthenticationController(sessionContext, authenticationService);
	}
 
	// tests down here...
}

One thing, that I find really annoying, is that somehow it seems to be accepted that test code creates instances of this and that like crazy! In a system I am currently maintaining with about 1MLOC where ~40% is test code, I often come across test fixtures with something like 20 individual tests, and each and every one of them creates instances of maybe 5 different entities, builds an object graph, runs some code to be tested, and does some assertions on the result.

This is a super example on how to write brittle and rigid tests, because what happens if the signature of one of the ctors changes? Or the semantics of the object graph? Or [insert way too many ways for the test to break for the wrong reasons here...].

When I come across these tests, I usually factor out the creation of all but the most simple objects behind methods with meaningful names. This has two advantages: 1) It’s more DRY because they can be re-used, and 2) It serves as brilliant documentation. Consider this rather simple assertion that requires a few objects to be in place:

[Test]
public void MortgageDeedKnowsItsActualPrincipalBeforeAmortizationHasBegun()
{
    var deed = new MortgageDeed();
 
    deed.Principal = 100000;
    deed.Amortization.FirstTerm = new DateTime(2003, 3, 11);
 
    deed.Amortization.AddAmortizationStrategyElement(new AnnuityAmortizationStrategyElement
    {
        FirstTerm = 1,
        TermsPerYear = 4,
        PeriodicPayment = 5000,
    });
 
    deed.Amortization.AddInterestStrategyElement(new FixedRateInterestStrategyElement
    {
        FirstTerm = 1,
        Rate = 0.05,
    });
 
    Assert.AreEqual(new DateTime(2003, 3, 11), deed.ActualPrincipalDate);
}

compared to this:

[Test]
public void MortgageDeedKnowsItsActualPrincipalDateBeforeAmortizationHasBegun()
{
    var deed = NewStandardMortgageDeedBeforeAmortization(new DateTime(2003, 3, 11), 100000, 5000);
 
    Assert.AreEqual(new DateTime(2003, 3, 11), deed.ActualPrincipalDate);
}
 
MortgageDeed NewStandardMortgageDeedBeforeAmortization(DateTime firstTerm, decimal principal, decimal periodicPayment)
{
    //...
}

MUCH more clear! The factory method acts as brilliant documentation on which aspects of the test are relevant to the outcome – it is clear, that a mortgage deed which has not yet begun its amortization must report its first term date as the actual principal date.

Go on to test another property of the mortgage deed before amortization:

[Test]
public void MortgageDeedKnowsItsActualPrincipalBeforeAmortizationHasBegun()
{
    var deed = NewStandardMortgageDeedBeforeAmortization(new DateTime(2003, 3, 11), 100000);
 
    Assert.AreEqual(100000, deed.ActualPrincipal);
}

- and we have already saved us from writing 50 lines of brittle rigid test code. Keep factoring out common stuff, so that the ctor of the mortage deed is still only called in one place… e.g. create methods like this:

MortgageDeed NewStandardMortgageDeedWithTransactions(
    DateTime firstTerm, 
    decimal principal, 
    decimal periodicPayment, 
    params Transaction [] transactions)
{
    var deed = NewStandardMortgageDeedBeforeAmortization(firstTerm, principal, periodicPayment);
    Array.ForEach(transactions, t => deed.AddTransaction(t));
}
 
Transaction NewPayment(DateTime paymentDate, decimal amount)
{
    var payment new PaymentTransaction
    {
        Amount = amount,
        PaymentDate = paymentDate,
        ValueDate = paymentDate,
    };
 
    payment.Record();
 
    return payment;
}
 
Transaction NewTermDebit(DateTime termDate, decimal interest, decimal installment)
{
    var termDebit = new TermDebitTransaction
    {
        Interest = interest,
        Installment = installment,
        TermDate = termDate,
    }
 
    termDebit.Record();
 
    return termDebit;
}

which allows me to write cute easy-to-understand tests like this:

[Test]
public void ActualPrincipalDateIsChangedWhenPaymentIsMade()
{
    var deed = NewStandardMortgageDeedWithTransactions(
        new DateTime(2003, 3, 11), 
        100000,
        NewPayment(new DateTime(2003, 6, 11), 5000));
 
    Assert.AreEqual(new DateTime(2003, 6, 11), deed.ActualPrincipalDate);
    Assert.AreEqual(new DateTime(2003, 3, 11), deed.AmortizedPrincipalDate);
}
 
[Test]
public void AmortizedPrincipalDateIsChangedWhenTermDebitIsMade()
{
    var deed = NewStandardMortgageDeedWithTransactions(
        new DateTime(2003, 3, 11), 
        100000,
        NewTermDebit(new DateTime(2003, 6, 11), 4000, 1000));
 
    Assert.AreEqual(new DateTime(2003, 3, 11), deed.ActualPrincipalDate);
    Assert.AreEqual(new DateTime(2003, 6, 11), deed.AmortizedPrincipalDate);
}

This is also a good example on how to avoid writing // bla bla comments all over the place – it’s just not necessary when the methods have sufficiently well-describing names.

In the previous post I showed how easy it is to install an IoC container at the system boundary of your ASP.NET MVC application and have it resolve everything from there.

But what I did not show, was where the container came from – in the example, the container just pops out of nowhere on this line:

static IContainer myContainer = GetContainerInstanceFromSomewhere();

So how can we implement GetContainerInstanceFromSomewhere()?

Well, I like to do it like this:

IWindsorContainer GetContainerInstanceFromSomewhere()
{
    return new WindsorContainer("windsor.config");
}

Isn’t that easy? And then I have a folder structure in my ASP.NET MVC project that looks like this:

config-folder

It can be seen that I have a folder for each configuration of the system (development, test, prod) and one containing configuration files that are common for all configurations. For each configuration I have a hibernate.cfg.xml to configure NHibernate and a windsor.config which is loaded by the Windsor container in each particular configuration.

My development/windsor.config looks like this:

<castle>
  <include uri="file://controllers.config"/>
 
  <include uri="file://facilities.config"/>
 
  <include uri="file://factories.config"/>
 
  <include uri="file://repositories.config"/>
 
  <include uri="file://services.config"/>
 
  <!-- For this configuration only -->
  <components>
    <component id="services.ApplicationSettings"
               service="Model.Services.IApplicationSettings, Model.Services"
               type="WebSite.Stuff.DevelopmentMachineApplicationSettings, WebSite">
      <parameters>
        <DefaultEmailSender>noreply@website.com</DefaultEmailSender>
        <UrlBase>http://localhost:1766</UrlBase>
      </parameters>
    </component>
 
    <component id="services.EmailSender"
               service="Model.Services.IEmailSender, Model.Services"
               type="WebSite.Stuff.FakeLoggingEmailSender, WebSite" />
 
  </components>
</castle>

It can be seen that my development configuration is used to Cassini running on port 1766 :) moreover, it can be seen that my development configuration is using a fake, logging email sender, which – much as you would expect – only logs the content from emails that would otherwise have been sent.

Of course, the configuration files will not automatically be available to the web application the way they are organized now – therefore, my web project has a post-build task with the following two lines:

xcopy "$(ProjectDir)Config\common\*.*" "$(TargetDir).." /y
xcopy "$(ProjectDir)Config\development\*.*" "$(TargetDir).." /y

- thus copying the common configuration files along with the development configuration files to the base directory of the web application.

This also means that my build script must overwrite the development configuration files when building the system in a deployment configuration. It can be achieved as simple as this (using MSBuild):

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ApplicationFiles Include="ProjectName\WebSite\Default.aspx" />
    <ApplicationFiles Include="ProjectName\WebSite\Global.asax" />
    <ApplicationFiles Include="ProjectName\WebSite\Global.asax.cs" />
    <ApplicationFiles Include="ProjectName\WebSite\web.config" />
 
    <ApplicationFiles Include="ProjectName\WebSite\bin\*.*" />
  </ItemGroup>
 
  <PropertyGroup>
    <DestinationFolder>C:\Release\ProjectName</DestinationFolder>
    <ConfigurationFolder>ProjectName\WebSite\Config</ConfigurationFolder>
  </PropertyGroup>
 
  <Target Name="build">
    <MSBuild Projects="ProjectName\WebSite.sln" Targets="build" StopOnFirstFailure="true" Properties="Configuration=Release;">
      <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuiltByChildProjects" />
    </MSBuild>
  </Target>
 
  <Target Name="deploy">
    <RemoveDir Directories="$(DestinationFolder)\Views;$(DestinationFolder)\Content;$(DestinationFolder)\bin;$(DestinationFolder)" />
    <MakeDir Directories="$(DestinationFolder);$(DestinationFolder)\bin;$(DestinationFolder)\Views;$(DestinationFolder)\Content" />
 
    <Copy SourceFiles="@(ApplicationFiles)" DestinationFolder="$(DestinationFolder)"/>
    <Exec Command="xcopy /d/e/f/y ProjectName\WebSite\Views\*.* $(DestinationFolder)\Views" />
    <Exec Command="xcopy /d/e/f/y ProjectName\WebSite\Content\*.* $(DestinationFolder)\Content" />
  </Target>
 
  <Target Name="deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\common\*.* $(DestinationFolder)" />
  </Target>
 
  <!-- Deployment configurations -->
  <Target Name="deploy_test" DependsOnTargets="build;deploy;deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\test\*.* $(DestinationFolder)" />
  </Target>
 
  <Target Name="deploy_prod" DependsOnTargets="build;deploy;deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\prod\*.* $(DestinationFolder)" />
  </Target>
</Project>

Here I have define tasks for compiling the web site (“build”), deploying the binaries + views + content files (“deploy”), deploying common configuration files (“deploy_common_configuration_files”), and then one task for each deployable configuration: “deploy_test” and “deploy_prod”. This makes deploying the web site on my test web server as easy as running the following command:

msbuild /t:deploy_test

What is left now, is to make sure that the different sets of configuration files are valid in the sense that Windsor can resolve everything right. That is easily accomplished in the following NUnit test:

[TestFixture]
public class TestWindsorCanResolve
{
	const string ConfigFileRoot = @"..\..\..\WebSite\Config";
 
	[Test]
	public void CanMakeControllerInstances_test()
	{
		CheckConfiguration("test");
	}
 
	[Test]
	public void CanMakeControllerInstances_prod()
	{
		CheckConfiguration("prod");
	}
 
	static void CheckConfiguration(string configuration)
	{
		var controllerTypes = GetControllerTypes();
		var container = GetContainer(configuration);
 
		// using the given controllers and the given Windsor container - make sure
		// every controller can be instantiated
		controllerTypes.ForEach(t => container.Resolve(t.Name.Substring(0, t.Name.LastIndexOf("Controller")).ToLower()));
	}
 
	static IWindsorContainer GetContainer(string configuration)
	{
		// get path to configuration to test (inside the web site project)
		var path = ConfigFileRoot + Path.DirectorySeparatorChar 
				+ configuration + Path.DirectorySeparatorChar 
				+ "windsor.config";
 
		// configure Windsor
		var windsorContainer = new WindsorContainer(new XmlInterpreter(path));
 
		return windsorContainer;
	}
 
	static List<Type> GetControllerTypes()
	{
		// get assembly with controllers
		var assembly = Assembly.GetAssembly(typeof (HomeController));
 
		var types = assembly.GetTypes();
 
		// get all controller types
		return new List<Type>(types)
			.FindAll(t => typeof (IController).IsAssignableFrom(t)
			              && !t.IsAbstract);
	}
}

This way, if I introduce a service in my development configuration that should have been implemented by a production version of the service in my production configuration, I will immediately know about it.

I think this post covers an easy and pragmatic way to control multiple configurations with Windsor and ASP.NET MVC. Of course you might want to split out the configuration-specific parts into multiple files instead of having only a windsor.config for each configuration. What I mean is something like this:

<castle>
  <include uri="file://controllers-common.config"/>
  <include uri="file://controllers.config"/>
 
  <include uri="file://facilities-common.config"/>
  <include uri="file://facilities.config"/>
 
  <include uri="file://factories-common.config"/>
  <include uri="file://factories.config"/>
 
  <include uri="file://repositories-common.config"/>
  <include uri="file://repositories.config"/>
 
  <include uri="file://services-common.config"/>
  <include uri="file://services.config"/>
</castle>

The great thing is that we can refactor our configuration with confidence because of our test. And if we want to be extra-certain that everything works as expect, we might begin to add assertions like this:

public class TestWindsorCanResolve
{
	// (...)
 
	[Test]
	public void OnlyProductionEnvironmentCanSpamOurSensitiveClients()
	{
		Assert.IsTrue(GetContainer("development").Resolve<IEmailSender>() is FakeLoggingEmailSender);
		Assert.IsTrue(GetContainer("test").Resolve<IEmailSender>() is FakeLoggingEmailSender);
	}

I have been thinking a little bit about the visitor pattern recently. One of my most recent applications was in combination with a class, which would be used in a message distribution scenario.

The class’ reposibility is – given a list of email addresses – to look up any existing users in my application, and allow the caller to perform an action depending on whether the email belongs to a registered user or not. Pretty simple if you feel like juggling dictionaries and stuff, but I made an even simpler solution.

My email lookup service has the following interface:

public interface IUserEmailLookupService
{
    IEnumerable<Recipient> GetRecipients(IEnumerable<string> emails);
}

And then I have two classes: EmailRecipient and UserRecipient which are both specializations of the abstract superclass Recipient – each containing either an email (a string) or an IUser depending on whether the service was able to look up a user.

Then I have another service, which functions as a message distributor. Given a list of email addresses, either an email or an internal message will be delivered to each recipient. This is a perfect application for the visitor pattern, because it allows us to avoid this kind of brittle code:

// violates the open-closed principle
if (recipient is EmailRecipient)
{
    emailService.Send(((EmailRecipient)recipient).Email, message);
}
else if (recipient is UserRecipient)
{
    messageService.Send(((UserRecipient)recipient).User, message);
}
else
{
    throw new UnexpectedSpecializationException("But why??");
}

I have seen this kind of code in far too many places where inheritance is used. It is obviously very brittle, because what happens if someone adds another kind of Recipient? Nothing at first, because the code will compile like everything is allright. Only after the code is run, and we actually get in a situation where another kind of Recipient is encountered, do we get an error… and in the example above, I was courteous and threw an exception – but what if the original author had not done that? The program could have been silently failing for months before someone found out… yikes!

Another solution is to move the behavior into the specializations – e.g. into an implementation of an abstract SendMessage method on Recipient. But then the specializations would require a reference to either the emailService or the messageService, which would kind of turn the layering upside down, since the domain classes would need to know about some higher level services.

What we really want, is for a service to be able to behave differently depending on which specialization is encountered, and for that service to contain the logic to handle each specialization. And we want errors at compile-time if a specialization is not handled. Enter the visitor pattern…

One way to accomplish this is by using the visitor pattern as described by GoF. It’s pretty simple: Make a call to an abstract method which gets implemented by each specialization, and let that specialization make a suitable callback to identify itself. My visitor interface looks like this:

public interface IRecipientVisitor
{
    void VisitUserRecipient(UserRecipient recipient);
    void VisitEmailRecipient(EmailRecipient recipient);
}

- and then each specialization must implement the abstract Visit method from the Recipient class:

public abstract void Visit(IRecipientVisitor visitor);

and then invoke their correponding callback method passing themselves back.

Then my client can create an implementation of IRecipientVisitor, supplying it with the necessary services, allowing the visitor to do different stuff depending on the specializations. But that requires me to implement a class like this every time I have a reason to do different stuff:

class MessageDispatcherVisitor : IRecipientVisitor
{
    // implements a message dispatch for each type of visit...
}

Having done this a few times, implementing a new class each time which would be used only once, I started thinking about how to accomplish this with fewer lines of code. One thing that really bugged me, was that I needed to supply the visitor with all kinds of context data to allow the visitor to perform whichever action it would decide to carry out, depending on which Visit(...) method would be called. Then I came up with the generic visitor:

public class RecipientVisitor : IRecipientVisitor 
{
    readonly Action<UserRecipient> handleUserRecipient;
    readonly Action<EmailRecipient> handleEmailRecipient;
 
    public RecipientVisitor(Action<UserRecipient> handleUserRecipient,
                            Action<EmailRecipient> handleEmailRecipient)
    {
        this.handleUserRecipient = handleUserRecipient;
        this.handleEmailRecipient = handleEmailRecipient;
    }
 
    public override void VisitUserRecipient(UserRecipient recipient)
    {
        handleUserRecipient(recipient);
    }
 
    public override void VisitEmailRecipient(EmailRecipient recipient)
    {
        handleEmailRecipient(recipient);
    }
}

Now my message dispatch can be implemented like this:

var recipients = lookupService.GetRecipients(emails);
 
var visitor = new RecipientVisitor(r => messageService.Send(r.User, message),
                                   r => emailService.Send(r.Email, message));
 
recipients.ForEach(r => r.Visit(visitor));

Why is this great?

1. I get to implement multiple dispatch with all the safety of the visitor pattern. If I add a new specialization of Recipient, e.g. ErronousEmailRecipient, I add a new method to the IRecipientVisitor interface. That causes the RecipientVisitor to break, so I implement the new method in there as well, in turn causing the code to break everywhere the visitor is used (“break” in a good not introducing bugs-kind-of-way). That way I can be sure that I will know where to handle this new specialization.

2. I get access to the context I am already in. Instead of creating a new visitor and supplying it with sufficient context to carry out whichever actions it needs to perform, I can specify in a short and concise way what I want to do for each specialization, accessing any local variables inside of the scope my labdas are in. That’s just elegant and easy.

3. The code is where it is used. The distance from usage to implementation is zero. Of course, if the implementation is more complex, it may look more like so:

var results = new List<Result>();
 
var visitor = new RecipientVisitor(
    r => 
    {
        var message = GetMessageFromContentService("SomeUserMessage", r.User);
        var result = SendMessageAndGetResult(message, r.User);
        results.Add("SendMessage", result);
    },
    {
        (...)
    }
);

- which is still pretty terse and to-the-point compared to creating an entirely new dedicated class for this.

Well, it happened when I was making a web page on which the user could pick a number of time slots. The time slots would be configured using a calendar and a couple of time entry controls, and the user would add the time slot by clicking a button. The selected time slots would be stored as a JSON serialized array of time slots in an input element.

The selected time slots would be shown in a list on the page, each one with an X on the side which could be used to remove the appropriate time slot. The problem was, that it did not remove the appropriate time slot. But why?

It’s because of the way JavaScript’s closures are implemented!

You see, my code was something like this (using Crockford’s JSON library and the incredible jQuery):

// get array of selected time slots
var timeSlots = JSON.parse($('#selectedTimeSlotsJson').val());
 
// create representation, including a link to remove each time slot
for(var index = 0; index < timeSlots.length; index++) {
    var timeSlot = timeSlots[index];
    var id = timeSlot.id;
 
    var removeTimeSlotLink = $('<img>')
        .attr('src', deleteTimeSlotImagePath)
        .bind('click', function() { removeTimeSlot(id); })
        .addClass('hasPointer');
 
    // more code here to create and attach a DOM element containing
    // a string representation of the time slot and the removeTimeSlotLink
    // (...)
}

What happened when I tried to remove the time slots? The most recently added time slot would get removed all the time, even though I clicked the first and the second etc.

At this point, I knew it was due to some JavaScript function closure stuff, because I could see that my click event handler would call removeTimeSlot with the id of the most recently added time slot all the time.

But why was this happening? I made all kind of changes to the snippet, moved the variables around, made several temporary variables, but the problem persisted!

Then I searched around, and I discovered two things that I did not know about JavaScript (and would not have expected):

  1. Variables reside in the function in which they are declared.
  2. Functions get the closure of their containing function.

I am a C# guy, and in C# I know that an anonymous delegate gets the closure that it needs and nothing more. I also know that variables declared inside the scope of for instance a for loop are local to that loop. So doing stuff like this would not cause any unexpected behaviour:

foreach(var timeSlot in timeSlots) {
    // create local reference to be lifted out of this scope
    var timeSlotTemp = timeSlot;
 
    var button = new Button();
    button.Click += delegate { RemoveTimeSlot(timeSlotTemp); };
 
    // place button somewhere
    // (...)
}

To put it another way, it means that my code was actually equivalent to this (notice how all my variabled are “declared” at the top of the function):

// get array of selected time slots
var timeSlots = JSON.parse($('#selectedTimeSlotsJson').val());
var index;
var timeSlot;
var id;
var removeTimeSlotLink;
 
// create representation, including a link to remove each time slot
for(index = 0; index < timeSlots.length; index++) {
    timeSlot = timeSlots[index];
    id = timeSlot.id;
 
    removeTimeSlotLink = $('<img>')
        .attr('src', deleteTimeSlotImagePath)
        .bind('click', function() { removeTimeSlot(id); })
        .addClass('hasPointer');
 
    // more code here to create and attach a DOM element containing
    // a string representation of the time slot and the removeTimeSlotLink
    // (...)
}

To circumvent this, I created an inline function which would deliver the DOM element with the link. Something like this:

// get array of selected time slots
var timeSlots = JSON.parse($('#selectedTimeSlotsJson').val());
var index;
var timeSlot;
var removeTimeSlotLink;
 
var createRemoveTimeSlotLink = function(id) {
    // id is safe in here... :-)
    return $('<img>')
        .attr('src', deleteTimeSlotImagePath)
        .bind('click', function() { removeTimeSlot(id); })
        .addClass('hasPointer');
};
 
// create representation, including a link to remove each time slot
for(index = 0; index < timeSlots.length; index++) {
    timeSlot = timeSlots[index];
 
    removeTimeSlotLink = createRemoveTimeSlotLink(timeSlot.id);
 
    // (...)
}

- and from now on, to avoid unnecessary confusion, I will stop declaring my variables anywhere except the beginning of each function.

Lastly, I would like to give some shoutouts to the Mozilla folks for driving us all forward. Firefox 2 actually implements JavaScript 1.7, in which let was introduced as a keyword. let creates a new lexical scope and fixes one or more variables, which will then be promoted to a closure if necessary. Using let, my code would look like this:

// get array of selected time slots
var timeSlots = JSON.parse($('#selectedTimeSlotsJson').val());
 
// create representation, including a link to remove each time slot
for(var index = 0; index < timeSlots.length; index++) {
    var timeSlot = timeSlots[index];
 
    // introduce a new scope where id resides
    let (id = timeSlot.id) {
        var removeTimeSlotLink = $('<img>')
            .attr('src', deleteTimeSlotImagePath)
            .bind('click', function() { removeTimeSlot(id); })
            .addClass('hasPointer');
    }
 
    // more code here to create and attach a DOM element containing
    // a string representation of the time slot and the removeTimeSlotLink
    // (...)
}

- which is a lot simpler than the inline function version I ended up using. However, JavaScript 1.7 is not implemented by other browsers than Firefox 2 and Safari 3.x (according to Wikipedia) so it’s not really an option yet.

© 2010 mookid on code Suffusion WordPress theme by Sayontan Sinha