Saturday 23 February 2013

ASP.NET MVC Consolidating "Usings" in Views/Web.config

Something I came across yesterday that you may find useful as an ASP.NET MVC developer. If you find yourself having to include the same set of "usings" across many of your razor views, then you can consolidate them and put them in the Web.config that sits under the Views folder.

The specific config element you're interested in is system.web.webPages.razor/pages/namespaces. It's a case of just creating an entry for each of your commonly used namespaces and then you don't need to worry about adding @using's or fully qualified class names in your views to resolve commonly used types.

...

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyMvcApp.Models.ViewModels" />
  </namespaces>
</pages>

...
If you're using the WebForms (ASPX) view engine then the equivalent place to add your global usings is in the same Web.config but within the system.web/pages/namespaces element.

Wednesday 20 February 2013

Implementing the Chain of Responsibility Design Pattern

Earlier this week I made use of the Chain of Responsibility design pattern to solve a fairly straight-forward problem. I've always been careful when trying to apply design patterns, it's easy to get carried away and try to force a design pattern to a problem that doesn't really require it. In this case, I felt it was justified and hopefully you'll think the same!

The Context

I'll give some context to the problem before we go into exactly what the Chain of Responsibility pattern is. I was working on a HTTP service (built on ASP.NET Web API) which had an API controller action that accepted requests for some data stored in a persistent repository. My requirement was to inspect the incoming request object, and depending on certain characteristics of the request, log the request object data to zero or many different output locations. This is to enable reporting on the types of requests that the service receives. The output locations were disparate data stores such as an XML file, Excel file and SQL Server Database. The key point was that to log the request I had to inspect the content of the request, and depending on some criteria, log it to none or certain data stores. Furthermore, certain requests had to be ignored and therefore not logged.

Chain of Responsibility

When I read this requirement I knew immediately there was a design pattern for this type of problem. I had taken an Object-Oriented design pattern course at university around six years ago but couldn't quite remember the name of the pattern. After having a quick look on the GoF website, I eventually found it - Chain of Responsibility (CoR). CoR is a software design pattern that has been classified into the "behavioral" category of patterns - these are patterns that broadly deal with objects interacting with other objects. The idea is that you have multiple handler objects chained together just like a linked list data structure. An incoming request object is passed over to the first handler in the chain, the handler (depending on its "responsibility"), inspects the request and can either:
  1. Handle the request and not pass the request down the chain of handlers
  2. Handle the request but still pass the request down the chain of handlers
  3. Not handle the request and pass the request down the chain to the next handler
Note that before a handler sends the request object down the chain, it is also responsible for checking if it is actually linked to another handler. If a handler isn't linked to another handler, it is the last handler in the chain and therefore consumes the request.

Applying CoR to the Problem

In my case, the incoming data request to the API was my CoR request that required "handling" from a logging perspective. I implemented a separate concrete logging handler class for each of the concrete data stores (XML, Excel and SQL Server). Each logging handler inspected the request and logged the request if it matched the criteria for the handler before passing the request to the next handler. Therefore, in my case, the CoR handler behaviour corresponded to point two above.

The Implementation

Note that I've stripped down the code below (especially for each concrete handler) so that it is easier to see what's going on from a design pattern perspective.

The first step was to write an abstract base handler that defined the behaviour that each of my handlers will support. The HandlerBase class below is generic enough to be reused in any case where you require a CoR implemented. The single type parameter "TRequest" is the type of the object that will go through your chain (can be any .NET type).
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public abstract void HandleRequest(TRequest request);
}
The HandlerBase class has one property, which allows users of a handler to set a successor to this handler (the next handler in the chain) and it has an abstract method that all derived classes will need to implement - HandleRequest. You will see further below how we use the Successor property when setting up our chain, and how each concrete handler (a class that derives from HandlerBase) uses the HandleRequest method on its successor to pass the request down the chain.

Next, I implemented each of my concrete handlers - that is, a handler for logging to an XML document, Excel document and SQL server.
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to xml document

        // Pass on the request to the next handler, if any
        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Notice how the concrete handler LogRequestToXmlHandler derives from HandlerBase and passes the type of the object that is going through the chain - ApiDataRequest. Also notice that because we're inheriting from an abstract base class containing one abstract method - we're forced by the compiler to override the HandleRequest method. This method accepts one parameter, the request object. It is in this method that you will place any specific handling logic for the request object - I've added some pseudo-code to demonstrate this. The last couple of lines inspect the Successor property (inherited from the base class), if it isn't null - then we call the HandleRequest on it, thus passing our request down the chain. If Successor returns null, then the current handler is the last in the chain and we do nothing - effectively consuming the request. For completeness, the other handlers are below.
public class LogRequestToExcelHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to excel document

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}

public class LogRequestToDbHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to database

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Now that we have our handlers, the final step is to setup our chain so that it's ready to handle requests. The code below shows how the handlers are chained together.
HandlerBase<ApiDataRequest> logToXmlHandler
    = new LogRequestToXmlHandler();

HandlerBase<ApiDataRequest> logToExcelHandler
    = new LogRequestToExcelHandler();

HandlerBase<ApiDataRequest> logToDbHandler
    = new LogRequestToDbHandler();

logToXmlHandler.Successor = logToExcelHandler;
logToExcelHandler.Successor = logToDbHandler;
The first step above was to initialise each handler that will be going into the chain. We then use the Successor property to chain the three handlers together. The beauty of using this pattern is that you can chain however many handlers you want and even make the chain configurable so that it is setup at runtime depending on some settings in a config file.

Now, when a new request came through my API, it was a simple case of invoking the HandleRequest method on the first handler in the chain and passing the ApiDataRequest object through as a parameter. This sent the object down the chain, allowing each log handler to inspect it and decide whether to log it to their individual outputs.
logToXmlHandler.HandleRequest(request);
* Update *

One thing that I missed in this post and is worth mentioning is a scenario where you don't want each concrete handler to decide whether to pass the request on down the chain. In this case, the request would go to every handler in the chain regardless. One way to accomplish this is to update the HandlerBase class as follows:
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public void HandleRequest(TRequest request)
    {
        Handle(request);

        if (Successor != null)
            Successor.HandleRequest(request);
    }

    protected abstract void Handle(TRequest request);
}
The updated HandlerBase now implements a public HandleRequest method which first delegates the handling logic to an abstract method (Handle) which will be overridden by a concrete handler. Once a request has been handled, a test is made to check if there is a successor and if there is, then the request is passed on. What this now means is that each concrete handler will implement just one method, Handle, and not need to worry about whether to pass the request on or not - that is done automatically in the HandleRequest method. An example concrete handler is below:
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    protected override void Handle(ApiDataRequest request)
    {
        // Check request and log it, if required
    }
}

Saturday 16 February 2013

ASP.NET MVC - Methods in Razor Views (via @helper syntax)

Todays post is about a little-known but very useful feature that was added to the Razor view engine since ASP.NET MVC3. The feature that I'm refering to is the @helper syntax which lets you define reusable methods at the view level. Let's dive straight into an example to show off this feature.

Imagine you have a simple Book model in your ASP.NET MVC project:
public class Book
{
    public string Isbn { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}
You may then have a controller called BookController with one HTTP GET action called Index. This action may read some books from some repository and pass a list of Book objects to the view. For the sake of brevity, I've hard-coded a couple of Book instances in the snippet below:
public class BookController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        var books = new List<Book>();

        books.Add(new Book {
            Isbn = "9780385660075",
            Title = "The Kite Runner",
            Author = "Khaled Hosseini"
        });

        books.Add(new Book {
            Isbn = "9780571219766",
            Title = "Self",
            Author = "Yann Martel"
        });

        return View(books);
    }
}
Initially, your Razor engine-based Index view may look something like:
@using System.Collections.Generic
@using MvcHelperMethods.Models

@model IList<Book>

<h2>Books Index</h2>

@foreach (var book in Model)
{
    <div>
        <span class="bookTitle">@book.Title</span>
        <span class="bookAuthor">by @book.Author</span>
        <span class="bookIsbn">ISBN: @book.Isbn</span>
    </div>
}
Now imagine that you have a new requirement to introduce another view in your application which shows books by individual authors. The requirement states that the books should be displayed exactly how they are on the Index view. In this scenario, you'll need to create another view that accepts a list of Book objects and renders them out. The only difference being that a different controller action would be used which returns books by a specific author. The view code would look very similar. This presents an opportunity to make use of the @helper syntax in Razor.

The @helper syntax lets you define a view-level method that consists of both C# and Razor syntax. This method can be placed in a specific view or outside of a specific view so that it can be reused across multiple views. We'll use the latter option and define an @helper method called RenderBook which accepts a single parameter of type Book and renders the book out using a mixture of Razor and html syntax.

To accomplish this in your ASP.NET MVC solution, ensure you have the App_Code folder. In Visual Studio 2012, you can add this folder by right-clicking your project then going to Add --> Add ASP.NET Folder --> App_Code. In your App_Code folder, you will now create a new MVC Razor View Page (a .cshtml file). Right click the App_Code folder and go to Add -> New Item. Select the option called "MVC View Page (Razor)", name your view page something sensible - like "ViewHelperMethods.cshtml" then click Add. If there is some pre-defined content in the new view, just remove it all. Now you can write your reusable @helper view method called RenderBook in the ViewHelperMethods.cshtml file:

@using MvcHelperMethods.Models

@helper RenderBook(Book book)
{
    <div>
        <span class="bookTitle">@book.Title</span>
        <span class="bookAuthor">by @book.Author</span>
        <span class="bookIsbn">ISBN: @book.Isbn</span>
    </div>
}
As you can see from the syntax, it's quite similar to the syntax of a standard C# method except you don't specify a return type and access modifier, instead, you use the keyword @helper. You can now refactor your original Index view so that it looks like:
@using System.Collections.Generic
@using MvcHelperMethods.Models

@model IList<Book>

<h2>Books Index</h2>

@foreach (var book in Model)
{
    @ViewHelperMethods.RenderBook(book)
}
Notice that we're now calling our reusable RenderBook method. You can now call the same RenderBook method from your other views, in our case, the view that displays books by specific authors. In summary, if you're working on a fairly large ASP.NET MVC application with many views, then this is a very useful feature to ensure your views are more maintainable.

Update: As pointed out by a reader of this post (on Google+), you also have the option to create a partial view for the Book model and reuse that. The example I gave above was quite simplistic and was aimed at introducing the reader to the @helper feature. I believe the advantage that helper methods give is that you can easily pass them additional parameters at the view level and those parameters can then control exactly how the smaller view is rendered out.

Wednesday 13 February 2013

Mocking Objects with Moq

A friend recently told me that his development team is trialing test-driven development on a new project and he asked me to recommend a mocking library for them to try. I recommended Moq (also available as a NuGet package). I have been using Moq as my go-to mocking library in C# for well over a year now. Having had experience with a couple of other mocking libraries prior to Moq, I can testify to its widely reported ease of use. It has a very neat fluent API that results in easy to understand code.

If you are new to the idea of mocking, then think of it as a way to simulate (or "mock") the behaviour of an object, where you can control exactly how you want the mocked object to behave. The mocked object can simulate a class that you have written from scratch or it can even simulate a class that you don't have the source code for (e.g. a BCL class).

A good example of when you would want to mock an object is when you are writing a unit test. Let's imagine that your unit test is exercising a method called RegisterUser on your UserService class. The UserService class constructor accepts an interface called IEmailService as one of its parameters. The IEmailService defines one method called SendRegSuccessEmail (which returns a boolean that indicates whether the email was fired off successfully). The RegisterUser method accepts two parameters, an email and a password and returns a boolean that indicates if registration was successful. The implementation of this method checks if the supplied email already exists, if it doesn't, then it saves the email and password in some repository, sends an e-mail to the user telling them that their registration was successful and returns true. If registration fails (e.g. if the user already exists in the repository) then false is returned.

With this setup, imagine that you now wanted to write a unit test that tests whether the RegisterUser method prevents multiple registrations for a single email. As the developer of the RegisterUser method, you know that it uses the IEmailService to fire off an e-mail - and that you (obviously) don't want to fire off e-mails in your unit test. This is where mocking comes into play. You can setup your test so that you mock an implementation of the IEmailService interface and control how you want the SendEmail method to behave. Using the Moq library, your setup would look like:
var emailServiceMock = new Mock<IEmailService>();
 emailServiceMock
   .Setup(es => es.SendRegSuccessEmail(It.IsAny<string>()))
     .Returns(true);

var userService = new UserService(emailServiceMock.Object, ...);

// Test userService.RegisterUser(...)
You can now write the remaining bit of your unit test using the userService object with the knowledge that you'll never fire off unnecessary e-mails when calls are made to the IEmailService.SendEmail method. As can be seen in the snippet above, it is quite simple to setup a mock, you instantiate an instance of the generic Mock class and pass in the object-to-mock as a type parameter (in this case IEmailService). The next line tells the mock object that whenever the SendRegSuccessEmail method is called with any string parameter (It.IsAny<string>()), then return the boolean value true. You can try this for yourself and you'll find that the following expression will always equal true:
emailServiceMock.Object.SendRegSuccessEmail("foo@bar.com")
Once the mock object is setup, you can get the actual mocked object instance using the "Object" property on the Mock class - the returned instance from this property can then be used in any location that it is expected (in the snippet, we've passed the mocked instance into the UserService constructor). The RegisterUser method will therefore use this mock and we'll avoid the unwanted scenario of emails getting fired off whenever our unit tests are executed!