ASP.NET MVC, TDD and Fluent Validation

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.

ASP.NET MVC, TDD and AutoMapper

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!

Real-life DDD: organise code by responsibility layers, not repositories and services

Here is a screenshot from Visual Studio from a project for a client that I have been lead developer on for the past few months. The domain (actually a bounded context within a larger ERP system) is training for an emergency services department, where staff are required to be proficient in all sorts of skills like using rescue equipment and performing first aid.

On the left is what the domain layer looked like when we began several months ago. On the right is how it looks today:

Before: repositories, specifications, services. After: responsibility layers

What do you notice? Obviously the domain model has grown bigger and more complex over time (including another 10-20 classes that didn’t fit in my screenshot). But more importantly our grouping of objects has changed.

Responsibility layers

We originally started grouping classes into namespaces based on their object type — we had separate namespaces for repositories, specifications, factories and services.

This method made sense when we just began and our domain was very small (just a handful of core objects), but did not scale as complexity grew. For example, one important aspect of the model that arose was the separation of practicing from monitoring, i.e.:

  • scheduling training tasks, choosing which skills are to be practiced, choosing who will participate etc versus
  • determining which skills a staff member is required to maintain according to their location and position, looking back and seeing when the last time they practiced skill X, applying policies to see if it’s time to practice it again, and looking at the overall operational status of individuals, teams etc

You can see this separation reflected in the screenshot on the right.

When we first put this split in, and others like it, we preserved this grouping inside each layer — e.g. we had a Practicing.Services and Monitoring.Services namespace. This dual classification felt wrong however, and led to an annoying proliferation of namespaces that required gazillions of using statements that we had to fix every time something shifted or renamed.

After a while, we pulled objects back to half a dozen big namespaces with 10-30 classes each, supplemented by a few smaller specific domain policy and state groups. These new namespaces are beginning to show the responsibility layers of our domain, and give a much clearer picture than simply grouping all the specifications together.

ASB’s new Track My Spending feature is great!

Disclaimer: I usually only write about code, and certainly this is not a product review blog, but this is something that really made my day. And their web pages end in .aspx so technically it is .NET related.

Yesterday, I came a forum post alerting ASB customers to check out their new Track My Spending online banking feature:

ASB Track My Money expense tracking (not mine)

The reason I’m so stoked about this feature is because I’ve been looking for a way of tracking where my day-to-day money is spent for a few months now.

I was considering moving banks to somewhere that supported OFX Direct Connect (so I can download my transaction logs automatically and sort them with a tool like GNUCash or Quicken), and I even started writing the foundations of a little WPF app to do it.

Now I can see pie charts and expense breakdowns just below the rest of my internet banking. What’s more is the transaction coding process is almost exactly the same as I had envisaged for my app — categorize one transaction, and it’ll automatically tag all similar transactions with the same label.

Coding transactions

To be honest, I never would’ve expected something like this from ASB — the rest of their online banking interface is pretty clunky and looks exactly the same as it did 6-7 years since I first became a customer. So it was a nice suprise to find this little gem hidden in the junk section of the online banking menus.

I’m not sure if other banks maybe already have features like this (probably even better ones), but I was very impressed anyway. So congratulations ASB, you guys hit the nail on the head and made one very satisfied customer at least!

Visual Studio: TFS or SVN?

You may have heard of the TFS MVP fiasco being talked about over the past couple of days. Aside from demonstrating how not to disagree with comments on your blog, it raised a favourite old question for .NET developers using Visual Studio: which is better — Team Foundation Server or Subversion?

Functionally, I find both TFS and SVN pretty much the same. They aren’t really, of course, but my everyday SCM needs are pretty simple, beyond branching, merging, and tagging/labelling — so it really just comes down to which one integrates into your IDE better.

At work, we use TFS 2008 for source control. I like the IDE integration with Visual Studio (well, most of it) — it’s seamless, and I really like the pending changes window for keeping track of what I’m working on.

At home, I use VisualSVN. The IDE integration with Visual Studio is almost as good as TFS, but extends out to Windows Explorer as well, courtesy of TortoiseSVN (which it uses under the hood). TortoiseSVN also has autocompletion for files and class names in the commit dialog which makes good check-in comments really easy.

So is TFS worth the license cost over VisualSVN? Maybe, if you use the work item tracking and MS Project integration. But based on my needs, I probably wouldn’t choose it.

A programmers secret weapon: the humble to-do list

A while ago I wrote a post how to lose traction on a personal software project, based on mistakes I have made myself in the past that have slowed down or even completely stopped progress. Today I want to share a tip that has greatly improved my time management since I’ve started doing it, and helped combat many “programmer’s block” moments I am notorious for.

Coming back to work

After you take a break from a coding project for a while, getting back into the groove can be difficult. Stopping for a while can be a great way to gain perspective and maybe reevaluate your goals of what the application should and shouldn’t be, but it can also be really hard starting again where you left off.

If you know you will be leaving for a while, and want to return later, you can try leaving a test failing, or some other obvious problem that needs fixing (like a syntax error), but these only keep you going in the short term. It can be difficult choosing the next big piece of functionality to work on.

Keeping an eye on the big picture

Have you ever been in the situation where, working on an application, you surround yourself with a forest of rich infrastructure code — configuration, data access, logging, UI widgets etc — and then stop and realise that’s all your application is: an empty shell that doesn’t do anything useful yet?

Or alternatively, do you ever find yourself getting lost in detail, giving unfair attention to making one little component perfect while neglecting the other 90% needed to be up and running for the alpha release?

All those little extra “clean up” tasks you want to do

While coding I’m always spotting things I want to clean up like refactorings, missing comments, source code formatting, etc. I want to finish my current task before starting something new (and can’t until I check in my current work anyway), but I do want to do these little clean ups at some stage.

All these problems really boil down to one simple question — what should I work on next?

The programmers’ to-do list

I have found from own personal experience that sitting down to cut code without a well-thought-out plan of attack is asking for trouble. As well as the examples above, I generally skip from task to task, dabbling in things I find interesting, but not gaining much real traction towards a useful application.

Over the past few months, I have discovered that keeping a detailed to-do list is a great tool for combating these problems and staying on track. The premise is very simple: take a high-level block of work — e.g. implementing a single user story — and break it down into all the little programming steps you need to do to get there, no matter how insignificant or obvious.

Here’s a dumb example snippet of a to-do list for a web app I am working on in my spare time (the whole thing runs about four pages total). You can see the ‘high level’ tasks get vaguer towards the end, because I haven’t planned them out yet, and right at the bottom there are unimportant cleanup tasks.

The key here is to be fine-grained; you want to see all the little tasks that needs to be done, and then tick them off to see your progress. Even if they are always assumed — like validation — it’s like a calendar, only useful if you know all your appointments are in there. And it doesn’t really matter where your high-level tasks start, as long as together they add up to a program that will be useful to a user.

Defer little tasks

If you think of an easy little ‘clean up’ task you’d like to do, don’t do it now — just write it down instead. Why? Because:

  • If you do it now, it could sidetrack you from your current focus
  • It might be a low priority and a poor use of your time right now
  • Instead of doing it now, it could be an easy way to get back into the groove later

For example, if you’ve got half an hour free before going somewhere, and want to spend it on your application, you don’t want to be starting fresh on some giant new piece of work. Why not spend the minutes crossing off one or two of those little clean-up tasks you’ve been meaning to do?

Planning sessions

Alternatively, if you’re not in the mood to code, you could use the time as a planning sessionand try to think of the next big task you want to achieve, and all the small steps that make it up. This is just as helpful as cutting coding, and makes you think about the big picture.

To-do list software

I’m a geek, so naturally, I want some flash tool for managing my to-do list. There are a lot to-do list applications on the web like Todoist and Remember the Milk. I tried a few, but eventually just went back to a bulleted, indented Word document because I found it by far the quickest to work with.

Working too many late nights makes you socially retarded

Working too many late nights makes you socially retarded

This Monday, we released the first of several stages in a 6-month upgrade project to a big ERP system. As with any software project, it was a big rush at the end, but particularly so this time because I was lead, and we were doing a lot of architectural improvements (which I will talk about here in a series of articles over the next few weeks).

Anyway, in the race for the deadline, I worked late nights and weekends for sixteen days in a row. The stress was fine, because I was really enjoying the work, but by the end, I found I could hardly hold a conversation with someone about anything other than the project itself. It was as if all my social skills had somehow been sapped — the mind was willing, but the tongue had nothing to talk about.

I’ve never experienced such a thing before, and it was pretty strange. It’s important not to neglect your social life when you’re working overtime to finish a project. It’s very easy to start saying no to parties and spending time with your friends, believing you’re doing a good thing by having early nights and recharging your batteries. My advice to you is DON’T. You need the distraction right now more than ever.

Hungarian notation, what do I think?

Hungarian notation, what do I think?

A girl at work asked me yesterday about whether or not encoding a variable’s type into its name — aka Hungarian Notation — was a good idea (she’s a designer who secretly wants to be a developer). I thought I might have written an article here before about it, but it seems I haven’t, so here goes.

Encoding the purpose of a variable into its name is a good idea. For example:

customerFormpasswordHashfirstNamesubmitButtonbodyHtmlerrorMessagecountries (plural = a collection of some sort)

This is just common-sense good naming.

On the other hand, I think encoding the variable’s runtime type into its name is brain-damaged — it usually doesn’t help much and just decreases code clarity. For example:

strNamestrMessageiAgearrNamesdsEmployees

I don’t think prefixes like this add any real value at all, because you could probably guess what type they are from their names and context in which they appear. Therefore they are simply clutter.

If you need them, however, then that suggests to me you have either 1) poor variable names that fail to properly explain their purpose or 2) your methods are too long and need to be refactored. Either way, fudging variable names so you can remember what type they were declared as 300 lines earlier is not the right answer, and will probably make your code even less readable.

The difference between these two naming styles is officially known as apps vs systems Hungarian notation. Joel Spolsky has a good article on the difference and how one became perverted into the other.

Windows equivalents of ps and kill commands

Windows equivalents of ps and kill commands

If you’ve ever used Unix, you’ll no doubt be well-aquainted with the commands ps and kill. On Windows, the graphical Task Manager performs these roles pretty well, but if you ever find yourself needing to resort to the command line to kill a process (e.g. for some reason on the Vista machine I am writing this on Task Manager just sits in the system tray flashing instead of opening), the Windows equivalents of ps and kill are tasklist and taskkill:

tasklist /v  - equivalent to ps aux
taskkill /f /im ncover*  - equivalent to kill -9 ncover*

AutoMapper: writing a custom IValueResolver for Gravatar

Gravatar

I’m a big fan of Jimmy Bogard’s AutoMapper – a handy little tool for fluently mapping your domain model objects to presentation model objects.

This week, I added Gravatar support to a small side-project I’m working on. For those that don’t know, Gravatar is a globally recognized avatar with a URL based on the MD5 hash of your e-mail address, e.g.:

http://www.gravatar.com/avatar/3b3be63a4c2a439b013787725dfce802.jpg

Any site that knows your e-mail address can therefore generate your Gravatar URL and show your profile pic. If you’re using AutoMapper, mapping an e-mail address to a Gravatar URL is a perfect case for a custom IValueResolver, e.g.:

Mapper.CreateMap<User, UserProfile>()    .ForMember(p => p.Username, opt => opt.MapFrom(u => u.Username))    .ForMember(p => p.About, opt => opt.MapFrom(u => u.Profile.About))    .ForMember(p => p.Location, opt => opt.MapFrom(u => u.Profile.Location))    .ForMember(p => p.Url, opt => opt.MapFrom(u => u.Profile.Url))    .ForMember(p => p.DisplayImage,               opt => opt.ResolveUsing<GravatarUrlResolver>()                         .FromMember(u => u.Profile.Email));

You can download my implementation here: GravatarUrlResolver.cs and tests (of course) here: GravatarUrlResolverTests.cs