On myself and FluentMVCTesting joining TestStack

I’d like to announce that I’m joining TestStack and my FluentMCVTesting library will become a TestStack library.

What is TestStack?

I think it can be summed up nicely by a post from one of the core TestStack team, Michael Whelan, in the blog post he wrote. tl;dr: TestStack is a collection of open source projects which mainly focus on making the left side of Marrick’s Agile Testing Quadrant easier!

Why am I joining TestStack?

I think that the libraries in TestStack are awesome and the core team are a group of people I trust and respect. It’s a pleasure to be invited into the core team and I think it’s really great for the FluentMVCTesting library to be present alongside the other awesome testing libraries.

What will happen to FluentMVCTesting?

The nuget package and namespace is changing to have a TestStack prefix for consistency with other TestStack libraries, but other than that nothing much – the library is the same library, but it’s more likely to have additions made to it and hopefully more people using it.

If you update the existing FluentMVCTesting package then it will include the new package as a dependency and wrap around the new classes, but mark the old classes as deprecated. This should provide a smooth transition to existing users of the package as well as letting them know there is a new package out there.

I’m also dropping the strong signing support for now to keep consistency with the other TestStack libraries. We will add that in due course to all the libraries if we feel there is enough demand for it.

Announcing ChameleonForms 0.1

One of the things I find frustrating with ASP.NET MVC out of the box is creating forms. That’s not to say I find it more frustrating than other frameworks or libraries though; on the contrary I think it’s painful almost always. I think ASP.NET MVC has an amazingly powerful and useful capacity to handle forms. However, out of the box I find it fiddly and annoying to output the HTML associated with the form in a consistent and maintainable way across a whole website.

The other problem occurs when you want to change the layout of the form. For instance, imagine I create a proof-of-concept application using Twitter Bootstrap to get up and running with something that looks nice quickly. I may well want to scrap the application because it turns out to not be popular or useful. On the other hand, if it became really popular then I might want to spend some more time and effort customising the look-and-feel. At that point I will more than likely want to move away from the HTML template that Twitter Bootstrap imposes on you to use a more semantic markup (e.g. definition lists).

Enter Chameleon Forms

For the last 2 years, while I was working at Curtin University I was lucky enough to be able to use a library that we developed for tersely and maintainably developing forms that conformed to the forms standard that we had at Curtin. We had the advantage that the library was able to be specific to the Curtin standard for forms and didn’t have to be very generic. We still ensured that the library was very flexible though, because we want to make sure we could use it for most of the use cases we came across and still be able to break out into straight HTML for the weird edge cases.

ChameleonForms is my attempt to use the learnings and concepts from the previous forms library I was using and apply them to a new, open source library that I can use on my personal and professional projects to ease the pain of creating forms and improve the maintainability of them.

I am implementing this library alongside Matt Davies, who I often work closely with.

This blog post is announcing the initial release of this library, which contains basic functionality only. There is more information about the library, an example of how to use it and the roadmap we have for it at the Github page.

If you want to install this initial version from NuGet then simply use:

Install-Package ChameleonForms

Enjoy!

Type-safe ViewBag use to pass generic view data to views / layouts

It seems there are a number of different approaches to passing data (that doesn’t make sense to put into the view model) to the view in ASP.NET MVC:

My preferred approach

I think that using the ViewBag is great because syntactically it’s much terser than ViewData and once you have used it once on a page then you will get intellisense for it. Personally, I think that having a base view model class that you use across your whole site is probably asking for trouble and from a separation of concerns point of view is just plain bad practice.

That’s one of the reasons why the ViewBag or even ViewData is good – they are completely separate from the view model so for data that it semantically doesn’t make sense to in include the view model of the page it’s the best place to put it.

I will say this with a disclaimer though, I think it’s important to minimise the amount of data you do pass in this way because otherwise you will get crazy spaghetti code that is hard to test and maintain. I will usually restrict using these data structures to data that I want to pass through to the base site layout. Things like the object representing the currently logged in user (e.g. their name, email address etc.) or a list of JavaScript and / or CSS files that should be included for the current page. Wherever it’s possible and it makes sense to put data in the strongly typed view model I think this is the best approach.

What I don’t like about ViewBag

The topic of using dynamics in C# is a pretty heated topic and there is much debate on either side. I think as always a pragmatic approach is required, but where possible I do prefer to avoid dynamics because they aren’t compile safe. While some people love to argue that it doesn’t matter and that the compiler is the first in a series of checks that you will perform, coming from an embedded background (I studied Embedded Software Engineering at University), I can’t help but appreciate and respect type-safety (let alone intellisense, which makes code easier to read/write and thus maintain!) ūüôā

Type-safe / intellisensed ViewBag access in views

In the interest of providing some consistency and assurance about using the ViewBag there is a technique I have been using for a while now to expose the getting (and setting if from views) of ViewBag properties by wrapping them in properties within the base page class.

In order to do this I simply extend the default base page class (WebViewPage<T>) and add relevant properties. I will usually locate this class directly in the Views folder (it semantically makes sense to me). An example implementation might be:

namespace MyWebApp.Views
{
    public abstract class BasePage<T> : WebViewPage<T>
    {
        public User CurrentUser { get { return (User) ViewBag.CurrentUser; } }
        public string Title { get { return (string) ViewBag.Title; } set { ViewBag.Title = value; } }
        public bool HideMenu { get { return (bool)(ViewBag.HideMenu ?? false); } set { ViewBag.HideMenu = value; } }
    }

    public abstract class BasePage : BasePage<dynamic> {}
}

There are a few things to note here:

  • The classes are abstract because they shouldn’t be instantiated directly, but rather extended by the Razor engine when compiling each page – more info.
  • I provide a non-generic class (BasePage) as well as the generic one (the generic type being the view model type) because otherwise the intellisense in the web.config (see below) file complains. I used to think this was for views that don’t specify an @model type, but I just tried it and it worked without that class there.
  • The properties that I want the views to set values for have setters – this ensures that views can only set the correct type of value into the given ViewBag property (making the assumption you use this in preference to direct ViewBag calls in views from now on!).
  • There is a property that I expect to be injected into ViewBag by the controller or a filter so it only has a getter.

Once you have done this then setting / accessing the properties in the view becomes dead simple (and terser than using ViewBag!) as well as giving you wonderful intellisense:

@{
    Title = "My Page Title";
    HideMenu = true;
}
<h1>My page</h1>
@if (CurrentUser == null)
{
    <p>You aren't logged in</p>
}
else
{
    <p>@CurrentUser.FirstName is your first name!</p>
}

There is one thing I’ve missed out, which is to get Razor to compile using this new base page and to get intellisense working you have to either:

  • Use @inherits on every page – ugh; or
  • Change the pageBaseType attribute in the pages element in the system.web.webPages.razor element in the web.config file in the Views directory to be the class you’ve created e.g.¬†<pages pageBaseType=”MyWebApp.Views.BasePage”> (also, feel free to add any common namespaces that you use across your views to the namespaces element and that way you don’t have to put in an @using statement for those namespaces in the views any more!)

Injecting information from the controller

One thing that I’ve noticed some people do with this technique is to return something from DependencyResolver in the properties or use property injection from their dependency injection framework. While I’m all for unobtrusively setting these properties where possible (e.g. say you have an enumeration with the current environment (test / prod etc.) so you can do simple feature toggles in your views), it strikes me that it’s probably not a good idea because it will encourage business logic to be called from within views (e.g. if you decided it would be easier to inject a database repository in one of the properties). I think it’s way more testable and consistent to have any properties that are set outside of the views to be set from either:

  • The controller – for instance you might have a base controller (if you rely on the base controller being used across the site it might be worth adding tests to check that this is the case [see Other Applications at the bottom of that post])
  • A global filter

Grouping ViewBag access together

One of the really nice side-effects of this approach (of abstracting ViewBag access to the base page) is that your ViewBag access is now grouped together in the same file so it’s easy to see at a glance how you are using it. This means you are less likely to let the ViewBag use explode out of control!

Other applications of a custom base page

The custom base page is a really nice abstraction and opens up a lot of interesting possibilities. One example that I have used it for is to include page-specific CSS and JavaScript files into the <head> of the document by specifying them within each page using functions on the base page. These functions set the JavaScript and CSS files into the ViewBag and then the layout simply uses these when outputting the HTML in <head>. Razor seems to execute the view before the layout hence why this works!

        protected void AddScript(string script)
        {
            var localPath = new Regex(@"^w");
            if (localPath.Match(script).Success)
            {
                script = "~/Scripts/" + script;
                if (!script.EndsWith(".js"))
                {
                    script += ".js";
                }
            }

            if (ViewBag.Scripts == null)
            {
                ViewBag.Scripts = new List<string>();
            }

            ViewBag.Scripts.Add(script);
        }

        public void AddStylesheet(string cssFile)
        {
            var localPath = new Regex(@"^w");
            if (localPath.Match(cssFile).Success)
            {
                cssFile = "~/Content/Css/" + cssFile;
                if (!cssFile.EndsWith(".css"))
                {
                    cssFile += ".css";
                }
            }

            if (ViewBag.Stylesheets == null)
            {
                ViewBag.Stylesheets = new List<string>();
            }

            ViewBag.Stylesheets.Add(cssFile);
        }

A note about the current user property in the base page

I illustrated some code above that exposed the current user to the views. To populate this value you probably need a database call and if you are in the situation where you don’t need to use the CurrentUser property on every page it makes sense to lazy load the value so you don’t take an unnecessary hit to the database on every request. One approach I’ve used in the past to combat this is to expose CurrentUser in the ViewBag as a functor rather than a straight object value, e.g.:

    public abstract class BaseController : Controller
    {
        private readonly IUserRepository _userRepository;
        private User _currentUser;

        public User CurrentUser
        {
            get { return _currentUser ?? (_currentUser = GetCurrentUser()); }
        }

        protected BaseController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
            Func<User> userGetter = () => CurrentUser;
            ViewBag.CurrentUser = userGetter;
        }

        private User GetCurrentUser()
        {
            return ControllerContext.HttpContext.User.Identity.IsAuthenticated
               ? _userRepository.Get(HttpContext.User.Identity.Name)
               : null;
        }
    }
...

    public abstract class BasePage<T> : WebViewPage<T>
    {
        protected User CurrentUser
        {
            get
            {
                return ViewBag.CurrentUser != null ? ViewBag.CurrentUser() : null;
            }
        }
    }

Controller instantiation testing

As I just mentioned in my post on Robust testing the best kind of test is one that automatically updates when you change your code. In particular when that test provides you a lot of value and checks something that would otherwise have a likelihood of going wrong when you deploy it (in particular production!). This post gives an example of this kind of test.

The problem

One thing that I’ve come across a number of times is a situation where controllers aren’t able to be instantiated because one of the constructor parameters isn’t able to be resolved from the dependency injection container. This is a pain and causes an ugly yellow screen of death to show up for requests to the affected controller(s) (or a nice error page if the environment you deploy to has that set up).

Ideally you should check the pages that a controller serves up after adding new parameters to it’s constructor before pushing your code changes, but sometimes you might forget and your development environment will break (I’m making a few assumptions here: continuous integration and continuous deployment to a dev environment after your tests pass). While it’s both quick and easy to identify and resolve this problem it’s annoying and can be disruptive to any testing on that environment. Ideally, the problem should be picked up much sooner than after the deployment.

Also, you may make some sort of changes that have unintended consequences like, say, changing the namespace of some classes that are registered by namespace to your dependency injection container.

In these situations, it’s impossible to use the compiler to check that the dependency resolution will work because they are resolved at run time. However, we can do the next best thing and write a test that will break!

An example solution for ASP.NET MVC

Consider the following code (this example in NUnit, but the same concept applies for other libraries):

namespace MyApp.Tests.Controllers
{
    [TestFixture]
    class ControllersShould
    {
        private IContainer _container;

        [TestFixtureSetUp]
        public void FixtureSetup()
        {
            _container = MvcApplication.RegisterDependencies();
        }

        // ReSharper disable UnusedMember.Global
        public IEnumerable<Type> GetAllControllers()
        {
            return typeof(MvcApplication).Assembly.GetTypes().Where(t => t.IsAssignableTo<ControllerBase>() && !t.IsAbstract);
        }
        // ReSharper restore UnusedMember.Global

        [Test]
        [TestCaseSource("GetAllControllers")]
        public void Instantiate(Type controller)
        {
            _container.Resolve(controller);
        }
    }
}

This test uses the (really handy) [TestCaseSource] attribute so each controller that is instantiated is presented as a separate test. This makes sense semantically and allows you to see all of the controllers that can’t be instantiated, rather than it¬†short-circuiting¬†at the first one that doesn’t. In saying that, if your unit testing library doesn’t support that kind of testing metadata then the same thing can be implemented as a loop inside the test.

The real magic here is in the GetAllControllers() method, which uses reflection to scan the assembly of the web application to find all classes that extend ControllerBase. You could use Controller too, but if for example you are using ActionMailer.Net then your mail controller will inherit from MailerBase, which extends ControllerBase. It also ensures the classes returned aren’t abstract.

Once you have this list of types, resolving each of them with the dependency injection container (in my case Autofac, but as with the unit testing library, this technique applies generically) you are using is easy. The only requirement is you make the method with all of your dependency registrations public and static so it’s available to call within the test. I usually have a method called RegisterDependencies() on the application class (unless the dependencies are shared with non-web projects too).

The beautiful thing about this test is that as soon as you add new controllers it will automatically apply the test to that controller! So you can literally write the test once and then forget about it :).

Note: there are a few implications of this technique that you should consider before using it:

  • This will call the constructor of all your controllers; if any of them are doing anything “funky” in their constructors then this might not be desirable. Personally, all my controller constructors ever have are storing the dependencies in the private instance scope.
  • More importantly, all of the dependencies that the controllers have and indeed all the dependencies down the chain will have their constructors called as well. This might well be a problem for your application depending on what it does so you should be very conscious of this. This usually involves me needing to set certain connection strings in the App.config of the test to test datasources etc. so the constructors don’t throw exceptions.
  • All of the dependencies to the controllers need to be such that your dependency container, with all the registrations made in your RegisterDependencies() (or similar) method, can resolve them. If you have any custom controller registration code outside of what your dependency injection framework provides you might need to adjust the approach above accordingly.
  • This is (at least in the way it’s written above, it could be adjusted though) an all-or-nothing approach – it will resolve all of the controllers.
  • If your controllers are in multiple assemblies then the GetAllControllers() method will need to be adjusted to scan the other assemblies.

Other applications

There is another application of this particular style of test that I have used before and is worth mentioning. If you are in a situation where most (or all) of your controllers must inherit from a base controller that contains important/shared functionality for your website then there is no way for you to use the compiler to check that the classes inherit that base controller. You will only find out if a new controller has that inheritance missing when loading up the site and even then, depending on the nature of the functionality, maybe only in certain circumstances (so it mightn’t be immediately obvious). As before, you can write a test that will automatically check this for you as soon as you add any new controllers.

Following is an example of such a test that I have used before:

        // ReSharper disable UnusedMember.Global
        public IEnumerable<Type> GetAllHttpControllers()
        {
            return typeof(MvcApplication).Assembly.GetTypes().Where(t => t.IsAssignableTo<Controller>() && !t.IsAbstract && t != typeof(ErrorController));
        }
        // ReSharper restore UnusedMember.Global

        [Test]
        [TestCaseSource("GetAllHttpControllers")]
        public void Inherit_from_base_controller(Type controller)
        {
            Assert.That(controller.IsAssignableTo<BaseController>());
        }

In this case the base controller class is called BaseController. There are a couple of differences to note here: I am checking for controllers that inherit from Controller rather than ControllerBase because I only want the controllers that are serving HTTP requests and I actually have an exclusion here for one particular controller, the ErrorController, because I didn’t want that particular one to extend BaseController.

FluentMVCTesting: Fluent, terse and maintainable ASP.NET MVC controller testing

I would like to announce the release of a software library I have been using for the last year or so as open source via NuGet / Github: FluentMVCTesting.

The motivation behind this library is to provide a way to test MVC actions quickly, tersely and maintainably. Most examples I find on MVC controller testing are incredibly verbose, repetitive and time-consuming to write and maintain.

Given how quickly you can write controller actions and how simple they are (assuming you are following best practices and keeping them lean) the time to test them generally isn’t worth it given you can glance at most of your controller actions and know they are right or wrong instantly.

This library aims to make the time to implement the tests inconsequential and then the value your tests are providing is worth it.

The other problem that I’ve noticed with most examples of controller testing is that there are a lot of magic strings being used to test view and action names; this library also aims to (where possible) utilise the type system to resolve a lot of those magic strings, thus ensuring your tests are more maintainable and require less re-work when you perform major refactoring of your code.

I came up with this library after using the MVCContrib.TestHelper library for quite a while, but becoming frustrated with it; the library was initially created during the experiment I conducted to try and create terse controller tests (which I still have to write a follow-up post for at some point!). I have been using the library for over a year on a number of projects both personally and professionally.

A small code snippet to whet your appetite (go to the NuGet site for more detailed documentation and examples):

// Check that a post to the Login action with model errors returns the Login view passing through the model
var vm = new LoginViewModel();
_controller.WithModelErrors().WithCallTo(c => c.Login(vm)).ShouldRenderDefaultView().WithModel(vm);

// Check that a post to the Login action without model errors redirects to the site homepage
_controller.WithCallTo(c => c.Login(new LoginViewModel())).ShouldRedirectTo<HomeController>(c => c.Index());

Enjoy!

Testing Url Helper within controllers in ASP.NET MVC

I recently had some code like the following in a controller that I wanted to test. The Facebook Connect API, despite being fairly awesome, is tied to the URL of the page so whenever you change the URL of your page then you will lose all your comments. This code was to get the initial URL of the page and store it in the database so that URL was used from then on:

var url = ControllerContext.RequestContext.HttpContext.Request.Url;
vm.FacebookCommentUrl = string.Format("https://{0}{1}", url.Authority, Url.Action("Detail", new { Id = "000", Controller = ArticleType.ToString() })).Replace("000", "{0}");

It’s easy to mock Request.Url within the ControllerContext; something like MVCContrib.TestHelper will mock it out for you with a few lines of code. Personally, I use the following code in conjunction with the AutoMock library to do it:

    public static class AutoMockContainer
    {
        public static AutoMock Create()
        {
            var autoMock = new AutoMock();

            var httpContext = Substitute.For<HttpContextBase>();
            autoMock.Provide(httpContext);

            var server = Substitute.For<HttpServerUtilityBase>();
            httpContext.Server.Returns(server);

            var request = Substitute.For<HttpRequestBase>();
            var parameters = new NameValueCollection();
            request.Params.Returns(parameters);
            var formParameters = new NameValueCollection();
            request.Form.Returns(formParameters);
            var qsParameters = new NameValueCollection();
            request.QueryString.Returns(qsParameters);
            var headers = new NameValueCollection();
            headers.Add("Host", "localhost");
            request.Headers.Returns(headers);
            request.AppRelativeCurrentExecutionFilePath.Returns("~/");
            request.ApplicationPath.Returns("/");
            request.Url.Returns(new Uri("http://localhost/"));
            request.Cookies.Returns(new HttpCookieCollection());
            request.ServerVariables.Returns(new NameValueCollection());
            autoMock.Provide(request);
            httpContext.Request.Returns(request);

            var response = Substitute.For<HttpResponseBase>();
            response.Cookies.Returns(new HttpCookieCollection());
            response.ApplyAppPathModifier(Arg.Any<string>()).Returns(a => a.Arg<string>());
            autoMock.Provide(response);
            httpContext.Response.Returns(response);

            var routeData = new RouteData();

            var requestContext = Substitute.For<RequestContext>();
            requestContext.RouteData = routeData;
            requestContext.HttpContext = httpContext;
            autoMock.Provide(requestContext);

            var actionExecutingContext = Substitute.For<ActionExecutingContext>();
            actionExecutingContext.HttpContext.Returns(httpContext);
            actionExecutingContext.RouteData.Returns(routeData);
            actionExecutingContext.RequestContext = requestContext;
            autoMock.Provide(actionExecutingContext);

            var actionExecutedContext = Substitute.For<ActionExecutedContext>();
            actionExecutedContext.HttpContext.Returns(httpContext);
            actionExecutedContext.RouteData.Returns(routeData);
            actionExecutedContext.RequestContext = requestContext;
            autoMock.Provide(actionExecutedContext);

            var controller = Substitute.For<ControllerBase>();
            autoMock.Provide(controller);
            actionExecutingContext.Controller.Returns(controller);

            var controllerContext = Substitute.For<ControllerContext>();
            controllerContext.HttpContext = httpContext;
            controllerContext.RouteData = routeData;
            controllerContext.RequestContext = requestContext;
            controllerContext.Controller = controller;
            autoMock.Provide(controllerContext);
            controller.ControllerContext = controllerContext;

            var iView = Substitute.For<IView>();
            autoMock.Provide(iView);

            var viewDataDictionary = new ViewDataDictionary();
            autoMock.Provide(viewDataDictionary);

            var iViewDataContainer = Substitute.For<IViewDataContainer>();
            iViewDataContainer.ViewData.Returns(viewDataDictionary);
            autoMock.Provide(iViewDataContainer);

            var textWriter = Substitute.For<TextWriter>();
            autoMock.Provide(textWriter);

            var viewContext = new ViewContext(controllerContext, iView, viewDataDictionary, new TempDataDictionary(), textWriter)
            {
                HttpContext = httpContext,
                RouteData = routeData,
                RequestContext = requestContext,
                Controller = controller
            };
            autoMock.Provide(viewContext);

            return autoMock;
        }

        public static T GetController<T>(this AutoMock autoMock) where T : Controller
        {
            var routes = new RouteCollection();
            MyApplication.RegisterRoutes(routes);
            var controller = autoMock.Resolve<T>();
            controller.ControllerContext = autoMock.Resolve<ControllerContext>();
            controller.Url = new UrlHelper(autoMock.Resolve<RequestContext>(), routes);
            return controller;
        }
    }

Above is the current version of the code that I use, but I change it every now and then when there is some other part of MVC that I need to mock, but haven’t yet. In this particular instance I was having trouble figuring out how to get Url.Action to return the actual URL – it was returning an empty string. I was registering my routes by calling the static method in my MvcApplication class, but that wasn’t enough. It took some Googling and¬†perseverance¬†to finally find the right set of steps to get it working (the one that really threw me was having to mock ApplyAppPathModifier in the Response object!):

  1. Register your routes in the route table
  2. Mock Request.Url (new Uri(“http://someurl/”))
  3. Mock Request.AppRelativeCurrentExecutionFilePath (“~/”)
  4. Mock Request.ApplicationPath (“/”)
  5. Mock Request.ServerVariables (new NameValueCollection())
  6. Mock Response.ApplyAppPathModifier(…) (return what is passed into it!)
  7. Set the UrlHelper in your controller to: new UrlHelper(A mock for request context with the above mocked, A route collection which has your applications routes registered into it);

Quite a strange an bizarre set of steps, but it’s what’s required to get around the core implementation within ASP.NET MVC. Maybe they will make it easier to test in the future…

With the above code snippet, I can do the following two lines of code to automatically get a controller with everything mocked correctly (not to mention any interfaces in it’s constructor automatically set to an NSubstitute Mock!):

var autoMock = AutoMockContainer.Create();
var controller = autoMock.GetController<HomeController>();

Testing code that uses Autofac + DependencyResolver in ASP.NET MVC

Sometimes it’s necessary to use DependencyResolver.Current in your MVC code where there is code that can’t be simply injected using your dependency injection framework. MVC provides a lot of extensibility points for things like model binding, model validation, and action filter, controller and view instantiation that mean that 90% of the time you can simply use your DI framework. This is made especially easy by frameworks like Autofac that provide easy MVC integration.

Use Case: Filter Provider

The main circumstance I’ve needed to use DependencyResolver.Current is in a filter provider (when trying to get precise control over globally applied filters and their execution order). I have tried passing through functors from Autofac that return the things I’m after, but you get Autofac resolution errors because it can’t tell what scope you are calling them from and if they are bound to, say, the HTTP lifetime then it can’t guarantee that the objects will be disposed correctly. There is possibly a way to inject something to correctly resolve the right Autofac lifetime scope, but I haven’t looked into it further.

An example such filter provider might be:

    public class MyAppFilterProvider : IFilterProvider
    {
        private readonly Environment _currentEnvironment;

        public MyAppFilterProvider(Environment currentEnvironment)
        {
            // Injected from Autofac
            _currentEnvironment = currentEnvironment;
        }

        public IEnumerable GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {

            // Ensure all pages other than the homepage are HTTPS in production
            if (_currentEnvironment == Environment.Prod && !(actionDescriptor.ActionName == "Index" && controllerContext.Controller.GetType() == typeof(StaticPageController)))
            {
                yield return new Filter(new RequireHttpsAttribute(), FilterScope.First, -5);
            }

            // Resolve the "current user" filter including any dependencies it may have
            // This could do something like, say put a reference to the current user from the database into the ViewBag so it can be accessed by the controller and the view
            var currentUserFilter = DependencyResolver.Current.GetService();
            yield return new Filter(currentUserFilter, FilterScope.First, -1);
        }
    }

Testing when there are calls to Dependency Resolver

Because we make use of DependencyResolver we need to be able to test it. This is trickier than it seems when using Autofac since if you resolve a service from the dependency resolver when there is no HttpContext then it will fail with “System.InvalidOperationException : The request lifetime scope cannot be created because the HttpContext is not available”. This problem may well affect other DI frameworks as well.

There are two options to combat this:

  • Create a custom class to resolve dependencies for that/those specific test/s and set it using DependencyResolver.SetResolver(new MyTestDependencyResolver()), but this could become tedious to maintain and complicates your test
  • Simulate a HTTP context by using HttpSimulator, it’s easy to install via NuGet (thanks Matt):¬†Install-Package HttpSimulator

When testing I use an Autofac container that automatically resolves interfaces as NSubstitute Substitutes (there are similar packages for other mocking frameworks, check out Autofac.Contrib). The following code is an example of how you can set up a test:

    public class ClassThatUsesDependencyResolver
    {
        public ClassThatUsesDependencyResolver()
        {
            var service = DependencyResolver.Current.GetService();
            service.Get(1);
        }
    }

    [TestFixture]
    class DependencyResolverTests
    {
        private AutoMock _autoMock;
        private HttpSimulator _httpSimulator;

        [SetUp]
        public void Setup()
        {
            _autoMock = new AutoMock();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoMock.Container));
            _httpSimulator = new HttpSimulator().SimulateRequest();
        }

        [TearDown]
        public void Teardown()
        {
            _httpSimulator.Dispose();
        }

        [Test]
        public void Test()
        {
            new ClassThatUsesDependencyResolver();
            DependencyResolver.Current.GetService().Received().Get(1);
        }
    }

One thing to note is that I used DependencyResolver.Current in the test rather than _autoMock.Resolve<…>() because the scoping that Autofac has is such that they resolve as different objects (which can be a bit confusing).

Testing the filter provider

Given I’ve shown an example filter provider above I figure I should demonstrate some of the tests that I have done in the past. There are two main things to test as far as I see (which you test for or indeed if you test for both (or don’t test it at all) depends on your situation – be pragmatic):

  • Test the order that the filters get applied is as you expect (you don’t want database calls for the current user before passive (e.g. single-sign-on) authentication is processed for instance…
  • Test that in certain circumstances a filter is applied (or not!)

An example showing both for the above filter provider is given below:

    [TestFixture]
    class MyAppFilterProviderShould
    {
        private AutoMock _autoMock;
        private HttpSimulator _httpSimulator;
        private ControllerContext _controllerContext;
        private ActionDescriptor _actionDescriptor;

        [SetUp]
        public void Setup()
        {
            _autoMock = new AutoMock();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoMock.Container));
            _httpSimulator = new HttpSimulator().SimulateRequest();
            _controllerContext = Substitute.For<ControllerContext>();
            _actionDescriptor = Substitute.For<ActionDescriptor>();
        }

        [TearDown]
        public void Teardown()
        {
            _httpSimulator.Dispose();
        }

        private IEnumerable<Filter> GetFilters(Environment environment)
        {
            var filterProvider = new MyAppFilterProvider(environment);
            return filterProvider.GetFilters(_controllerContext, _actionDescriptor);
        }

        [Test]
        public void Resolve_filters_in_correct_order()
        {
            var filters = GetFilters(Environment.Prod).ToList().OrderBy(f => f.Scope).OrderBy(f => f.Order).ToList();
            var index = 0;
            Assert.That(filters[index++].Instance, Is.TypeOf<RequireHttpsAttribute>()); // Require Https should always be run first
            Assert.That(filters[index++].Instance, Is.TypeOf<CurrentUserFilter>());
            Assert.That(filters, Has.Count.EqualTo(index)); // This ensures we update the test when more filters are added
        }

        [Test]
        public void Not_require_https_when_not_in_production([Values(Environment.Dev, Environment.CI, Environment.Test)] Environment environment)
        {
            Assert.That(GetFilters(environment).Select(f => f.Instance), Has.None.TypeOf<RequireHttpsAttribute>());
        }

        [Test]
        public void Not_require_https_for_homepage_in_production()
        {
            _controllerContext.Controller = _autoMock.Resolve<StaticPageController>();
            _actionDescriptor.ActionName.Returns("Index");
            Assert.That(GetFilters(Environment.Prod).Select(f => f.Instance), Has.None.TypeOf<RequireHttpsAttribute>());
        }
    }

Update (23/03/2013)

It might not be necessary to ever use DependencyResolver.Current any more due to a new technique I’ve found.

Unobtrusive Validation in ASP.NET MVC 3 and 4

Most things that can be done to reduce the amount of code that you need to write to get the same outcome (keeping in mind that you still need code to be easily readable/understandable for maintainability reasons) is great. The less code you have the less change of a bug, the less code to maintain, the less code that needs to be modified to add a new feature and the easier (hopefully) the overall solution is to understand.

In particular, if plumbing code that doesn’t actually serve any purpose other than to join the useful bits of code can be negated then that will usually significantly increase readability and maintainability of code. It’s also this sort of boring, monotonous code that often contains little errors that get missed because of the blight of CPDD (copy-paste-driven-development) where you copy a few lines of code, plonk them somewhere else and then change a couple of the class names or magic strings around. Inevitably you will miss one of two of the references and this is often combined with the fact that this type of code is likely not tested (depending on how strict your testing regime is).

Thus, one of the things that my team and I have put energy into over the last year and a half while we progress on our ASP.NET MVC journey is how to reduce this type of code. The first technique that springs to mind to combat this type of plumbing code is convention over configuration and to that end we have come up with unobtrusive techniques for model binding and validation that make heavy use of our dependency injection framework (Autofac). While the techniques I’ll demonstrate make use of Autofac, I imagine similar techniques can be used for the other frameworks.

Example code

This post is accompanied by some example code.

Data type validation

The DefaultModelBinder class that comes with MVC is pretty magical; it managed to parse the various values from the various scopes submitted with a request e.g. get and post values, etc. by name to your (potentially nested)  view model by name and pops any validation errors that it encounters in the Model State for you. Then a simple call to ModelState.IsValid in your controller will tell you if the view model was ok! This includes things like putting your data type as int and checking the input the user submitted was an integer and the same for any primitive types or enumerations! Furthermore, any custom types you define can have validation logic associated with them that will get automatically triggered (see my blog post for an example; look at the code for the custom type).

Thus, if you are taking user input in a controller action you will likely want code like this:

        public ActionResult SomeAction(SomeViewModel vm)
        {
            if (!ModelState.IsValid)
                return View(vm);

            // todo: Perform the action
        }

System.ComponentModel.DataAnnotations

By default in MVC you are given a number of unobtrusive validation options from the System.ComponentModel.DataAnnotations namespace, you can see the list of classes included on MSDN, but here is a quick rundown of the notable ones:

  • [DataType(DataType.Something)] – by default doesn’t actually perform any (server-side) validation, although you can use this to perform custom validation. It’s mostly used to provide metadata for UI controls to affect the display of the data. This is one of the confusing things about the DataAnnotations namespace – you would reasonably expect that this attribute would perform validation on first inspection!
  • [Display(“Label text”)] – Override the label text, although if you use this for every field because the default display of the field name when there is multiple words in camel case is ugly then you might want to define a custom metadata provider instead.
  • [Range(min, max)] – Specify a numerical range
  • [RegularExpression(regex)] – Specify a regex the data has to conform to
  • [Required] – enough said, although one thing to note is that non-nullable types like int, double etc. are implicitly required so the omission (or inclusion) of this attribute will have no effect. If you want to have an int that isn’t required make the type int? (or Nullable<int> if you like typing).
  • [StringLength(MinimumLength = minLength, MaximumLength = maxLength)] – Specify a min and/or max character length for a string

It should be noted that you are given the option of overriding the default error message for any of these attributes.

Data Annotations Extensions

The default set of unobtrusive data validation annotations can be extended with a much more useful set of validations via the Data Annotations Extensions project, which includes server- and client-side validation for:

  • Credit cards
  • Dates
  • Digits
  • Emails
  • Cross-property equality
  • File extensions
  • Digits and other numerical validations
  • Urls
  • Years

It’s pretty easy to get up and running with them too via NuGet:

Install-Package DataAnnotationsExtensions.MVC3

Custom Validation

Sometimes simply validating that the data type and format of your view model properties just isn’t enough, what if you want to validate that a URL returns a 200 OK, or that the username the user provided isn’t already in your database?

In this instance we need to turn to performing custom validation. There are a number of ways this could be done:

  1. Put custom validation code directly in your controller after checking ModelState.IsValid
    • Tedious and awful separation of concerns, plus we will still need to use model state (if you want errors to propagate to the UI via Html.ValidationMessageFor(…) or similar) and thus have a second call to check ModelState.IsValid
  2. Wrap the custom validation code into a helper or extension method and calling it from the controller after checking ModelState
    • More reusable if you use the view model multiple times and makes the controller action easier to test and understand, still tedious though
  3. Use one of the custom validation approaches to call the validation code
    • Even better separation of concerns since the model errors will now appear in model state when the controller action is called, but still reasonably tedious
  4. Use a validation library to take away the tedium (my favourite is Fluent Validation)
    • Getting there, but the amount of code to write increased :(…
  5. Use an MVC ModelValidatorProvider and reflection to unobtrusively apply the validation using the default model binder without having to implement IValidatableObject for every view model
    • Almost there, we still have to statically call DependencyResolver.Current to get any database repositories or similar, which is painful to test
    • In my case I’m using the MVC integration that the FluentValidation library provides to automatically pick up the correct validator, but you could obviously write your own ModelValidatorProvider, for this to work it simply requires that you add the [Validator(typeof(ValidatorClass)] attribute on your view models
  6. Integrate with your DI framework to inject dependencies to the unobtrusively called validator
    • Perfect!
    • Props to my Senior Developer Matthew Davies for coming up with this technique

I’ve ordered the list above in pretty much the order of approaches that we went through to get to where we are now. I’ve included a comparison of the different approaches in the Github repo for this blog post. Note that I’ve bundled all the code for each approach into a region when in reality the validation classes should be separated, but it makes it easier to compare the different approaches this way.

I should note that there is another approach I neglected to mention, which is to create a custom model binder for the view model and to perform the validation and setting of model state in there rather than the controller. While this is a better separation of concerns than putting the code in the controller, it still leaves a lot to be desired and can be quite tedious. On occasion, when you actually need to use custom model binding (e.g. not just for validation) it can become important to put errors in the model state though.

Conclusions

Now, the example code I’ve written doesn’t really give a good indication of the advantages of the final solution (that I recommend). This is mainly because I was¬†only performing a single view model validation on a single property of that validation – the more custom validation you have the more the unobtrusive solution shines. It’s also worth noting that your test code will become significantly less complex for each example I gave though as well. Another consideration is that the unobtrusive code, while it means you have to write less code all up does hide away a lot of what is happening in “magic”. For someone new to the solution this could pose a problem and make the solution hard to understand and for this reason if you are using this approach I recommend it forms a part of the (brief) documentation of your solution that supplements the code and tests.

At the end of the day, you should take a pragmatic approach, if all you need is one or two really simple validations then you probably don’t need to put in the code for the unobtrusive validation and at that point the unobtrusive validation will probably complicate rather than simplify your solution. If you are lucky enough to have some sort of base libraries that you use across projects and you have a consistent team that are familiar with it’s use then it makes sense to abstract away the unobtrusive validation code so that you can simply be up and running with it straight away for all projects.

Nice label names in ASP.NET MVC 3

By default in ASP.NET MVC the label names when you use the Html.LabelFor() method are simply the property name. This is great for single word properties like Email or Name, but quickly falls apart when you have properties like EmailAddress, and FirstName.

If you have a convention for your label names (at Curtin our forms standard states we need to have Sentence case labels) then you can save yourself a lot of hassle (e.g. having to specify [DisplayName(“…”)] on most of the properties) by simply defining a custom metadata provider. For example, the one we use is:

    public class MetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, 
            Func<object> modelAccessor, Type modelType, string propertyName)
        {
            // Default metadata implementations
            var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            // Auto-sentence case for display name
            if (metadata.DisplayName == null && metadata.PropertyName != null)
            {
                metadata.DisplayName = metadata.PropertyName.UnCamelCaseify();
            }

            return metadata;
        }
    }

Then you simply need the following one-liner in Global.asax.cs in Application_Start() to hook it up:

ModelMetadataProviders.Current = new MetadataProvider();

The UnCamelCaseify() extension method simply translates from CamelCase to Sentence case.

Obviously, for complex label names you will simply use the DisplayName attribute, but I find that more than 80% of the time the sentence case conversion works a treat, which is thus a nice time saver and results in less code, which is only a good thing!

Data type validation in ASP.NET MVC 3

This post outlines some experimentation that was conducted to find the different approaches that can be taken to perform data type validation in ASP.NET MVC 3 (when binding a view model).

I did some work on this over a year ago with Miguel Madero when he was doing some consulting work with my team. Frankly, I’m confused that I can’t find a post on my blog about it because I swear that I did one.

Regardless, this one is a fairly easy post to write because it’s basically easier said in code. As such I’ll direct you to the Github repository we created and put a small explanation below.

What do I mean by data type validation?

I mean validating the semantic form of the data – e.g. is it an integer number, is it an email address, is it one of a number of enumeration values? etc. I don’t mean validating the format of the data or the metadata or properties of the data – e.g. does it have a length greater than x characters, is it smaller than number y, does it conform to a given regular expression, is it the same as another property in the view model?

I realise that the line between data type and data format can be blurred, particularly when it comes to strings, so another way to put it is that I’m referring to the primary validation you will perform before being able to assign the data to the given property in the view model. Then on top of that you might want to perform other validations.

What are the ways that you can perform this validation in ASP.NET MVC?

We found three ways, feel free to post a comment if you discover any other ways and I’ll be happy to include that in the Github repo (or even better send me a pull request):

  • Custom validation attributes; e.g.
    [Digits]
    public string DigitsWithCustomAttribute { get; set; }
    
  • Custom Data Type attribute; e.g.
    [DataType("Digits")]
    public string DigitsWithDataTypeAttribute { get; set; }
    
  • Custom type; e.g.
    public Digits DigitsAsCustomType { get; set; }

Motivation and findings

The reason why we did this was because at the time the documentation for how to perform custom data type validation (outside of the build-in validation MVC provides) was confusing and lacking. It may have improved since then though…

At the end of the day, the easiest to implement was the custom validation attribute, but the nicest and tersest end result was from the most complex to implement in the custom type. I should note that one of the cool things (that all three methods supported) is that you can pass metadata to the JavaScript for client-side validation (you will have to write JavaScript validation code as well though for anything that jQuery Validate doesn’t support out of the box). The way that Microsoft have implemented this through their unobtrusive client validation code is pretty clever and well thought out :).

The readme file for the Github repository explains where to look to find the relevant code.

Enjoy!