Monthly Archives: December 2010

Asynchronous MVC using the Task Parallel Library

I’m not going to go into any detail in this post as to why asynchronous actions may be beneficial to your application; other people have covered that in more detail than I’d care to go into. This post will however, try to show how implementing Async controllers can be made simpler, using the Task Parallel Library in .NET 4.0 and a little bit of MVC trickery.

Before I go too far, I’d like to point you to have a look at an introduction in using the TPL with MVC from Mike Hadlow. Mike’s post shows how you can use the TPL to simplify the consumption of Asynchronous services, from an Asp.Net Mvc AsyncController.

In Mike’s example, he ends up with the following AsyncController implementation:

public class HomeController : AsyncController

{

    readonly UserService userService = new UserService();

 

    [HttpGet]

    public void IndexAsync()

    {

        AsyncManager.OutstandingOperations.Increment();

        userService.GetCurrentUser().ContinueWith(t1 =>

        {

            var user = t1.Result;

            userService.SendUserAMessage(user, "Hi From the MVC TPL experiment").ContinueWith(t2 =>

            {

                AsyncManager.Parameters["user"] = user;

                AsyncManager.OutstandingOperations.Decrement();

            });

        });

       

    }

 

    public ViewResult IndexCompleted(User user)

    {

        return View(user);

    }

}

 

As you can see, we unfortunately have to abandon the succinctness of the TPL syntax, and revert back to the Asynchronous Programming Model pattern of having a start method with a completion callback.

Mike points out that it would be rather nice if instead, we could write a controller action that returns a Task result instead – our resultant action would be nice and simple:

[HttpGet]
public Task<ViewResult> Index()
{
    return from user in userService.GetCurrentUser()
           from _ in userService.SendUserAMessage(user, "Hi From the MVC TPL experiment")
           select View(user);
}

Even though this will compile (when using the TPL extension extras library), unfortunately, this will not run, as the default controller action invoker for running async actions (AsyncControllerActionInvoker) does not know how to handle Tasks…

Asp.Net Mvc Futures

The asp.net mvc futures project currently includes some more flexibility in its support for async patterns. Rather than being limited to supporting the “Async –> Completed” action pairs, the futures project contains the following options:

 

  • The Async Pattern (BeginFoo/EndFoo)
  • The event pattern (Foo/FooCompleted)
  • The Delegate Pattern (returning a Func<> that represents a continuation).

The most interesting of these techniques (to this example) is the Delegate Pattern:

[HttpGet]
public Func<int> Foo(int id)
{
    return () => id * 2;
}

Using this approach, a controller can specify a delegate to provide a completion callback. It’s not too much of a leap to see the similarities with this, and the desired technique using Tasks.

So how does the Asp.Net Futures project add these additional features?  Perhaps we can extend them to support TPL?

Hooking in to the Action Invoker

To support the additional async patterns using the futures project, a Controller must inherit the AsyncController from the futures assembly. This controller overrides a property from the base controller class in order to specify a new Action Invoker that can correctly identify actions that represent asynchronous methods. To identify these actions, the AsyncActionInvoker delegates to a AsyncActionMethodSelector that will reflect over the methods on a controller, and pick our asynchronous actions based on naming conventions, or the return type in the case of the delegate pattern. This seems like a good place to start looking to add our new feature.

Unfortunately for us, the AsyncActionMethodSelector does not delegate out to individual objects to identify and handle each type of asynchronous pattern, so supporting an additional pattern will involve some changes to this class. Following the Open/Closed principle could really have cleared up the design here…

Anyway, once we have extended to the AsyncActionMethodSelector to support our new pattern, we need to hook this back into the AsyncActionInvoker (which again, requires some code changes to this class – seriously, this code could’ve been much simpler if people followed SOLID principles!), and then we can use this new invoker from our Async Controller.

Using this new invoker, our controller can now support the use of Tasks for Asynchronous Actions!

Conclusion

As with other areas of the MVC framework, extending the framework to add new features like supporting Tasks to represent Asynchronous Controller Actions was a little bit more painful than it could have been, but in the end, it’s worth it to clean up the the required code to support asynchronous controller actions.

To check out the implementation of all this, you can get the full sample source from GitHub:

https://github.com/CraigCav/Suteki.AsyncMvcTpl

Script Management in ASP.Net MVC

In all but the simplest of modern web applications, it’s not uncommon to find that our application depends on many web assets such as CSS and JavaScript files. While it’s generally good practice for maintainability to keep these files separated into small logical chunks, unfortunately practice has implications on the overall performance of our application when referencing these resources; an additional HTTP request will be made for each asset, in turn adding to the latency of the initial load of our application.

Whilst many developers are probably aware of various optimization techniques such as those proposed in the YSlow recommendations (like script combining, minification, caching, compression), implementing these techniques can be a bit of burden.

Further still, when we utilize the Master and Content page features of our view engine, we will often want to place core JavaScript (such as the JQuery library) and common component initialization in the Master Page, whilst the Content pages may have their own file sets and initialization scripts.

This set-up adds an additional complexity to managing our scripts; we need to ensure the scripts tags are all rendered first, regardless of where they are located in the page (Master Page/Content Page/User Control) or our application will start throwing JavaScript exceptions all over the place!

Help is at hand!

Several projects exist that attempt to address some, or all of the issues I’ve mentioned (page request optimization and asset management) – lets take a look at some of our options:

Telerik ScriptRegistrar

Probably one of the closest matches to our requirements, the Telerik ScriptRegistrar and its partner in crime the StylesheetRegistrar provide a simple mechanism to provide a range of optimizations to improve the performance of our applications.  The ScriptRegistrar API is composed of a fluent interface allowing groups of scripts to be rendered at the bottom of our master page, whilst additional script dependencies and initialization can be registered in content pages. One small gotcha to look out for here is that partial views returned from Ajax requests will not have the scripts registered.

Overview

  • Resource combination (served by a IHttpHandler)
  • Grouping
  • Compression
  • Caching
  • Support for Content Delivery Networks (CDN)
  • Nice Fluent Interface for script registration and initialization
  • A Commercial License is required if you are building closed-source commercial products for redistribution (GPLv2 license).
  • Extra care is required for scripts registered in partial views rendered by Ajax calls (since these are not included by the ScriptRegistrar).
  • Minification of your scripts is not provided (although some support for selecting between pre-minified scripts and un-minified scripts in debug mode is provided)
  • Cache headers and ETags are not generated

Include Combiner

The Include Combiner project, which is included in the MvcContrib* solution as MvcContrib.IncludeHandling, tackles many of the aforementioned issues surrounding the optimization of asset management. It is not as complete as the Telerik implementation, and also suffers from the same complexity in registering scripts in partial views returned by ajax, however this tool is still worth a look for Asp.Net Mvc applications, especially for projects already consuming MvcContrib.

Overview

  • Resource combination (served by a custom controller)
  • Grouping
    • Resources grouped by page usage (rather than explicit sets) – scripts shared across pages must be re-downloaded for each page.
  • Compression
  • Minifies scripts
  • Generates cache headers and ETags
  • Simple interface for including/outputting resources
  • Included as part of MvcContrib
  • No server side caching – content is fetched every request
  • Treats JS and CSS separately, and therefore causes a minimum of 2 additional requests per page.
  • Extra care is required for scripts registered in partial views rendered by Ajax calls (since these are not included by the ScriptRegistrar).

Combres

Possibly the most complete libraries in terms of features, Combres is a strong choice for managing assets in your application. Combres requires that you define named resources sets which can then be combined, minified, compressed and sent to the browser as a single request. Interestingly, combres has an interesting extensibility model allowing developers to provide additional features, such as applying .less rules and replacing relative urls with absolute urls in css files. On the downside, the configuration model for Combres is very XML heavy, and not as nice to consume as the fluent API provided by other libraries. Unfortunately, the underlying implementation seems to wrap around the XML configuration too, so extending the library for easier consumption (applying your own conventions etc) might be tricky, especially when considered in conjunction with the fact that there are NO unit tests included in the source code (available on CodePlex).

Overview

  • Resource combination (served by a IHttpHandler and RouteHandler)
  • Grouping (Resource sets)
  • Compression (gzip or deflate depending on browser)
  • Minifies scripts (YUI compressor, MS Ajax or Google Closure)
  • Generates cache headers and ETags
  • Server side caching
  • Integrated with Asp.Net routing engine, and therefore also supports webforms development in addition to MVC
  • Extensible filtering support
  • XML heavy asset configuration model
  • Requires resource configuration upfront – as far as I can tell, there isn’t an easy way for a view component to quietly declare “I need this JS/CSS” and for it to be included if it isn’t already there

Conclusion

Optimizing our web applications and conforming to good practices like caching, combining and compressing our resources needn’t be a burden for developers. There are some great tools available to help us keep our applications nimble, whilst ensuring we aren’t distracted from delivering our customers value with technical implementation concerns. I’ve listed our some of the tools I’ve come across that bring us closer to achieving this goal.

Is there anything I’ve missed? Do you have any tools you use to optimize asset management? If so, let me know so I can check them out too!

 

*MvcContrib is a project designed to add functionality to and ease the application of Microsofts Asp.Net Mvc framework and really useful for developers looking to develop and test UI elements on top of MS Asp.Net Mvc. Check it out here.

Follow

Get every new post delivered to your Inbox.