Channels ▼
RSS

Mobile

Visual Studio 2012 for ASP.NET Developers


Writing Asynchronous Code

Asynchronous operations are a necessity in modern websites. An asynchronous API for handling requests has been part of ASP.NET since version 1.0, but it was never easy to use in Web Forms or MVC. In ASP.NET 4.5, you can consider this fixed: Writing async methods is really straightforward and the resulting code is surprisingly simple to read. It should be noted that most of credit goes to a couple of new keywords added to the C# language: await and async. Here's how you write now an async method in ASP.NET MVC:

public async Task<IList<News>> GetAll()
{
   var url = "...";   // Some RSS feed
   var client = new WebClient();

   // The current ASP.NET thread is NOT blocked waiting for results to download 
   var result = await client.DownloadStringTaskAsync(url);
   return Parse(result); 
}

In the sample code, you use an instance of WebClient to asynchronously download an RSS feed and then parse it to a list of custom objects. Before .NET 4.5, you needed two controller methods running before and after the "async point" where the original ASP.NET thread yields to an OS thread and returns to the ASP.NET threadpool. The underlying behavior is exactly the same, but the resulting code is much sweeter thanks to the syntactic sugar of keywords async and await.

Bundling Resource Files

As Web pages offer greater client functionality, the cost of downloading several script files (and related resources such as CSS and images) grows. To obtain decent performance, minification and bundling are therefore a necessary. Until ASP.NET 4.5, you had to resort to external libraries to get these services. Now you can leverage built-in bundling as shown below for JavaScript files:

<script type="text/javascript" src="/Content/Scripts/js" />

You instruct the server to combine all JS files in the specified path to be dynamically combined together in a single minified file and returned over a single request. If you want to take control over the minification algorithm and the way in which files are grouped together, you can create a custom bundle. You add the following code to the global.asax startup code:

var bundleCore = new Bundle("~/CoreScripts", new JsMinify());     // Standard minification
bundleCore.AddFile("~/Content/Scripts/jquery.js");
bundleCore.AddFile("~/Content/Scripts/modernizr.js"); 
BundleTable.Bundles.Add(bundleCore);
var bundleApp = new Bundle("~/AppScripts", new MyCustomMinify()); // Custom minification
bundleApp.AddFile("~/Content/Scripts/app.index.js"); 
bundleApp.AddFile("~/Content/Scripts/app.global.js"); 
BundleTable.Bundles.Add(bundleApp);

Such bundles are created upon application startup and can be downloaded using the following markup:

<script type="text/javascript" src="~/CoreScripts" />
<script type="text/javascript" src="~/AppScripts" />

Bundling and minification work in the same way for CSS, except that you use the CssMinify class as the default minifier for CSS content.

Mobile Development in ASP.NET MVC

Among the standard project templates in ASP.NET MVC, you find a new mobile template as in Figure 2. If you start from the template, you will get a sample site that works well on mobile devices.


Figure 2: Project templates in ASP.NET MVC.

How does the sample mobile site differ from a standard desktop site? First, it uses the viewport meta tag to control the size of the browser's rendering area.

  <meta name="viewport" content="width=device-width" />

Restricting the viewport to the actual device width fits any content to the exact screen real-estate, resulting in more comfortable reading for users. Second, the pages of the site are designed using jQuery Mobile. The jQuery Mobile library uses ad hoc widgets, which give an iPhone-style look to the page, and they style basic HTML elements properly for touch input.

This is an extremely simple way to approach the development of a mobile site. Because of the numerous different form factors for mobile devices, a key sore point for building mobile sites is finding a way to serve different content (and layout) to different classes of mobile devices; and even recognizing different classes of devices. The sample project template leaves handling this (key) design aspect to jQuery Mobile. The progressive enhancement design is better to have than not, but it doesn't solve the problem of serving different content to different devices.

If the standard mobile project template is not the right starting point for your needs, ASP.NET MVC does have a small API that makes implementing multi-serving — the ability to serve different content to different classes of devices — fairly simple. This small API is based on the concept of display modes. A display mode identifies a possible way of serving markup to a specific family of devices. Have a look at the code below:

var smartphones = new DefaultDisplayMode("smart")
{
    ContextCondition = (c => Helpers.IsSmartPhone(c))
};
DisplayModeProvider.Instance.Modes.Insert(0, smartphones);

The display mode named "smart" captures all requests whose HTTP context makes the function IsSmartphone return true:

private class Helpers
{
    public static bool IsSmartPhone(HttpContextBase context)
    {
        return IsSmartPhoneInternal(context.GetOverriddenUserAgent()); 
    }
    private static bool IsSmartPhoneInternal(string userAgent)
    {
        var ua = userAgent.ToLower();
        return ua.Contains("iphone") || ua.Contains("android");
    }
}

The sample code recognizes as smart phones any device whose user agent string contains iphone or android. With this infrastructure up and running, all you need to do is add views to your project according to the pattern xxx.smart.cshtml, where xxx is the name of the view. Those views will be automatically selected when the requesting browser is recognized as a smart phone.

Once you get accustomed to display modes, you're ready to face the core problem: How can you reliably detect the capabilities (OS, touch, resolution, whether it is a tablet) of the device? For that, you need to go outside the Microsoft packages to libraries like WURFL — the de facto standard for device capabilities detection.

Conclusion

ASP.NET is a well-established branch of the .NET Framework, so you can hardly expect lots of relevant new features with each new release. Both Web Forms and MVC are mature platforms and, while improvements are always possible and desirable, the room for expanding well-done and mature platforms is limited. Nonetheless, in this release of Visual Studio, Microsoft has added useful tools for coding REST applications, a greatly simplified JavaScript minimizer and bundler, and handy ways of tailoring delivered content to the various form factors of mobile devices. Taken together, these features facilitate writing apps quickly for access by mobile devices. These enhancements alone warrant the upgrade to the new release.


Dino Esposito has written several books on ASP programming and is a frequent contributor to Dr. Dobb's.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video