# Monday, January 04, 2010

In a previous post I described how AutoFixture's Do method can let you invoke commands on your SUT with Dummy values for the parameters you don't care about.

The Get method is the equivalent method you can use when the member you are invoking returns a value. In other words: if you want to call a method on your SUT to get a value, but you don't want the hassle of coming up with values you don't care about, you can let the Get method supply those values for you.

In today's example I will demonstrate a unit test that verifies the behavior of a custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't really matter. The point is that a ModelBinder must implement the IModelBinder interface that defines a single method:

object BindModel(ControllerContext controllerContext,

    ModelBindingContext bindingContext);

In many cases we don't care about one or the other of these parameters, but we still need to supply them when unit testing.

The example is a bit more complex than some of my other sample code, but once in a while I like to provide you with slightly more realistic AutoFixture examples. Still, it's only 10 lines of code, but it looks like a lot more because I have wrapped several of the lines so that the code is still readable on small screens.

[TestMethod]

public void BindModelWillReturnCorrectResult()

{

    // Fixture setup

    var fixture = new Fixture();

    fixture.Customize<ControllerContext>(ob =>

        ob.OmitAutoProperties());

 

    var value = fixture.CreateAnonymous("Value");

    var bindingContext = new ModelBindingContext();

    bindingContext.ValueProvider =

        new Dictionary<string, ValueProviderResult>();

    bindingContext.ValueProvider["MyValue"] =

        new ValueProviderResult(value, value,

            CultureInfo.CurrentCulture);

 

    var expectedResult =

        new string(value.Reverse().ToArray());

    var sut = fixture.CreateAnonymous<MyModelBinder>();

    // Exercise system

    var result = fixture.Get((ControllerContext cc) =>

        sut.BindModel(cc, bindingContext));

    // Verify outcome

    Assert.AreEqual(expectedResult, result, "BindModel");

    // Teardown

}

The first part simply creates the Fixture object and customizes it to disable AutoProperties for all ControllerContext instances (otherwise we would have to set up a lot of Test Doubles for such properties as HttpContext, RequestContext etc.).

The next part of the test sets up a ModelBindingContext instance that will be used to exercise the SUT. In this test case, the bindingContext parameter of the BindModel method is important, so I explicitly set that up. On the other hand, I don't care about the controllerContext parameter in this test case, so I ask the Get method to take care of that for me:

var result = fixture.Get((ControllerContext cc) =>

    sut.BindModel(cc, bindingContext));

The Get method creates a Dummy value for the ControllerContext, whereas I can still use the outer variable bindingContext to call the BindModel method. The return value of the BindModel method is returned to the result variable by the Get method.

Like the Do methods, the Get methods are generic methods. The one invoked in this example has this signature:

public TResult Get<T, TResult>(Func<T, TResult> function);

There are also overloads that works with the versions of the Func delegate that takes two, three and four parameters.

As the Do methods, the Get methods are convenience methods that let you concentrate on writing the test code you care about while it takes care of all the rest. You could have written a slightly more complex version that didn't use Get but instead used the CreateAnonymous method to create an Anonymous Variable for the ControllerContext, but this way is slightly more succinct.

posted on Monday, January 04, 2010 9:53:24 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, December 14, 2009

In my previous posts I discussed how to enable global error handling in ASP.NET MVC and how to inject a logging interface into the error handler. In these posts, I simplified things a bit to get my points across.

In production we don't use a custom ErrorHandlingControllerFactory to configure all Controllers with error handling, nor do we instantiate IExceptionFilters manually. What I described was the Poor Man's Dependency Injection (DI) approach, which I find most appropriate when describing DI concepts.

However, we really use Castle Windsor currently, so the wiring looks a bit different although it's still exactly the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter are any different than I have already described, but for completeness I wanted to share a bit of our Windsor code.

This is how we really wire our Controllers:

container.Register(AllTypes
    .FromAssemblyContaining(representativeControllerType)
    .BasedOn<Controller>()
    .ConfigureFor<Controller>(reg => 
        reg.LifeStyle.PerWebRequest.ServiceOverrides(
            new { ActionInvoker = typeof(
                ErrorHandlingControllerActionInvoker)
                .FullName })));

Most of this statement simply instructs Windsor to scan all types in the specified assembly for Controller implementations and register them. The interesting part is the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining that the ActionInvoker property should be wired up with an instance of the component registered as ErrorHandlingControllerActionInvoker.

Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance we need to configure at least one of these as well. Instead of one, however, we have two:

container.Register(Component.For<IExceptionFilter>()
    .ImplementedBy<LoggingExceptionFilter>());
container.Register(Component.For<IExceptionFilter>()
    .ImplementedBy<HandleErrorAttribute>());

This is Windsor's elegant way of registering Decorators: you simply register the Decorator before the decorated type, and it'll Auto-Wire everything for you.

Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from the MVC Contrib project.

To reiterate: You don't have to use Castle Windsor to enable global error handling or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous posts, or you can use some other DI Container. The purpose of this post was simply to demonstrate one way to take it to the next level.

posted on Monday, December 14, 2009 7:59:32 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, December 07, 2009

In a previous post I described how to enable global error handling in ASP.NET MVC applications. Although I spent some time talking about the importance of DRY, another major motivation for me was to enable Dependency Injection (DI) with exception handling so that I could log stack traces before letting ASP.NET MVC handle the exception.

With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter implementation. As an example I used HandleErrorAttribute, but obviously that doesn't log anything. Once again, it would be tempting to derive from HandleErrorAttribute and override its OnException method, but staying true to the Single Responsibility Principle as well as the Open/Closed Principle I rather prefer a Decorator:

public class LoggingExceptionFilter : IExceptionFilter
{
    private readonly IExceptionFilter filter;
    private readonly ILogWriter logWriter;
 
    public LoggingExceptionFilter(IExceptionFilter filter,
        ILogWriter logWriter)
    {
        if (filter == null)
        {
            throw new ArgumentNullException("filter");
        }
        if (logWriter == null)
        {
            throw new ArgumentNullException("logWriter");
        }        
 
        this.filter = filter;
        this.logWriter = logWriter;
    }
 
    #region IExceptionFilter Members
 
    public void OnException(ExceptionContext filterContext)
    {
        this.logWriter.WriteError(filterContext.Exception);
        this.filter.OnException(filterContext);
    }
 
    #endregion
}

The LoggingExceptionFilter shown above is unabridged production code. This is all it takes to bridge the gap between IExceptionFilter and some ILogWriter interface (replace with the logging framework of your choice). Notice how it simply logs the error and then passes on exception handling to the decorated IExceptionFilter.

Currently we use HandleErrorAttribute as the decorated filter so that behavior stays as expected.

c.ActionInvoker = 
    new ErrorHandlingControllerActionInvoker(
        new LoggingExceptionFilter(
            new HandleErrorAttribute(), logWriter));

This is not too different from before, except that a LoggingExceptionFilter now decorates the HandleErrorAttribute instance.

posted on Monday, December 07, 2009 7:20:27 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, December 01, 2009

ASP.NET MVC comes with an error-handling feature that enables you to show nice error Views to your users instead of the dreaded Yellow Screen of Death. The most prominently described technique involves attributing either you Controller or a single Controller action, like we see in the AccountController created by the Visual Studio project template.

[HandleError]

public class AccountController : Controller { }

That sure is easy, but I don't like it for a number of reasons:

  • Even though you can derive from HandleErrorAttribute, it's impossible to inject any dependencies into Attributes because they must be fully constructed at compile-time. That makes it really difficult to log errors to an interface.
  • It violates the DRY principle. Although it can be applied at the Controller level, I still must remember to attribute all of my Controllers with the HandleErrorAttribute.

Another approach is to override Controller.OnException. That solves the DI problem, but not the DRY problem.

Attentive readers may now point out that I can define a base Controller that implements the proper error handling, and require that all my Controllers derive from this base Controller, but that doesn't satisfy me:

First of all, it still violates the DRY principle. Whether I have to remember to apply a [HandleError] attribute or derive from a : MyBaseController amounts to the same thing. I (and all my team members) have to remember this always. It's unnecessary project friction.

The second thing that bugs me about this approach is that I really do favor composition over inheritance. Error handling is a cross-cutting concern, so why should all my Controllers have to derive from a base controller to enable this? That is absurd.

Fortunately, ASP.NET MVC offers a third way.

The key lies in the Controller base class and how it deals with IExceptionFilters (which HandleErrorAttribute implements). When a Controller action is invoked, this actually happens through an IActionInvoker. The default ControllerActionInvoker is responsible for gathering the list of IExceptionFilters, so the first thing we can do is to derive from that and override its GetFilters method:

public class ErrorHandlingActionInvoker :

    ControllerActionInvoker

{

    private readonly IExceptionFilter filter;

 

    public ErrorHandlingActionInvoker(

        IExceptionFilter filter)

    {

        if (filter == null)

        {

            throw new ArgumentNullException("filter");

        }

 

        this.filter = filter;

    }

 

    protected override FilterInfo GetFilters(

        ControllerContext controllerContext,

        ActionDescriptor actionDescriptor)

    {

        var filterInfo =

            base.GetFilters(controllerContext,

            actionDescriptor);

        filterInfo.ExceptionFilters.Add(this.filter);

        return filterInfo;

    }

}

Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not tightly binding it to any particular implementation – it will work with any IExceptionFilter we give it, so it simply serves the purpose of adding the filter at the right stage so that it can deal with otherwise unhandled exceptions. It's pure infrastructure code.

Notice that I first invoke base.GetFilters and then add the injected filter to the returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to attempt to deal with the error first.

This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every Controller in the application. This can be done using a custom ControllerFactory:

public class ErrorHandlingControllerFactory :

    DefaultControllerFactory

{

    public override IController CreateController(

        RequestContext requestContext,

        string controllerName)

    {

        var controller =

            base.CreateController(requestContext,

            controllerName);

 

        var c = controller as Controller;

        if (c != null)

        {

            c.ActionInvoker =

                new ErrorHandlingActionInvoker(

                    new HandleErrorAttribute());

        }

 

        return controller;

    }

}

Notice that I'm simply deriving from the DefaultControllerFactory and overriding the CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.

In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker instance. This seems weird, but it's the HandleErrorAttribute that implements the default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter, it works like a charm.

The only thing left to do is to wire up the custom ErrorHandlingControllerFactory in global.asax like this:

ControllerBuilder.Current.SetControllerFactory(

    new ErrorHandlingControllerFactory());

Now any Controller action that throws an exception is gracefully handled by the injected IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters, any normal [HandleError] attribute and Controller.OnException override gets a chance to deal with the exception first, so this doesn't even change behavior of existing code.

If you are trying this out on your own development machine, remember that you must modify your web.config like so:

<customErrors mode="On" />

If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on your local box.

posted on Tuesday, December 01, 2009 7:37:01 AM (Romance Standard Time, UTC+01:00)  #    Comments [3] Trackback
# Tuesday, November 17, 2009

When using Castle Windsor in web applications you would want to register many of your components with a lifestyle that is associated with a single request. This is the purpose of the PerWebRequest lifestyle.

If you try that with ASP.NET MVC on IIS7, you are likely to receive the following error message:

Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
Add '<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />' to the <httpModules> section on your web.config.

Unfortunately, following the instructions in the error message doesn't help. There's a discussion about this issue on the Castle Project Users forum, but the gist of it is that if you don't need to resolve components during application startup, this shouldn't be an issue, and indeed it isn't – it seems to be something else.

In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules instead of configuration/system.web/httpModules.

Although I haven't had the opportunity to dive into the technical details to understand why this works, this seems to solve the problem on both Windows Vista and Windows Server 2008.

posted on Tuesday, November 17, 2009 1:44:37 PM (Romance Standard Time, UTC+01:00)  #    Comments [2] Trackback
# Monday, September 07, 2009

How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel and I recently had that problem and we couldn't find any guidance on this topic, so now that we have a solution, I thought I'd share it.

The problem is simple: We needed a link that invoked some server side code and updated the text of the link itself based on the result of the operation. Here is a simplified example:

image

Each time you click the link, it should invoke a Controller Action and return a new number that should appear as the link text.

This is pretty simple to implement once you know how. The first thing to realize is that the link and all the AJAX stuff must be placed in a user control. The only thing that needs to go into the containing page is the containing element itself:

<h2>Self-updating AJAX link</h2>
Click the link to update the number:
<span id="thespan">
    <% this.Html.RenderPartial("NumberAjaxUserControl"); %>
</span>

Notice the id of the span element – this same id will be referenced from the user control.

To bootstrap this view, the Controller Action for the page contains code that assigns an initial value to the number (in this case 1):

public ActionResult Index()
{
    this.ViewData["number"] = 1.ToString();
    return this.View();
}

To keep the example simple, I simply add the number to the ViewData dictionary, but in any production implementation, I would opt to use a strongly typed ViewModel instead.

The NumberAjaxUserControl itself only contains the definition of the AJAX link:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Ajax" %>
<%= this.Ajax.ActionLink((string)this.ViewData["number"],
    "GetNext",
    new { number = this.ViewData["number"] }, 
    new AjaxOptions { UpdateTargetId = "thespan" })%>

The first parameter to the ActionLink method is simply the current number to render as the link text. Since I'm using the untyped ViewData dictionary for this example, I need to cast it to a string.

The next parameter ("GetNext") indicates the Controller Action to invoke when the link is clicked – I will cover that shortly.

The third parameter is a Route Value that specifies that the parameter number with the correct value will be supplied to the GetNext Controller Action. It uses the number stored in ViewData.

The last parameter indicates the id of the element to update. Recall from before that this name was "thespan".

The only missing piece now is the GetNext Controller Action:

public PartialViewResult GetNext(int number)
{
    this.ViewData["number"] = (number + 1).ToString();
    return this.PartialView("NumberAjaxUserControl");
}

In this example I simply chose to increment the number by one, but I'm sure you can imagine that this method could just as well perform a database lookup or something similar.

Notice that the method returns a PartialViewResult that uses the same user control that I used to bootstrap the thespan element. This means that every time the link is clicked, the GetNext method is updated, and the exact same user control is used to render the content that dynamically replaces the original content of the element.

posted on Monday, September 07, 2009 8:14:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Thursday, July 16, 2009

The expressiveness of WPF is amazing. I particularly like the databinding and templating features. The ability to selectively render an object based on its type is very strong.

When I recently began working with ASP.NET MVC (which I like so far), I quickly ran into a scenario where I would have liked to have WPF's DataTemplates at my disposal. Maybe it's just because I've become used to WPF, but I missed the feature and set out to find out if something similar is possible in ASP.NET MVC.

Before we dive into that, I'd like to present the 'problem' in WPF terms, but the underlying View Model that I want to expose will be shared between both solutions.

PresentationModel

The main point is that the Items property exposes a polymorphic list. While all items in this list share a common property (Name), they are otherwise different; one contains a piece of Text, one contains a Color, and one is a complex item that contains child items.

When I render this list, I want each item to render according to its type.

In WPF, this is fairly easy to accomplish with DataTemplates:

<ListBox.Resources>
    <DataTemplate DataType="{x:Type pm:NamedTextItem}">
        <StackPanel>
            <TextBlock Text="{Binding Path=Name}"
                       FontWeight="bold" />
            <TextBlock Text="{Binding Path=Text}" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate DataType="{x:Type pm:NamedColorItem}">
        <StackPanel>
            <TextBlock Text="{Binding Path=Name}"
                       FontWeight="bold" />
            <Ellipse Height="25" Width="25"
                     HorizontalAlignment="Left"
                     Fill="{Binding Path=Brush}"
                     Stroke="DarkGray" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate DataType="{x:Type pm:NamedComplexItem}">
        <StackPanel>
            <TextBlock Text="{Binding Path=Name}"
                       FontWeight="bold" />
            <ListBox ItemsSource="{Binding Path=Children}"
                     BorderThickness="0">
                <ListBox.Resources>
                    <DataTemplate
                        DataType="{x:Type pm:ChildItem}">
                        <TextBlock
                            Text="{Binding Path=Text}" />
                    </DataTemplate>
                </ListBox.Resources>
            </ListBox>
        </StackPanel>
    </DataTemplate>
</ListBox.Resources>

Each DataTemplate is contained within a ListBox. When the ListBox binds to each item in the Items list, it automatically picks the correct template for the item.

The result is something like this:

WpfApp

The NamedTextItem is rendered as a box containing the Name and the Text on two separate lines; the NamedColorItem is rendered as a box containing the Name and a circle filled with the Color defined by the item; and the NamedComplexItem is rendered as a box with the Name and each child of the Children list.

This is all implemented declaratively without a single line of imperative UI code.

Is it possible to do the same in ASP.NET MVC?

To my knowledge (but please correct me if I'm wrong), ASP.NET MVC has no explicit concept of a DataTemplate, so we will have to mimic it. The following describes the best I've been able to come up with so far.

In ASP.NET MVC, there's no declarative databinding, so we will need to loop through the list of items. My View page derives from ViewPage<MyViewModel>, so I can write

<% foreach (var item in this.Model.Items)
   { %>
   <div class="ploeh">
   <% // Render each item %>
   </div>
<% } %>

The challenge is to figure out how to render each item according to its own template.

To define the templates, I create a UserControl for each item. The NamedTextItemUserControl derives from ViewUserControl<NamedTextItem>, which gives me a strongly typed Model:

<div><strong><%= this.Model.Name %></strong></div>
<div><%= this.Model.Text %></div>

The other two UserControls are implemented similarly.

A UserControl can be rendered using the RenderPartial extension method, so the only thing left is to select the correct UserControl name for each item. It would be nice to be able to do this in markup, like WPF, but I'm not aware of any way that is possible.

I will have to resort to code, but we can at least strive for code that is as declarative in style as possible.

First, I need to define the map from type to UserControl:

<%
    var dataTemplates = new Dictionary<Type, string>();
    dataTemplates[typeof(NamedTextItem)] =
        "NamedTextItemUserControl";
    dataTemplates[typeof(NamedColorItem)] =
        "NamedColorItemUserControl";
    dataTemplates[typeof(NamedComplexItem)] =
        "NamedComplexItemUserControl";
%>

Next, I can use this map to render each item correctly:

<% foreach (var item in this.Model.Items)
   { %>
   <div class="ploeh">
   <% // Render each item %>
   <% this.Html.RenderPartial(dataTemplates[item.GetType()],
                            item); %>
   </div>
<% } %>

This is definitely less pretty than with WPF, but if you overlook the aesthetics and focus on the structure of the code, it's darn close to markup. The Cyclomatic Complexity of the page is only 2, and that's even because of the foreach statement that we need in any case.

The resulting page looks like this:

AspNetMvcApp

My HTML skills aren't good enough to draw circles with markup, so I had to replace them with blocks, but apart from that, the result is pretty much the same.

A potential improvement on this technique could be to embed the knowledge of the UserControl into each item. ASP.NET MVC Controllers already know of Views in an abstract sense, so letting the View Model know about a UserControl (identified as a string) may be conceptually sound.

The advantage would be that we could get rid of the Dictionary in the ViewPage and instead let the item itself tell us the name of the UserControl that should be used to render it.

The disadvantage would be that we lose some flexibility. It would then require a recompilation of the application if we wanted to render an item using a different UserControl.

The technique outlined here represents an explorative work in progress, so comments are welcome.

posted on Thursday, July 16, 2009 9:33:48 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback