ASP.NET 4.5, ASP.NET MVC 4, ASP.NET Web Pages 2, and Visual Studio 2012 for web developers: Part 1

Wow, yesterday was a big day for ASP.NET developers! In addition to some other very cool things, Microsoft announced Visual Studio 2012, ASP.NET 4.5, ASP MVC 4 were released to manufacturing. Hooray! So what now?

Get The Bits

The easiest way to get all the new goodies is to install Visual Studio 2012. You've got a few options there:

We've got the top download links listed for you on the ASP.NET site as well.

Note: Just install what you'll use

As before, my personal recommendation is to just install the Visual Studio components you're expecting to use. If you never do C++ development, installing all the C++ support just means that your install will take longer, take up more space, make service packs take longer to install, increase the Windows Updates you'll encounter, etc. You can always modify the installed features if you need to later. Here's what I'm installing (I'm including Blend because I've been doing a bit of Windows 8 app development - it works with both both XAML and HTML Windows Store apps).

Here's what I've got selected:

Visual Studio 2012 Install

Learning Resources On The New Stuff

There is a ton of new stuff, and it's easy to get overwhelmed. Here's a quick overview of some of the top resources before we dig into specifics:

ASP.NET 4.5

Model Binding and Strongly Typed Data Controls

The Model Binding and Strongly Typed Data Controls in ASP.NET Web Forms are really cool. Damian Edwards (who helped found the Web Forms MVP project before joining the ASP.NET team) and team pulled of an amazing feat: they brought the model binding and strong typing features of ASP.NET MVC into ASP.NET Web Forms in a way that still fits with Web Forms. Essentially, it's something like an object data source approach, but so much smoother.

First, the strongly typed data controls allow you to define a model type for a control. That allows you to replace string-based data binding expressions with strongly typed binding expressions:

Hooray!

Also, notice that the FormView above isn't binding to a data source, it's got methods defined for Select / Insert / Update. The select method looks like this:

public Issue GetIssue([Control("issuesGrid")]int? id)
{
    return _db.Issues.Find(id);
}

The Insert and Update methods take advantage of the binding features in MVC, allowing you to bind to control values, URL and other contextual values, and custom value providers:

public void InsertIssue()
{
    var issue = new Issue();

    TryUpdateModel(issue);

    if (ModelState.IsValid)
    {
        _db.Issues.Add(issue);
        SaveChanges(issue);
    }
}

This eliminates all the tedious and error-prone "this parameter equals that control value, this other parameter equal that other control value, kill me now" type code. Note that TryUpdateModel call (familiar to MVC devs) which will automatically apply any validation rules defined via data annotations on the model class.

I gave a presentation this week at ThatConference looking at the feasibility of mixing ASP.NET Web Forms and MVC in the same project, and my conclusion was that the best way to get started is to get your Web Forms apps on ASP.NET 4.5 so you can start sharing models and converting traditional Web Forms code towards this approach, which is a lot more similar to MVC.

Bundling and Optimization

Bundling and Optimization in ASP.NET 4.5 and ASP.NET MVC 4 is based on an optimization system the MSN team developed called WebGrease. The core has been battle tested (MSN is a top 20 site) and performs really well. The bundling and optimization system optimizes user experience by compressing and combining CSS and JavaScript so your users get a faster experience and you minimize your bandwidth.

You'll see default bundles defined in \App_Start\BundleConfig.cs in an ASP.NET 4.5 Web Forms or ASP.NET MVC 4 application. Here's what it looks like in Web Forms:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
          "~/Scripts/WebForms/WebForms.js",
          "~/Scripts/WebForms/WebUIValidation.js",
          "~/Scripts/WebForms/MenuStandards.js",
          "~/Scripts/WebForms/Focus.js",
          "~/Scripts/WebForms/GridView.js",
          "~/Scripts/WebForms/DetailsView.js",
          "~/Scripts/WebForms/TreeView.js",
          "~/Scripts/WebForms/WebParts.js"));

    bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(
        "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",
        "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",
        "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",
        "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));

    // Use the Development version of Modernizr to develop with and learn from. Then, when you’re
    // ready for production, use the build tool at http://modernizr.com to pick only the tests you need
    bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
        "~/Scripts/modernizr-*"));
}

Now you can just use any of those bundles in your application:

 <asp:PlaceHolder runat="server">        
         <%: Scripts.Render("~/bundles/modernizr") %>
         <%: Scripts.Render("~/bundles/jquery") %>
         <%: Scripts.Render("~/bundles/jqueryui") %>
</asp:PlaceHolder>

One of my favorite parts about this is that we can make bundles that accomodate version numbers in script names, so updating jQuery (maybe via NuGet if you're awesome) doesn't require *any* code / markup changes:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
            "~/Scripts/jquery-ui-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.unobtrusive*",
            "~/Scripts/jquery.validate*"));

For more on using Bundling and Minification in Web Forms, see Adding Bundling and Minification to Web Forms (Rick Anderson) or either of the following videos:

Quick intro by Scott Hanselman:

Deep Dive by Howard Dierking:

Updated Project Templates (Adaptive Rendering)

Both the new ASP.NET Web Forms and MVC project templates have been redesigned. They don't just look nicer, they leverage web standards to automatically adapt to screen resolution (HTML and CSS only, no JavaScript or server-side code required).

Here's how the default template looks in a wide screen (> 850px):

2012-08-16_16h50_39

Resizing the screen automatically applies new styles via CSS media queries so it's easier to read and navigate:

2012-08-16_16h50_47

I wrote about how this works in pretty gory detail in the context of ASP.NET MVC 4, but it's working exactly the same in ASP.NET Web Forms 4.5.

OAuth and OpenID support

The default project templates now have built-in support for user registration and log in via OAuth and OpenID. They're making use of the excellent DotNetOpenAuth library, included as  a NuGet package so you can update later if you'd like.

Your OAuth and OpenID providers are registerd in \AppStart\AuthConfig.cs. Initially there are some examples that are all commented out (this is something you should do explicitly, and OAuth providers require you fill in an app id and app secret):

public static void RegisterOpenAuth()
{
    // See http://go.microsoft.com/fwlink/?LinkId=252803 for details on setting up this ASP.NET
    // application to support logging in via external services.

    //OpenAuth.AuthenticationClients.AddTwitter(
    //    consumerKey: "your Twitter consumer key",
    //    consumerSecret: "your Twitter consumer secret");

    //OpenAuth.AuthenticationClients.AddFacebook(
    //    appId: "your Facebook app id",
    //    appSecret: "your Facebook app secret");

    //OpenAuth.AuthenticationClients.AddMicrosoft(
    //    clientId: "your Microsoft account client id",
    //    clientSecret: "your Microsoft account client secret");

    //OpenAuth.AuthenticationClients.AddGoogle();
}

Uncommenting and filling in the key / secret information for OAuth clients changes your Log In screen to allow users to access your site as members without creating an account:

2012-08-16_16h59_15

For more information on configuring specific clients, see Pranav's blog post: OAuth/OpenID Support for WebForms, MVC and WebPages.

And much more...

There's of course a lot more, these are just some of my favorite features. Let's move on to ASP.NET MVC 4!

ASP.NET MVC

Mobile Features

ASP.NET MVC 4 has several great options to help you build sites that work well on mobile devices. Here's a diagram that helps illustrate it:

2012-08-16_19h10_27

I talked about all three of these and overviewed ASP.NET MVC 4 mobile features at aspConf:

We've already talked about adaptive rendering in Web Forms, it works the same here.

Display Modes allow you to create views which are served to mobile devices, and you can create your own display modes to target specific devices. Since the display modes are defined in code, they can be based on any logic you want - database queries, user cookies, day of the week, whatever. Here's how a display mode is defined:

DisplayModeProvider.Instance.Modes.Insert(0, new 
DefaultDisplayMode("iPhone") 
{ 
    ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf 
        ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) 
 });

Finally, the mobile template (based on jQuery Mobile) makes it easy to create web applications that are optimized for mobile users.

To learn more about what you can do using the Mobile Project Template, see Rick Anderson's tutorial: ASP.NET MVC 4 Mobile Features.

K. Scott Allen did a great presentation on the Mobile Project Template and jQuery Mobile at NDC 2012:

Scott Allen - ASP.NET MVC and jQuery Mobile from NDCOslo on Vimeo.

Async Support

ASP.NET MVC has had async support since MVC 2, but it was hard. It gets a lot easier in MVC 4 due to async and await. Once again, I'll refer to Rick Anderson's excellent tutorial: Using Asynchronous Methods in ASP.NET MVC 4. Here's an example of an async controller method that calls three long running services and returns to the user when all three are complete:

public async Task<ActionResult> PWGasync() 
{ 
    ViewBag.SyncType = "Asynchronous"; 
    var widgetService = new WidgetService(); 
    var prodService = new ProductService(); 
    var gizmoService = new GizmoService(); 
 
    var widgetTask = widgetService.GetWidgetsAsync(); 
    var prodTask = prodService.GetProductsAsync(); 
    var gizmoTask = gizmoService.GetGizmosAsync(); 
 
    await Task.WhenAll(widgetTask, prodTask, gizmoTask); 
 
    var pwgVM = new ProdGizWidgetVM( 
       widgetTask.Result, 
       prodTask.Result, 
       gizmoTask.Result 
       ); 
 
    return View("PWG", pwgVM); 
}

OAuth and OpenID support

Yes, already mentioned before in Web Forms, but it's also in MVC 4, and it's really cool.

The ASP.NET MVC 4 Release Notes cover these and other features in more detail.

ASP.NET Web API

ASP.NET Web API is officially released! I did a series of screencasts earlier this year that introduce ASP.NET Web API. They're slightly out of date on a few technical details (I'll be updating them soon) but explain what it is and why you'd use it; here's the first in the series:

[Video and code on the ASP.NET site]

The team wrote some great posts on recent features:

Wow, that's a lot, and we didn't even get into Visual Studio 2012 features for Web Developers! Looks like it's time for a break, with a part 2 to follow...

30 Comments

Comments have been disabled for this content.