Tuesday, December 6, 2011

ASP.NET MVC 4 Developer Preview: What’s New

Microsoft is ramping up the release cycles of some of its products, and the phenomenal rate at which the ASP.NET MVC framework is being updated is testament to that.
The latest version, MVC 4 Developer Preview, has some cool new additions to its armory. Over the next few weeks, I’ll be taking a look at some of the features new to the framework, and how you might use these in your website.
The more noticeable features added to the framework include:
  • Mobile project templates
  • Display modes
  • Recipes
  • Task support for Asynchronous controllers
  • Azure SDK
  • Bug fixes

Installation

Before undertaking any development, you’ll need to install the MVC 4 builds. The simplest way to do this is via the Web Platform Installer. MVC 4 is available for Visual Studio 2010 or Visual Studio 2011 Developer Preview. All of the MVC articles I’m authoring are developed in Visual Studio 2011 Developer Preview. Below are the links to get started.
Once you’ve installed everything, the fun really begins!

Task Support for Asynchronous Controllers

The feature I’m going to be focusing on today is task support for asynchronous controllers.
Nobody likes to wait, so why should your users wait for a long-running asynchronous task? It doesn’t make sense!
Developing asynchronous controllers has been available since MVC 3, but for this to work you had to write a bunch of extra code – what I like to refer to as code noise – to get it to work.
Take the example of integrating Twitter into a webpage. In MVC 3, the code needed to follow specific rules. Instead of there being one action method, there had to be two action methods. Both were named the same, but for the method beginning the asynchronous request, you needed to append Async to the action name. For the method handling the ending of the asynchronous request, you needed to append Completed to the action name.
It’s much easier to follow if you see some code. The sample code below requests data from Twitter asynchronously.
public void SearchTwitterAsync()
{
        const string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
 
        // the asynchronous operation is declared
        AsyncManager.OutstandingOperations.Increment();
 
        var webClient = new WebClient();
        webClient.DownloadStringCompleted += (sender, e) =>
        {
              AsyncManager.Parameters["results"] = e.Result;
              AsyncManager.OutstandingOperations.Decrement();
        };
        webClient.DownloadStringAsync(new Uri(url)); //the asynchronous process is launched
}
 
public ActionResult SearchTwitterCompleted(string results)
{
        // Now return the twitter results to the client
        return Json(ReadTwitterResults(results), JsonRequestBehavior.AllowGet);
}
The code above is going off to Twitter, searching for data and returning the results asynchronously. There’s a lot of code noise in there and to me, it’s violating – for want of a better word – the Don’t Repeat Yourself (DRY) principle.
Well, in MVC 4, these tasks have been rolled into one. You can now write asynchronous action methods as single methods that return an object of type Task or Task.
These features are only available in MVC 4 or C# 5. Here’s the simplified code below.
public async Task Search()
{
        string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}
The results are the same, but now you can reduce the amount of code you need to accomplish the same outcome.
Asynchronous action methods that return Task instances can also support timeouts. To set a time limit for your action method, you can use the AsyncTimeout attribute. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds. Once it has timed out, the view “TimedOut” will be displayed to the user.
[AsyncTimeout(2500)]
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task Search()
{
        string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}
Nothing else has changed with asynchronous actions.
The controller still needs to derive from AsyncController, and you still access the action in the same way but you have to write less code.
Asynchronous controllers are perfect for pieces of code that run to great length. Most of the time you’ll be working with a database, so being able to make calls to the database asynchronously is a big plus for the end user.
Why should they wait?
All of the code samples can be downloaded here.

 Now article will focus on using Display Modes.  This selects a view depending on the browser making the request, which means you can target specific devices and give the user a truly rich experience.

Default Mobile Views in MVC 4
It’s important to understand a new feature in MVC 4.  By default, if you add a .mobile.cshtml view to a folder, that view will be rendered by mobile and tablet devices.
fig1
This is a nice feature, but if you want to target specific devices, such as the iPhone, iPad or Windows Phone, you can use Display Modes.
To do this, you need to register a new DefaultDisplayMode instance to specify which name to search for when a request meets the condition.  You set this in the global.asax file in the Application_Start event.  Here’s how to specify a display mode for an iPhone.
protected void Application_Start()
{
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context =>context.Request.UserAgent.IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
}
To consume views that meet this condition, you create a view but change the extension to .iPhone.cshtml.  Likewise if you want to target an iPad, create an iPad instance.
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPad")
{
ContextCondition = (context =>context.Request.UserAgent.IndexOf
("iPad", StringComparison.OrdinalIgnoreCase) >= 0)
});
Basically, Display Modes checks the User Agent.  If it finds a matching suffix, it will display any view it finds that matches the suffix.  The suffix is the parameter that’s passed to the DefaultDisplayMode method.  To see this in action, I’ve created a Home controller and added three views to the Home folder.
fig2
The differences between the views is the H1 heading.  They’ll display iPhone, iPad or Desktop depending on the device.  I’m also displaying the User Agent so you can see it changing.  First I’ll debug the website through my desktop browser.  You can  see the desktop specific page being served.
fig3
Now navigate to the website using an iPhone.  You’ll see the iPhone specific page being served.
fig4
Switching over to an iPad, you’ll see the iPad specific page being served.
fig5
This is a simple way to target specific devices, producing a view that suits the device – and thus the user.
Testing with Emulators
To test these new features, you can either use a physical iPhone or iPad, or you can use an emulator.  The emulator I was using is from MobiOne.  You can download a 15 day free trial here.
The Windows Phone RC emulator is free and can be downloaded here.
Likewise another good option is the User Agent Switcher add-on for Firefox, which changes the user agent that’s sent to the browser.  That can be downloaded here.

1 comment: