Yesterday I wrote about ASP.NET MVC, TDD and AutoMapper, and how you can use them together in a DDD application. Today I thought I would follow up and explain how to apply these techniques to another important (but boring) part of any web application: user input validation.

To achieve this, we are using Fluent Validation, a validation framework that lets you easily set up validation rules using a fluent syntax:

public class UserRegistrationFormValidator : AbstractValidator<UserRegistrationForm>
{
    public UserRegistrationFormValidator()
    {
        RuleFor(f => f.Username).NotEmpty()
            .WithMessage("You must choose a username!");

        RuleFor(f => f.Email).EmailAddress()
            .When(f => !String.IsNullOrEmpty(f.Email))
            .WithMessage("This doesn't look like a valid e-mail address!");

        RuleFor(f => f.Url).MustSatisfy(new ValidWebsiteUrlSpecification())
            .When(f => !String.IsNullOrEmpty(f.Url))
            .WithMessage("This doesn't look like a valid URL!");
    }
}

If you think about it, validation and view model mapping have similar footprints in the application. They both:

  • Live in the application services layer
  • May invoke domain services
  • Use third-party libraries
  • Have standalone fluent configurations
  • Have standalone tests
  • Are injected into the application services

Let’s see how it all fits together starting at the outermost layer, the controller.

public class AccountController : Controller
{
    readonly IUserRegistrationService registrationService;
    readonly IFormsAuthentication formsAuth;

    ...

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(UserRegistrationForm user)
    {
        if (user == null)
            throw new ArgumentNullException("user");

        try
        {
            this.registrationService.RegisterNewUser(user);
            this.formsAuth.SignIn(user.Username, false);
            return RedirectToAction("Index", "Home");
        }
        catch (ValidationException e)
        {
            e.Result.AddToModelState(this.ModelState, "user");
            return View("Register", user);
        }
    }

    ...
}

As usual, the controller is pretty thin, delegating all responsibility (including performing any required validation) to an application service that handles new user registration. If validation fails, all our controller has to do is catch an exception and append the validation messages contained within to the model state to tell the user any mistakes they made.

The UserRegistrationForm validator is injected into the application service along with any others. Just like AutoMapper, we can now test both the controller, validator and application service separately.

public class UserRegistrationService : IUserRegistrationService
{
    readonly IUserRepository users;
    readonly IValidator<UserRegistrationForm> validator;

    ...

    public void RegisterNewUser(UserRegistrationForm form)
    {
        if (form == null)
            throw new ArgumentNullException("form");

        this.validator.ValidateAndThrow(form);

        User user = new UserBuilder()
            .WithUsername(form.Username)
            .WithAbout(form.About)
            .WithEmail(form.Email)
            .WithLocation(form.Location)
            .WithOpenId(form.OpenId)
            .WithUrl(form.Url);

        this.users.Save(user);
    }
}

Testing the user registration form validation rules

Fluent Validation has some nifty helper extensions that make unit testing a breeze:

[TestFixture]
public class When_validating_a_new_user_form
{
    IValidator<UserRegistrationForm> validator = new UserRegistrationFormValidator();

    [Test]
    public void The_username_cannot_be_empty()
    {
        validator.ShouldHaveValidationErrorFor(f => f.Username, "");
    }

    [Test]
    public void A_valid_email_address_must_be_provided()
    {
        validator.ShouldHaveValidationErrorFor(f => f.Email, "");
    }

    [Test]
    public void The_url_must_be_valid()
    {
        validator.ShouldNotHaveValidationErrorFor(f => f.Url, "http://foo.bar");
    }
}

You can even inject dependencies into the validator and mock them out for testing. For example, in this app the validator calls an IUsernameAvailabilityService to make sure the chosen username is still available.

Testing the user registration service

This validation code is now completely isolated, and we can mock out the entire thing when testing the application service:

[TestFixture]
public class When_registering_a_new_user
{
    IUserRegistrationService registrationService;
    Mock<IUserRepository> repository;
    Mock<IValidator<UserRegistrationForm>> validator;

    [Test, ExpectedException(typeof(ValidationException))]
    public void Should_throw_a_validation_exception_if_the_form_is_invalid()
    {
        validator.Setup(v => v.Validate(It.IsAny<UserRegistrationForm>()))
            .Returns(ObjectMother.GetFailingValidationResult());

        service.RegisterNewUser(ObjectMother.GetNewUserForm());
    }

    [Test]
    public void Should_add_the_new_user_to_the_repository()
    {
        var form = ObjectMother.GetNewUserForm();

        registrationService.RegisterNewUser(form);

        service.Verify(
            r => r.Save(It.Is<User>(u => u.Username.Equals(form.Username))));
    }
}

Testing the accounts controller

With validation out of the way, all we have to test on the controller is whether or not it appends the validation errors to the model state. Here are the fixtures for the success/failure scenarios:

[TestFixture]
public class When_successfully_registering_a_new_user : AccountControllerTestContext
{
    [SetUp]
    public override void SetUp()
    {
        ...
        result = controller.Register(form);
    }

    [Test]
    public void Should_register_the_new_user()
    {
        registrationService.Verify(s => s.RegisterNewUser(form), Times.Exactly(1));
    }

    [Test]
    public void Should_sign_in()
    {
        formsAuth.Verify(a => a.SignIn(user.Username, false));
    }
}

[TestFixture]
public class When_registering_an_invalid_user :  AccountControllerTestContext
{
    [SetUp]
    public override void SetUp()
    {
        ...

        registrationService.Setup(s => s.RegisterNewUser(form)).Throws(
            new ValidationException(
                ObjectMother.GetFailingValidationResult()));

        result = controller.Register(form);
    }

    [Test]
    public void Should_not_sign_in()
    {
        formsAuth.Verify(a => a.SignIn(It.IsAny<string>(),
            It.IsAny<bool>()), Times.Never());
    }

    [Test]
    public void Should_redirect_back_to_the_register_view_with_the_form_contents()
    {
        result.AssertViewRendered().ForView("Register")
            .WithViewData<UserRegistrationForm>().ShouldEqual(form);
    }
}

This post has been a bit heavier on code than usual, but hopefully it is enough to get an idea of how easy it is to implement Fluent Validation in your ASP.NET MVC application.

August 19th, 2009 | 18 Comments

This post is in response to a question on a recent article I wrote about mapping domain entities to presentation models with AutoMapper, an object-object mapper for .NET. Today I will give a brief example of how we can tie it all together in an ASP.NET MVC application using dependency injection and application services.

First, let’s start with the controller and the application service it talks to:

public class TasksController : Controller
{
    readonly ITaskService tasks;

    public TasksController(ITaskService tasks)
    {
        if (tasks == null)
            throw new ArgumentNullException("tasks");

        this.tasks = tasks;
    }

    public ActionResult Index()
    {
        IEnumerable<TaskView> results = this.tasks.GetCurrentTasks();
        return View(results);
    }

    ...
}
public interface ITaskService
{
    IEnumerable<TaskView> GetCurrentTasks();
    TaskView AddTask(TaskForm task);
    TaskView SaveTask(TaskForm task);
    void DeleteTask(int id);
}

Note the service’s inputs and outputs are defined in terms of view models (TaskView) and edit models (TaskForm). Performing this mapping in the application services layer keeps our controllers nice and simple. Remember we want to keep them as thin as possible.

Inside the tasks service

public class TaskService : ITaskService
{
    readonly ITaskRepository taskRepository;
    readonly IMappingEngine mapper;

    public TaskService(ITaskRepository taskRepository, IMappingEngine mapper)
    {
        if (taskRepository == null)
            throw new ArgumentNullException("taskRepository");

        if (mapper == null)
            throw new ArgumentNullException("mapper");

        this.taskRepository = taskRepository;
        this.mapper = mapper;
    }

    public IEnumerable<TaskView> GetCurrentTasks()
    {
        IEnumerable<Task> tasks = this.taskRepository.GetAll();
        return tasks.Select(t => this.mapper.Map<Task, TaskView>(t));
    }

    ...
}

The tasks service has two dependencies: the tasks repository* and AutoMapper itself. Injecting a repository into a service is simple enough, but for AutoMapper we have to inject an IMappingEngine instance to break the static dependency on AutoMapper.Mapper as discussed in this post.

* Note this is a very simple example — in a bigger app we might use CQS instead of querying the repository directly.

Testing the service

We are using Moq to isolate the tasks service from its repository and AutoMapper dependencies, which always return a known result from the Object Mother. Here are our test cases for all the different things that should occur when retrieving the current tasks:

[TestFixture]
public class When_getting_all_current_tasks
{
    Mock<ITaskRepository> repository;
    Mock<IMappingEngine> mapper;
    ITaskService service;
    IEnumerable<Task> tasks;

    [SetUp]
    public void SetUp()
    {
        repository = new Mock<ITaskRepository>();
        mapper = new Mock<IMappingEngine>();

        service = new TaskService(repository.Object, mapper.Object);

        tasks = ObjectMother.GetListOfTasks();
        repository.Setup(r => r.GetAll()).Returns(tasks);

        mapper.Setup(m => m.Map<Task, TaskView>(It.IsAny<Task>()))
            .Returns(ObjectMother.GetTaskView());
    }

    [Test]
    public void Should_get_all_the_tasks_from_the_repository()
    {
        service.GetCurrentTasks();

        repository.Verify(r => r.GetAll());
    }

    [Test]
    public void Should_map_tasks_to_view_models()
    {
        service.GetCurrentTasks();

        foreach (Task task in tasks)
            mapper.Verify(m => m.Map<Task, TaskView>(task));
    }

    [Test]
    public void Should_return_mapped_tasks()
    {
        IEnumerable<TaskView> results = service.GetCurrentTasks();
        results.Should().Not.Be.Empty();
    }
}

Enter AutoMapper

As you can see, we have both the controller and service under test without needing to involve AutoMapper yet. Remember it is being tested separately as discussed in my previous post.

To wire up AutoMapper so it gets injected into the TaskService, all we have to do is register IMappingEngine in the IoC container:

container.RegisterInstance<IMappingEngine>(Mapper.Engine);

Putting the mapping step in the application service and then mocking out AutoMapper like this allows us to easily test everything in isolation, without having to set up the mapper first.

I hope this answers your question Paul!

August 18th, 2009 | 9 Comments

I found an interesting problem this morning when my ASP.NET MVC application mysteriously broke after adding an HttpModule in the web.config. Here’s the problem code:

public class MvcApplication : HttpApplication, IUnityContainerAccessor
{
    IUnityContainer container;

    public IUnityContainer Container
    {
        get { return container; }
    }

    public void Application_Start()
    {
        this.container = new UnityContainer();

        // this.container.RegisterTypes etc
    }

The container was being configured fine in Application_Start, but then UnityControllerFactory would throw “The container seems to be unavailable in your HttpApplication subclass” exceptions every time you tried to load a page — this.container was somehow null again.

After doing a little digging and finding this article where someone had the same problem with Winsdor, it seems ASP.NET will create multiple HttpApplication instances when parallel requests are received. However, Application_Start only gets called once, so anything you would like to share between multiple instances (e.g. your IoC container) must be static:

public class MvcApplication : HttpApplication, IUnityContainerAccessor
{
    static IUnityContainer container; // good

    IUnityContainer container; // bad, not shared between HttpApplication instances

    public IUnityContainer Container
    {
        get { return container; }
    }
April 17th, 2009 | 2 Comments

This is the first half of a two-part article. Read the second half here: Domain entities vs presentation model objects, part 2: mapping.

When putting domain driven design (DDD) principles to practice in a real application, it’s important to recognize the difference between your domain model and presentation model.

Here’s a simple real-life example from a little MVC application that displays a to-do list of tasks. The task domain entity is very simple, with an identifer, a name and an optional due date:

// task domain entity
public class Task
{
    public int Id;
    public string Name;
    public DateTime? DueDate;
    // ...etc
}

Pretty much everything we want to know about this Task can be derived from its properties via Specifications. For example, an OverDueTaskSpecification will tell us whether or not the task is overdue by checking if the due date has already passed, and an UnscheduledTaskSpecification will tell us if the task is scheduled by checking if the due date is null.

However, when rendering the task to the user, the application’s view must remain dumb — a passive view — and cannot work this sort of stuff out for itself. It is not enough to simply pass a collection of domain entities to the view; all relevant details must be explicitly provided so the view has all the information it requires without having to do any work itself.

Together, all these UI-specific details form a presentation model object, which is effectively identical to a DTO in that it has only carries data and no methods or behaviour of its own (some people call them PTOs). Here’s what my application’s presentation model object for a task looks like:

// task presentation model object
public class TaskView
{
    public int Id;
    public string Name;
    public string DueDate;
    public bool IsUnscheduled;
    public bool IsOverDue;
    public long SortIndex;
}

The ID and name fields are exactly the same, but DueDate is now a string which will either hold a friendly-formatted date or ‘Anytime’ if the task is not scheduled. Unscheduled and overdue are now explicit flags so the view can immediately identify tasks that need special display like highlighting.

Most of the front-end user interaction in this application is implemented via JavaScript, so we need an index for sorting and appending tasks in the correct order. It needs to be simple to parse and fast to compare, so I chose a long integer which is resolved from the due date.

Note this is a very simple example with only one domain entity class which we just added some new properties to. Most real scenarios will require some degree of flattening aggregate object graphs into a single class, and hiding of fields which are not relevant.

In the big scheme of things, presentation model objects are defined in the application layer (see the Onion Architecture), where they are validated and mapped between domain entities. All public interfaces to the application layer are expressed in terms of presentation model objects, so domain entities do not leak into the UI layer.

In an ASP.NET MVC application for example, presentation model objects would be used as the Models for all views and action results.

Update: a friend asked me total why I don’t format DueDate in the view, as proper MVC separation of concerns would dictate. The reason is that as well as rendering them directly in the view when a page is requested, this application also sends presentation model objects to the client via AJAX. I decided that having one single place (instead of two) where tasks’ DueDates are formatted would make maintenance easier in the long run.

Continue reading: Domain entities vs presentation model objects, part 2: mapping

February 28th, 2009 | 2 Comments

In the past couple of weeks, I’ve started working on a new framework for my team, for developing domain-driven, test-driven web applications with ASP.NET MVC. Actually, it’s more of a meta-framework: a pattern for application development that leans on as many community-backed, best-of-class tools like NHibernate, NUnit, Rhino.Mocks, Json.NET etc as possible.

From time to time, however, I need to write my own utility class or interface, because it’s too specialised or not available elsewhere. To promote reuse and consistency between applications, I started putting them in a shared Foo.Core project (plus Foo.Core.Tests of course), similar to SharpArch.Core. Unfortunately, it began to turn into a bit of a mess; I had DDD-specific stuff like concept base classes and repository traits mixed in alongside generic LINQ extension methods and other random .NET utility classes.

It’s quite likely that some of the more generic stuff will be used in non-DDD projects, like SharePoint components and addins for Microsoft Office. But to a non-DDD developer, Foo.Core contains a lot of mysterious and scary stuff for whom the purpose of isn’t clear. This is not going to help adoption within my team.

To solve this problem, I decided to split the project in two. I now have a Foo.DomainDrivenDesign project that so far includes:

  • Repository Traits
  • Specification bases
  • DomainException
  • IEntityValidator<T>, RuleViolation and RuleViolationException
  • ObjectWithId<T>

The project name makes it immediately obviously what all this stuff is for. The rest has been dumped in Foo.Utilities:

Hopefully in future, the Utilities project can be eliminated completely and replaced by Umbrella or Utilities.NET so we don’t have to maintain it.

January 20th, 2009 | No Comments Yet