Entries categorized 'Blog' ↓

Testing IoC Registrations

When I first started writing automated unit tests for my code, I remember getting carried away writing lots of tiny little tests, each with a single Assert. It felt good initially to see all those green ticks, but rapidly became a maintenance headache, and I am now happier having fewer less-brittle tests that do more.

I think it’s great when tools like AutoMapper provide powerful methods like...

AutoMapper.Mapper.AssertConfigurationIsValid();

...allowing me to test large swathes of the system configuration with a single, stable test.

I wanted to write a similar test to check that all the necessary system dependencies for my MVC application could be resolved by the IoC container. Here’s what I came up with:

[ClassInitialize]
public static void MyClassInitialize(TestContext testContext)
{
    var guyWire = new GeneralGuyWire();
    guyWire.Wire();
}

/// <summary>
/// Tests that the IoC container can resolve instances of each Controller.
/// 
/// Assuming that constructor DI is used throughout the system, this will
///  indirectly test that all dependencies have been correctly registered.
/// </summary>
[TestMethod]
public void Wire_CanResolveAllControllers()
{
    Assembly
        .GetAssembly(typeof(HomeController))
        .GetExportedTypes()
        .Where(t => MvcContrib.ControllerExtensions.IsController(t))
        .ForEach(c => Assert.IsNotNull(ServiceLocator.Current.GetInstance(c)));
}

A few things to note:

  1. I’m configuring my container using the GuyWire pattern described by Fabio Maulo.
  2. I’m using ControllerExtensions from the MvcContrib project to identify controllers.
  3. I’m accessing the IoC container via the Common Service Locator.
  4. This only tests the dependencies that are referenced by dependency injection, and won’t pick up on any missing registrations that are only referenced via service locator (you’d have to write separate itty-bitty tests to check those registrations).

What do you think? How, if at all, do you test your IoC container registrations?

SupportDetails.com

Here’s a super-handy little site for anyone who’s ever had to perform website support over the phone.

Instruct the user to navigate to SupportDetails.com. They can then see the answers to most of the questions you’re likely to ask, and have the option to send the details to you by email. Sweet.

SupportDetails

WCF - NHibernate Unit Of Work Endpoint Behavior

OK, my last WCF-related code snippet of the day, I promise. This is quite similar to the last one. I required that the WCF service I was developing started a new NHibernate Session for each invocation, and closed it after invocation (i.e. session-per-request). I couldn’t rely on the ASP.NET session start and end events in global.asax as this particular WCF service was to respond to MSMQ messages rather than HTTP.

So, once again I found myself bashing out a custom EndpointBehavior to add a custom CallContextInitializer to every operation:


using System;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

/// <summary>
/// Being a custom EndpointBehavior added to the WCF services such that each operation begins a 
/// new unit of work when invoked, and closes the same unit of work after invocation.
/// </summary>
/// <remarks>
/// In practice, we are using this simply to manage NHibernate sessions - opening a new Session at
/// the start of each operation, and closing it as the operation completes.
/// </remarks>
public class UnitOfWorkEndpointBehavior : IEndpointBehavior
{
    /// <summary>
    /// Local instance of unit of work implementation.
    /// </summary>
    /// <remarks>
    /// Interface is ORM-agnostic, it need not be NHibernate.
    /// </remarks>
    private IUnitOfWork unitOfWork;
    
    /// <summary>
    /// Initializes a new instance of the UnitOfWorkEndpointBehavior class.
    /// </summary>
    /// <param name="unitOfWork">Unit of Work</param>
    public UnitOfWorkEndpointBehavior(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    {
        // Add a new Unit of Work call context initializer to every operation.
        foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
        {
            operation.CallContextInitializers.Add(new UnitOfWorkCallContextInitializer(this.unitOfWork));
        }
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

/// <summary>
/// Custom call context initializer added to all WCF operations such that each operation begins
/// a new unit of work when invoked, and closes the same unit of work after invocation.
/// </summary>
/// <remarks>
/// In practice, we are using this simply to manage NHibernate sessions - opening a new Session at
/// the start of each operation, and closing it as the operation completes.
/// </remarks>
public class UnitOfWorkCallContextInitializer : ICallContextInitializer
{
    /// <summary>
    /// Local instance of unit of work implementation.
    /// </summary>
    /// <remarks>
    /// Interface is ORM-agnostic, it need not be NHibernate.
    /// </remarks>
    private IUnitOfWork unitOfWork;

    /// <summary>
    /// Initializes a new instance of the UnitOfWorkCallContextInitializer class.
    /// </summary>
    /// <param name="unitOfWork">Unit of Work</param>
    public UnitOfWorkCallContextInitializer(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    /// <summary>
    /// Method fired after the operation is invoked.
    /// </summary>
    /// <param name="correlationState"></param>
    public void AfterInvoke(object correlationState)
    {
        // End the unit of work (closes the NH session).
        this.unitOfWork.End();
    }

    /// <summary>
    /// Method fired before the operation is invoked.
    /// </summary>
    /// <param name="instanceContext"></param>
    /// <param name="channel"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
    {
        // Begin a new unit of work (opens the NH session).
        return this.unitOfWork.Start();
    }
}


And the Windsor configuration is much the same as before:
container.Register(
    Component.For<UnitOfWorkEndpointBehavior>()
    .Attribute("scope").Eq(WcfExtensionScope.Services));

WCF – Logging Before and After Operation Invocation

Here’s another custom WCF EndpointBehavior I found useful recently.

Not content with logging all unhandled errors, I wanted to output a DEBUG level log message before and after every operation invocation. As before, I’m using the Castle Windsor Logging Facility to handle my logging, but you can swap that out for your logger of choice if required.

Firstly, here’s the EndPointBehaviour itself. This adds a custom CallContextInitializer to every service operation:

using System;
using System.ServiceModel.Description;
using Castle.Core.Logging;

/// <summary>
/// Being a custom EndpointBehavior added to the WCF services such that each operation outputs
///  a debug log message before and after invocation.
/// </summary>
public class OperationLoggingEndpointBehavior : IEndpointBehavior
{
    private readonly ILogger logger;

    public OperationLoggingEndpointBehavior(ILogger logger)
    {
        this.logger = logger;
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    {
        foreach (var operation in endpointDispatcher.DispatchRuntime.Operations)
        {
            operation.CallContextInitializers.Add(new OperationLoggingCallContextInitializer(this.logger, operation.Name, endpoint.Contract.Name));
        }
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

Here's the custom CallContextInitializer:

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Castle.Core.Logging;

/// <summary>
/// Custom call context initializer added to all WCF operations such that each operation outputs
///  a log message before and after invocation.
/// </summary>
public class OperationLoggingCallContextInitializer : ICallContextInitializer
{
    private readonly ILogger logger;
    private readonly string operationName;
    private readonly string contractName;

    public OperationLoggingCallContextInitializer(ILogger logger, string operationName, string contractName)
    {
        this.logger = logger;
        this.operationName = operationName;
        this.contractName = contractName;
    }

    public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
    {
        this.logger.DebugFormat("BeforeInvoke {0}.{1}", this.contractName, this.operationName);
        return null;
    }

    public void AfterInvoke(object correlationState)
    {
        this.logger.DebugFormat("AfterInvoke {0}.{1}", this.contractName, this.operationName);
    }
}

And the Windsor configuration is much the same as last time:

container.Register(
    Component.For<OperationLoggingEndpointBehavior>()
    .Attribute("scope").Eq(WcfExtensionScope.Services));

WCF – Global Exception Handling

I’ve done a fair bit of WCF development recently (and amazingly I came out of it relatively unscathed, both psychologically and emotionally). Using Castle Windsor’s WCF Facility helped a great deal, but I still found myself writing a fair bit of infrastructure and plumbing code. I thought I’d blog some of these code snippets lest I forget, and on the offchance they might help others.

One of the things I wanted to achieve was to ensure that any unhandled exceptions that propagated to the top of the stack were logged. The following custom EndpointBehavior achieves that. I’m using Castle Logging Facility here, but you could of course swap out the logging code for whatever error handling code you require.

using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Castle.Core.Logging;

/// <summary>
/// Being a custom EndpointBehavior added to the WCF services to provide custom error handling functionality.
/// Namely, logging error so it doesn't get ignored.
/// </summary>
public class ErrorHandlerBehavior : IEndpointBehavior, IErrorHandler
{
    /// <summary>
    /// Backing store for <paramref name="Logger"/>.
    /// </summary>
    /// <remarks>Defaults to a NullLogger, so that this component can safely be used even if logging has not been configured.</remarks>
    private ILogger logger = NullLogger.Instance;

    /// <summary>
    /// Gets or sets a component for providing logging functionality.
    /// </summary>
    public ILogger Logger
    {
        get { return this.logger; }
        set { this.logger = value; }
    }

    /// <summary>
    /// Handles an exception.
    /// </summary>
    /// <param name="error">Exception to be handled</param>
    /// <returns>Indication of whether it is safe for WCF to continue using state associated with the failed request.</returns>
    public bool HandleError(Exception error)
    {
        // Just log the error, umkay?
        this.Logger.Error("Unhandled exception occurred", error);
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        // Add ourself to the collection of error handlers.
        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(this);
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}
Here's the relevant line from my Windsor configuration:
container.Register(
    Component.For<ErrorHandlerBehavior>()
    .Attribute("scope").Eq(WcfExtensionScope.Services));

Testing LINQ Queries

I’ve been asked “How do you test LINQ queries?” a couple of times in the past few months, so I thought I’d blog my answer for the benefit of all you lovely people.

Firstly I should explain how I’ve been doing most of my data access in recent months. I find that the Repository pattern, and particularly the .NET implementation described here by Fabio Maulo meets the vast majority of requirements I have in my applications, and I fall back on additionally using custom DAOs when required.

So, my service classes can ask the IoC container for instances of IRepository<T>, where IRepository<T> implements IQueryable<T>.

Now, in the best tradition of encapsulation, all but the most trivial of the queries I write against these repositories are defined in extension methods, for example:

/// <summary>
/// Finds leads in the repository by Customer Name.
/// </summary>
/// <param name="repo" />Repository of Leads</param>
/// <param name="customerName" />Customer name</param>
/// <returns>Leads matching the criteria</returns>
public static IQueryable<Lead> ByCustomerName(this IQueryable<Lead> repo, string customerName)
{
    if (customerName.IsNullOrEmpty())
    {
        return repo;
    }

    return repo
        .Where(
            l => l.Customers.Any(c => c.Name.Contains(customerName)));
}

Aside from the testability aspect (which I promise I’ll get onto in a second), this approach also helps keep us on the right side of the Law of Demeter, as Garry Shutler blogged about recently. It also allows for method chaining, allowing us to enact multiple filters and other transformations in a single line of code:

return this.leadRepository
    .ByAllocatedUserId(query.AllocatedUserId)
    .ByClosed(query.Closed)
    .ByCustomerId(query.CustomerId)
    .ByCustomerName(query.CustomerName)
    .ByLeadTypeIds(query.LeadTypeIds)
    .ByProjectId(query.ProjectId)
    .ByScapeId(query.ScapeId)
    .ByStarred(query.Starred)
    .Sort(sortField, sortDescending)
    .Skip(offset)
    .Take(maximumResults)
    .ToDto()
    .ToArray();

But I digress. I was talking about how to test these LINQ queries. It’s easy really, the trick is knowing that IEnumerable<T> offers an AsQueryable() method. So, we can build up some dummy data in a List<T> before calling AsQueryable() to obtain an object against which the extension method can act. Dead simple. The creation of the test data can even be automated using the open source NBuilder tool.

One caveat – this is merely testing that your LINQ query does what you think it should do, it doesn’t test the behaviour of the underlying LINQ provider. If you’re using, say, the NHibernate LINQ 1.0 provider (which is great but not at all feature-complete) then you’ll also need to write some suitable integration tests, say by testing against the Sqlite database engine.

An MVC Gotcha and the PRG Pattern

If you’ve recently moved across to ASP.NET MVC development following years of wrangling with the leaky abstraction that was WebForms, you may have encountered some seemingly curious behaviour when posting back to the same URL.

Suppose we have the following simple, contrived and utterly imagination-free model:

using System;

namespace MvcGotcha1.Models
{
    public class FooModel
    {
        public int FooCounter { get; set; }
    }
}

Here’s a view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcGotcha1.Models.FooModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Foo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Foo</h2>
    <% using (Html.BeginForm())
       { %>
    <%=Html.TextBoxFor(m=>m.FooCounter) %><br />
    <%=Html.DisplayFor(m=>m.FooCounter) %><br />
    <input type="submit" value="Increment!" />
    <% } %>
</asp:Content>

And here’s the controller:

using System;
using System.Web.Mvc;
using MvcGotcha1.Models;

namespace MvcGotcha1.Controllers
{
    public class FooController : Controller
    {

        public ActionResult Index()
        {
            var model = new FooModel() { FooCounter = 1 };

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(FooModel model)
        {
            model.FooCounter++;

            return View(model);
        }
    }
}

Note that we have two separate Index actions – one for HTTP GET which instantiates and displays a new FooModel instance, and one for HTTP POST which modifies one of the properties on the posted FooModel instance before re-rendering the view.

We issue a GET against the relevant URI, and the view renders as we expect (in that both the textbox and the literal show the value 1:

Foo1

But here’s the gotcha – look what happens when we hit the increment button to post back:

Foo2

Huh? What gives? The model has definitely been updated (as reflected in the literal which is now showing 2), but the textbox is still stubbornly displaying 1.

What’s happening is that the Html helpers for form fields (including hidden fields) take their values from the controller’s ModelState dictionary, which contains details of all the POSTed fields and any validation errors.

So how to achieve our desired behaviour? We could make a quick and dirty call to ModelState.Clear(), but that’s not such a good idea and might lead to undesirable results surrounding validation.

In fact, this gotcha is symptomatic of a deeper anti-pattern in evidence in this example, namely rendering views from POST actions. Consider what happens if the user refreshes their browser when viewing the POSTed view. Recognise these dialog boxes?

IE

Chrome

Firefox

Pretty ugly, aren’t they? And you really don’t want to leave open the possibility of a user accidentally submitting duplicate transactions if at all possible.

Enter the Post, Redirect, Get pattern. Here, the POST action updates the model as before, but redirects to the GET action to perform the re-rendering of the view. Of course, you’ll need to persist the model somewhere in the meantime (e.g. session state). This pattern avoids the gotcha of a value from the ModelState being displayed instead of an updated figure, and ensures that your user will never see those ugly form resubmission dialog boxes, or submit duplicate transactions.

Here’s a quick reworking of the earlier controller to use this pattern. Note the introduction of a “New” action to handle the instantiation of a new Foo instance. This is crummy code fraught with potential uncaught NullReferenceExceptions, but you’ll get the gist, I’m sure.

using System;
using System.Web.Mvc;
using MvcGotcha1.Models;

namespace MvcGotcha1.Controllers
{
    public class FooController : Controller
    {
        public ActionResult New()
        {
            var model = new FooModel() { FooCounter = 1 };

            Session["model"] = model;

            return RedirectToAction("Index");
        }

        public ActionResult Index()
        {
            var model = Session["model"];

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(FooModel model)
        {
            model.FooCounter++;

            Session["model"] = model;

            return RedirectToAction("Index");
        }
    }
}

And now we get the desired results on postback:

Foo3

If you’re using MVC, and returning ViewResults from POST actions, I would urge you to consider the potential side-effects of that approach, and standardise instead on a PRG pattern.

On the Relative Prices of Petrol and Diesel

I have a question about the economics of fuel prices, and I’m sure one of you clever folks will be able to help.

I was just reading the BBC News website, and saw this story predicting that UK fuel prices could reach a new record high over the Easter weekend. That surprised me, as I was certain I could remember paying around 10p per litre more than current prices during the summer of 2008.

In an effort to check my memory, I scampered over to http://data.gov.uk and searched for “fuel prices”, which led me to this page on the Department of Energy & Climate Change website offering an Excel spreadsheet detailing weekly average fuel prices.

An aside – I thought the whole point of http://data.gov.uk was for the data to be available on that site, in an open, queryable format? Most of the search results seem to be nothing more than links to Excel 2003 spreadsheets or (worse) PDFs hosted across dozens of disparate government websites? Oh well. Excel works for me, and it’s a start I suppose.

Anyway, having downloaded the spreadsheet, I charted the prices of both unleaded and diesel over the past three years:

PetrolVsDiesel

So my memory wasn’t playing tricks on me. Our Toyota runs on diesel, and sure enough back in summer 2008 it was costing me over 130p/litre to fill up, compared to around 120p/litre now. But the news article wasn’t fibbing – it talks specifically about the price of unleaded petrol, which was 120p/litre both at the previous peak and now.

It seems that the differential between the price of petrol and diesel grew as high 15.09p at one point in December 2008, but has all but disappeared now. Here’s another graph showing the premium that diesel owners have been paying, per litre, since summer 2003:

PetrolVsDiesel2

So, the question I have is – why did this price differential between the price of petrol and diesel arise between 2007-9, and why has it diminished again now?

Oh, and for my US readers – yes, you read it right. We really do pay 120 pence per litre for gas, or $6.90 per US gallon. Count your blessings!

On the Market Again

This blog post comes to you live from a Starbucks in the north of England.

Yesterday I wrapped up another eight months’ stint contracting at my old haunt Marshalls Plc. It’s been a genuinely interesting gig, working on two distinct greenfield projects using bang up to date technologies including .NET 4.0 and MVC2.

But it hasn’t just been a benefit for my CV, I think Marshalls might have got a little something out of the arrangement too, as Marshalls’ Development Manager Sion Harrison commented yesterday:

"You have enabled us to drive some major changes into the business whilst introducing new technologies and concepts to the team. We now have great working examples of Workflow, NHibernate, IOC, programming to interfaces and MVC code which can be applied in other applications. I couldn't have asked for more - a combination of business and technological advancement. Thanks again."

Could I help to advance your business in a similar manner? If so, give me a call on 07901 828483 or email ian@iannelsonsystems.com .

In the meantime, I’ll get back to my cinnamon swirl and venti latté…

Recursion

Oh, those witty Google engineers!

Recursion