finishing the windsor mvc controller factory

This is the seventh in a series of posts illustrating building a custom Windsor registration process and I've almost completed the Windsor controller factory.

After testing out my controller with a quick integration into the test of my code base, I observed at runtime that if the controller cannot be found by the factory and it returns null that an error is thrown by the MVC framework:
"System.InvalidOperationException: The IControllerFactory 'Apollo.Infrastructure.Windsor.WindsorControllerFactory' did not return a controller for a controller named 'xxx'".

I now want to account for this and to communicate to the client the correct status for this http request and my specification for this is as follows:

[Observations]
public class when_an_unrecognised_controller_is_requested :
         observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static string unrecognisedController;

    private context c = () => unrecognisedController = "NotRecognised";

    private because b = () => doing( ()=> sut.CreateController(null, unrecognisedController) );

    [Observation]
    public void should_fail_appropriately_as_a_http_error()
    {
        exception_thrown_by_the_sut.should_be_an_instance_of<HttpException>();
    }
}

Here, I am using the doing() method to delay the execution of my because action until the "exception_thrown_by_sut" is examined. This test fails because I am returning null when the controller type is not found, so I can implement this as follows:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    var controllerType = GetControllerTypeFromLoadedAssemblies(controllerName);

    if(controllerType==null)
        throw new HttpException(0, string.Format("Could not find a 
                      controller for the request for {0}.", controllerName));

    return container.Resolve<IController>(controllerType.FullName.ToLower());
}

My test now passes, but I need one more observation to ensure this works as desired:

[Observations]
public class when_an_unrecognised_controller_is_requested : 
         observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static string unrecognisedController;
    private static int theExpectedHttpStatusCode;

    private context c = () =>
                            {
                                unrecognisedController = "NotRecognised";
                                theExpectedHttpStatusCode = 404;
                            };

    private because b = () => doing( ()=> sut.CreateController(null, unrecognisedController) );

    [Observation]
    public void should_fail_appropriately_as_a_http_error()
    {
        exception_thrown_by_the_sut.should_be_an_instance_of<HttpException>();
    }

    [Observation]
    public void should_communicate_the_correct_http_status()
    {
        ((HttpException)exception_thrown_by_the_sut).GetHttpCode()
                          .should_be_equal_to(theExpectedHttpStatusCode);
    }
}

And this is easily implemented with a change to the status code when creating an instance of the HttpException:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    var controllerType = GetControllerTypeFromLoadedAssemblies(controllerName);

    if(controllerType==null)
        throw new HttpException(404, string.Format("Could not find a 
                      controller for the request for {0}.", controllerName));

    return container.Resolve<IController>(controllerType.FullName.ToLower());
}

All that's left to do now on this class is to implement the ReleaseController method of the IControllerFactory interface so I write my specification for this first:

[Observations]
public class when_a_controller_is_released_from_the_windsor_controller_factory : 
       observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static IWindsorContainer container;
    private static FakeController controller;

    private context c = () =>
    {
        container = the_dependency<IWindsorContainer>();
        controller = new FakeController();
    };

    private because b = () => sut.ReleaseController(controller);

    [Observation]
    public void should_release_the_controller_from_the_container()
    {
        container.was_told_to(c => c.Release(controller));
    }
}

In my specification I want to ensure that when the controller factory is asked to release the controller that the Windsor IOC container releases the transient controller instance and thus free it up for garbage collection - if I don't do this then the reference is held for the lifetime of the Windsor kernel.

The implementation is really straightforward:

public void ReleaseController(IController controller)
{ 
    container.Release(controller);   
}

I've now completed my illustration of test-driving the creation of a Windsor controller factory. In the next post in this series I'll move onto how I implemented this in the application.

Posted at at 7:24 AM on Monday, November 23, 2009 by Posted by Justin Davies | 3 comments Links to this post   | Filed under: , , , ,

adding to the windsor mvc controller factory

This is the sixth in a series of posts illustrating building a custom Windsor registration process. I'm currently test driving an implementation of a Windsor controller factory for ASP.NET MVC and have discovered that the ASP.NET MVC framework will be calling CreateController without the "Controller" suffix in the controller name.

I therefore need a new specification to address this:

[Observations]
public class when_a_controller_is_requested_from_the_factory_without_a_controller_suffix :
    observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static string controllerName;
    private static Type controllerType;
    private static WindsorContainer container;
    private static IController returnedController;

    private context c = () =>
                        {
                            controllerName = "Fake";
                            controllerType = typeof (FakeController);
                            container = new WindsorContainer();
                            container.AddComponentLifeStyle(controllerType.FullName.ToLower(),
                                controllerType, LifestyleType.Transient);
                        };

    public override IControllerFactory create_sut()
    {
        return new WindsorControllerFactory(container);
    }

    because b = () => returnedController = sut.CreateController(null, controllerName);

    [Observation]
    public void should_return_a_known_instance_of_the_controller()
    {
        returnedController.should_be_an_instance_of<FakeController>();
    }
}

When this test runs it fails with a NullReferenceException on the return line of the CreateController method where the controllerType.FullName property is used on a null reference. I note this down so that I can write a specification for that a little later on.

For now, to implement this new requirement I write the code as follows:

public class WindsorControllerFactory : IControllerFactory
{
    private IWindsorContainer container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        this.container = container;
    }

    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controllerType = GetControllerTypeFromLoadedAssemblies(controllerName);

        return container.Resolve<IController>(controllerType.FullName.ToLower());
    }

    private Type GetControllerTypeFromLoadedAssemblies(string controllerName)
    {
        Type controllerType = null;

        controllerName = EnsureCorrectFormattingOfControllerName(controllerName);

        var assemblies = AppDomain.CurrentDomain.GetApolloAssemblies();
        foreach (var assembly in assemblies)
        {
            controllerType = assembly.GetTypes().Where(t => t.Name == controllerName)
                                                .FirstOrDefault();
            if (controllerType != null)
                return controllerType;
        }

        return null;
    }

    private string EnsureCorrectFormattingOfControllerName(string controllerName)
    {
        if (!controllerName.EndsWith("Controller"))
            controllerName += "Controller";
        return controllerName;
    }

    public void ReleaseController(IController controller)
    {
        throw new NotImplementedException();
    }
}

I now have a new method that ensures the controller suffix is present before the type is obtained from the assemblies. It is now my intention to ensure this works for lowercase requests too, so I write a specification for that also:

[Observations]
public class when_a_controller_is_requested_from_the_factory_in_lower_case_without_a_suffix :
    observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static string controllerName;
    private static Type controllerType;
    private static WindsorContainer container;
    private static IController returnedController;

    private context c = () =>
                        {
                            controllerName = "fake";
                            controllerType = typeof (FakeController);
                            container = new WindsorContainer();
                            container.AddComponentLifeStyle(controllerType.FullName.ToLower(),
                                                      controllerType, LifestyleType.Transient);
                        };

    public override IControllerFactory create_sut()
    {
        return new WindsorControllerFactory(container);
    }

    private because b = () => returnedController = sut.CreateController(null, controllerName);

    [Observation]
    public void should_return_a_known_instance_of_the_controller()
    {
        returnedController.should_be_an_instance_of<FakeController>();
    }
}

This specification is almost exactly the same as the previous one, so at this stage I might normally consider refactoring the test code itself and push common parts to a base class, but for clarity here on my blog I'm illustrating each specification's code in full. This test now fails with the same NullReferenceException, so I put the implementation code in as:

private string EnsureCorrectFormattingOfControllerName(string controllerName)
{
    controllerName = EnsureCapitalisationOfFirstCharacter(controllerName);

    if (!controllerName.EndsWith("Controller"))
        controllerName += "Controller";
    return controllerName;
}

private string EnsureCapitalisationOfFirstCharacter(string controllerName)
{
    var beginningCharacter = controllerName.Substring(0, 1);
    if (beginningCharacter != beginningCharacter.ToUpper())
        controllerName = beginningCharacter.ToUpper() + controllerName.Substring(1);
    return controllerName;
}

This test passes and it is now time to revisit the cause of the NullReferenceException:

[Observations]
public class when_an_unknown_controller_is_requested_from_the_controller_factory :
    observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static string controllerName;
    private static IController returnedController;

    private context c = () => controllerName = "Unknown";

    because b = () => returnedController = sut.CreateController(null, controllerName);

    [Observation]
    public void should_return_gracefully_without_a_controller()
    {
        returnedController.should_be_null();
    }
}

The test fails with the familiar NullReferenceExceptiont that I want to get rid of, so the implementation is straightforward to resolve this:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    var controllerType = GetControllerTypeFromLoadedAssemblies(controllerName);

    if(controllerType==null)
        return null;

    return container.Resolve<IController>(controllerType.FullName.ToLower());
}

I now have a working implementation that meets my current specifications. I would normally move onto specifying edge case specifications (such as empty or null string passed as the controllerName variable into CreateController) but I'll stop here for the purpose of this blog post.

In my next post I'll finish off the WindsorControllerFactory by implementing the ReleaseController method.

Posted at at 7:26 AM on Friday, November 20, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , , , ,

what do you do with your code coverage results?

I was reading Dave Laribee's latest post "Code Coverage: what is it good for?" and there's a great tidbit in there:

while code coverage isn't proof that our testing efforts will yield higher maintainability, it does tell us a teams commitment to a test practice.

This is exactly what I believe is the main benefit of having an agreed code coverage metric in a team - to ensure a commitment to continue test practices on an ongoing project. In a test-driven environment it highlights when test-first isn't being performed or isn't covering all of the production code that is being written.

Once a commitment is in place, I believe code coverage results can enable you to grow as a developer - reviewing where you often slip from pure test-first development and leave areas of implementation untouched by a test can help you prevent that in the future.

100% coverage isn't unachievable in a test-first environment and is something I think you can push for but it does beg the question of how much benefit you gain from the extra work involved in filtering agreed edge cases and exceptional circumstances.
However, do you want everybody to be purely test-first and not to have production code that is not covered by a test - if so, I think 100% is the only goal you can aim for.
It seems to me that any target number is pretty arbitrary if you accept the fact that you can't achieve 100% - it just becomes a  stake in the ground that people can dance around.

Are the developers performing test-driven development and are they consistent?
That's really all you need from the metric.

Posted at at 8:05 AM on Wednesday, November 18, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

more windsor mvc controller factory

This is the fifth in a series of posts illustrating building a custom Windsor registration process. In my last post I reached a point where my code satisfied all my current specifications for a Windsor controller factory for ASP.NET MVC.

I now want to add a requirement where the type is resolved from the IOC container using the full type name in lower case - this will then match my previous controller registration process.
I therefore change both sets of specifications to cope with this - the first one is changed to expect the call to the Resolve method to use the lower case FullName:

[Observations]
public class when_a_controller_is_requested_from_the_windsor_controller_factory :
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static IWindsorContainer container;
    private static RequestContext requestContext;
    private static string controllerName;
    private static IController returnedController;
    private static IController theExpectedController;
    private static string theExpectedControllerNameResolved;

    private context c = () =>
            {
                container = the_dependency<IWindsorContainer>();
                controllerName = "FakeController";
                theExpectedControllerNameResolved = typeof(FakeController).FullName.ToLower();
                theExpectedController = an<IController>();
                container.expect_at_least_once(w => w.Resolve<IController>(controllerName))
                                         .IgnoreArguments()
                                         .Return(theExpectedController);
            };

    private because b = () => returnedController = sut.CreateController(null, controllerName);

    [Observation]
    public void should_ask_the_container_to_resolve_the_controller()
    {
        container.was_told_to(c => c.Resolve<IController>(theExpectedControllerNameResolved));
    }

    [Observation]
    public void should_return_the_controller_obtained_from_the_container()
    {
        returnedController.should_be_equal_to(theExpectedController);
    }
}

This results in the tests failing due to an expectation violation:
Rhino.Mocks.Exceptions.ExpectationViolationException: IWindsorContainer.Resolve<System.Web.Mvc.IController>("apollo.infrastructure.windsor.fakecontroller"); Expected #1, Actual #0.

...and the second set of specifications are changed so that the registration is made with the lower case FullName:

[Observations]
public class simple_when_a_controller_is_requested_from_the_windsor_controller_factory :
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static Type controllerType;
    private static IController returnedController;
    private static IWindsorContainer container;

    private context c = () =>
                        {
                            controllerType = typeof (FakeController);
                            container = new WindsorContainer();
                            container.AddComponentLifeStyle(controllerType.FullName.ToLower(),
                                              controllerType, LifestyleType.Transient);
                        };

    public override IControllerFactory create_sut()
    {
       return new WindsorControllerFactory(container);
    }

    private because b = () => returnedController = sut.CreateController(null,
                                                                      controllerType.Name);

    [Observation]
    public void should_return_an_instance_of_the_controller()
    {
        returnedController.should_not_be_null();
    }

    [Observation]
    public void should_return_the_correct_controller()
    {
        returnedController.should_be_an_instance_of<FakeController>();
    }
}

The tests fail with a ComponentNotFoundException because I am now registering with the full name, but resolving with the type name.
I now need to change the implementation code accordingly:

public class WindsorControllerFactory : IControllerFactory
{
    private IWindsorContainer container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        this.container = container;
    }

    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controllerType = GetControllerTypeFromLoadedAssemblies(controllerName);

        return container.Resolve<IController>(controllerType.FullName.ToLower());
    }

    private Type GetControllerTypeFromLoadedAssemblies(string controllerName)
    {
        Type controllerType = null;

        var assemblies = AppDomain.CurrentDomain.GetApolloAssemblies();
        foreach (var assembly in assemblies)
        {
            controllerType = assembly.GetTypes().Where(t => t.Name == controllerName)
                                                .FirstOrDefault();
            if (controllerType != null)
                return controllerType;
        }

        return null;
    }

    public void ReleaseController(IController controller)
    {
        throw new NotImplementedException();
    }
}

This new implementation looks in the relevant currently loaded assemblies and finds the type name - it uses a custom AppDomain extension method to find the assemblies:

public static class AppDomainExtensions
{
    public static IEnumerable<Assembly> GetApolloAssemblies(this AppDomain appDomain)
    {
        return AppDomain.CurrentDomain.GetAssemblies()
                        .Where(a => a.FullName.StartsWith("Apollo"));
    }
}

This forms the working implementation until I then discover that the ASP.NET MVC framework actually calls the CreateController method with the first part of the name of the controller - in this example it would call with "Fake" for the "FakeController".

In my next post I'll illustrate how I introduce new specifications to meet this new requirement.

Posted at at 7:01 AM on Monday, November 16, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , , , ,

revising the windsor mvc controller factory

This is the fourth in a series of posts illustrating building a custom Windsor registration process. I continue on from the last post where I was using test driven development to build a Windsor Controller Factory for ASP.NET MVC.

Following on from the last post, I have some breaking tests as a result of implementing the IOC container in the controller factory. I now need to revise the particular specifications so that I register the FakeController type with the IOC container. Note that I am also over-riding the SUT's creation so that I can provide a container pre-registered with this type:

[Observations]
public class when_a_known_controller_is_requested_from_the_windsor_controller_factory :
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static Type controllerType;
    private static IController returnedController;
    private static IWindsorContainer container;

    private context c = () =>
                            {
                                controllerType = typeof (FakeController);
                                container = new WindsorContainer();
                                container.AddComponentLifeStyle(controllerType.Name,
                                    controllerType, LifestyleType.Transient);
                            };

    public override IControllerFactory create_sut()
    {
        return new WindsorControllerFactory(container);
    }

    private because b = () => returnedController = sut.CreateController(null,
                                                                      controllerType.Name);

    [Observation]
    public void should_return_an_instance_of_the_controller()
    {
        returnedController.should_not_be_null();
    }

    [Observation]
    public void should_return_the_correct_controller()
    {
        returnedController.should_be_an_instance_of<FakeController>();
    }
}

All of the specifications now pass and I'm happy with a basic implementation.

However in my previous Windsor registration process for Controllers (in the first post of this series) I am registering the controllers with the FullName in lower case.
I want to keep that registration process intact as I want to know the namespace of the type when inspecting the container so I will have to introduce this into my WindsorControllerFactory.

In my next post I'll look at revising my specifications to fit this new requirement.

Posted at at 7:30 AM on Thursday, November 12, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , , , ,

windsor mvc controller factory

This is the third in a series of posts illustrating building a custom Windsor registration process. Here I want to illustrate test driven development on another Windsor implementation that will fit into the upcoming registration process - a Windsor Controller Factory for ASP.NET MVC.

I start, as always, with my context specification class:
(If unfamiliar with this library, my context specifications series my be of interest)

[Observations] 
public class when_a_known_controller_is_requested_from_the_windsor_controller_factory : 
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>  
{ 
    private static Type controllerType;
    private static IController returnedController; 

    private context c = () => controllerType = typeof (FakeController);

    private because b = () => returnedController = sut.CreateController(null,
                                                                     controllerType.Name); 

    [Observation] 
    public void should_return_an_instance_of_the_controller() 
    { 
        returnedController.should_not_be_null(); 
    } 
 }

Here, in my because "Act" delegate I'm requesting a controller via the IControllerFactory interface method CreateController and asserting that it returns something.
The implementation to make this build is as follows:

public class WindsorControllerFactory : IControllerFactory
{
    private IWindsorContainer container;

    public WindsorControllerFactory(IWindsorContainer container)
    {
        this.container = container;
    }

    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        return null;
    }

    public void ReleaseController(IController controller)
    {
        throw new NotImplementedException();
    }
}

Running the tests it predictably fails, so in true TDD style I add the most basic implementation to make the test pass:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    return new FakeController2();
}

I now improve upon this with a second observation:

[Observation]
public void should_return_the_correct_controller()
{
    returnedController.should_be_an_instance_of<FakeController>();
}

This test fails and I implement enough to pass the test:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    return new FakeController();
}

Moving onto a new specification, I want to ensure it now asks for the controller instance from the Windsor Container instead of providing its own instance as it currently does:

[Observations]
public class when_a_controller_is_requested_from_the_windsor_controller_factory :
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static IWindsorContainer container;
    private static string controllerName;

    private context c = () =>
                            {
                                container = the_dependency<IWindsorContainer>();
                                controllerName = "acontroller";
                            };

    private because b = () => sut.CreateController(null, controllerName);

    [Observation]
    public void should_ask_the_container_to_resolve_the_controller()
    {
        container.was_told_to(c => c.Resolve<IController>(controllerName));
    }
}

To make this test pass, I implement the following:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    container.Resolve<IController>(controllerName);
    return new FakeController();
}

A second observation in this specification will now ensure it uses the correct instance when returning:

[Observations]
public class when_a_controller_is_requested_from_the_windsor_controller_factory :
  observations_for_a_sut_with_a_contract<IControllerFactory, WindsorControllerFactory>
{
    private static IWindsorContainer container;
    private static string controllerName;
    private static IController returnedController;
    private static IController theExpectedController;

    private context c = () =>
                            {
                                container = the_dependency<IWindsorContainer>();
                                controllerName = "acontroller";
                                theExpectedController = an<IController>();

                                container.expect_at_least_once(w => 
                                              w.Resolve<IController>(controllerName))
                                         .IgnoreArguments()
                                         .Return(theExpectedController);
                            };

    private because b = () => returnedController = sut.CreateController(null, controllerName);

    [Observation]
    public void should_ask_the_container_to_resolve_the_controller()
    {
        container.was_told_to(c => c.Resolve<IController>(controllerName));
    }

    [Observation]
    public void should_return_the_controller_obtained_from_the_container()
    {
        returnedController.should_be_equal_to(theExpectedController);
    }
}

Now I am setting up an expectation on my mock of IWindsorContainer and returning a mock controller instance. I then assert that this is the correct one coming back from the method call. This fails, so the implementation then becomes:

public IController CreateController(RequestContext requestContext, string controllerName)
{
    return container.Resolve<IController>(controllerName);
}

This specification now passes, but it breaks the original set of observations as we no longer have the FakeController hard coded and it is not registered in those specifications.

I'll cover revising this in my next post.

Posted at at 7:54 AM on Monday, November 9, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , , , ,

implementing windsor controller registration

Continuing the custom Windsor registration series of posts this second post illustrates implementing the Windsor controller registration that was created in the previous post.
I do this with a simple implementation entry in the global.asax for the time being:

protected void Application_Start() 
{ 
    CreateWindsorContainer(); 
    WindsorControllerRegistration.RegisterControllersFrom(Assembly.GetExecutingAssembly(),
                                                           container); 
    RegisterRoutes(RouteTable.Routes); 
} 

private static void CreateWindsorContainer() 
{ 
    container = new WindsorContainer(); 
}

private IWindsorContainer container; 

The above code uses the static class illustrated in the previous post to register the controllers from the executing assembly but I will look to be improving the readability of this once the framework is in place through future posts.

The next step is to code a new Windsor component - the Windsor MVC Controller Factory and I'll cover this in my next post.

Posted at at 8:30 AM on Thursday, November 5, 2009 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , ,