A Comparison of Asp.Net MVC Templates

Visual Studio 2012 and the Asp.Net refresh (2012.2) have introduced a number of new and refreshed templates to help bootstrap your project as you turn up a new MVC 4 site.  This post breaks down the key items that are in each of the templates to help you get a better understanding of your starting point.

Structure, Feature and Element Comparison

The template names are across the top, and the items included in the template in the leftmost column.

  Empty Basic Internet Intranet Mobile
Folder Structure          
    Controllers, Models, Views, App_Start, App_Data     X     X     X     X     X
    Content, Scripts       X     X     X     X
    Views\Shared       X     X     X     X
Project Elements          
    Global.asax, Web.Config, Packages.Config     X     X     X     X     X
    FilterConfig, RouteConfig, WebApiConfig     X     X     X     X     X
    BundleConfig       X     X     X     X
    AuthConfig         X    
    _ViewStart, _Layout and Error Pages       X     X     X     X
    Sample Home Controller & Views         X     X     X
Notable Third-Party Features          
    Packages Installed     11     23     34     25     28
    jQuery, jQuery UI       X     X     X     X
    jQuery Mobile             X
    KnockoutJS, Modernizer, Validation       X     X     X     X
    EntityFramework       X     X     X     X
Authentication and Authorization          
    Sample Controller         X       X
    Models, EF DbContext Samples         X       X
    Supporting “Simple” Provider & ActionFilter         X       X
    Support for External OAuth         X       X
    Auth via Active Directory (Azure or Windows)           X  

And Then Again, In English

Taking a look at the templates from a more pragmatic perspective, let’s consider how you’d actually use them and the situations where they’d be most appealing.

  • Empty – This is the barebones project with enough of the MVC bits wired so that you can work on the Asp.Net stack. If you are looking for a clean slate, this is it. You can leverage the conventions of the framework, choose your client-side libraries, build your own templates, and create your controllers and views from scratch.
  • Basic – If you’re good with the default selection of scripts and templates – jQuery and jQuery UI are installed for you – the rest of the pieces are in place for you to pick up and start developing. This project type adds a basic template (your layout page) and an error page with no styling.  There’s more of a canvas here, with a little less legwork than the empty template.
  • Internet – This is the bells and whistles edition. Sample controllers, local accounts and third-party authentication, a complete style makeover and more. You can use this to build a decent looking CRUD site, just be prepared for 1984-style conformity.  There’s also a wealth of JavaScript libraries to help build a great end-user experience as you learn the MVC Framework.
  • Intranet – The biggest differentiator for this template from the Internet version is the absence of accounts and authorization. Instead, the project ships with a read me with links on how to configure Active Directory and integrated sign on. This is especially great if you’re working with Azure and corporate accounts where users have IE installed – you get single sign-on to the app.
  • Mobile – While all the template types support alternate views which could be used for mobile support, this project comes ready to target mobile browsers. I won’t get into the debate of responsive design vs. dedicated sites here, but certainly if you are trying to create a context-centric, mobile-specific experience, this is the easiest place to start.

Not Mentioned In Today’s Broadcast

There are notably three project types missing from the mix: Single Page Application, Web API and the newly introduced Facebook Application. These each a have specific function in the web development world and are worth considering individually; I’ll break them down in another post.

What’s in A Name?

While I’ve spelled out the features of MVC projects that are included in each of the templates, I want to also say that if there is something that you would like included in a template that doesn’t have it by default, it’s still pretty easy to add most in.  Many of the items above can be added with a right-click –> “New Something…” or by installing a package via NuGet.

And, Next on the Docket

All that’s left now to do is to poke around with the templates. Download Visual Studio 2012 from the Asp.Net MVC homepage to get all the bits you need to start building sites. You can get the template refresh from the vNext site. Finally, push through some of the tutorials and get an idea of what you can do with the MVC Framework!

Diving deeper? Try these:

Bootstrapping Asp.Net MVC–Introduction to Twitter.Bootstrap.Mvc4

I’m continuing my series in exploring Bootstrap integration with the Mvc Framework – part of the Asp.Net stack – and in this entry we’re going to be looking at a helper package that you can install in seconds to kickstart a project.  Covered in this video are:

  • Installing from NuGet
  • Forking from GitHub, building locally and using the latest bits (or contributing!)
  • Navigation routes
  • Auto-scaffolded views for CRUD operations

Getting the Latest Stable Bits

One thing I didn’t mention in the video is that you don’t have to build the packages locally to get the latest versions. Eric Hexter has a MyGet feed setup to help you out in this regard. imageFrom the Package Manager Console in Visual Studio, simply pop open the options and add a new package feed:

http://www.myget.org/F/erichexter/

This lets you install the package from MyGet if you want to expose features not yet posted to the primary NuGet feed.

Alternatively, you can use the NuGet Package Explorer (as I am in the image shown here) to browse through the packages on the feed. Primarily you’re going to be looking for “Bootstrap” or “Navigation” in the feed to pick up the relevant packages.

Detail All the Things!

I cover a lot of ground in the video and try to give you a sense of what is possible to do in only a few short minutes. If you want to dive deeper here are some resources to help you out as you explore Twitter’s Bootstrap library working with Asp.Net Mvc:

Have fun!

jQuery Script Map Causing Critical Error in jQuery 1.9.0

Script maps are a great addition to the debugging arsenal of any script developer. Even for those of us who are “consumers” of some of the libraries out there, the script maps will help us get at the details of why something is going sideways when we’re working with minified versions of the code. 

Without the map, it has been difficult to find the correlating code in the original file. Elijah Manor does a great job at going over how to take advantage of script map support and it’s benefits in jQuery 1.9.0.

Minification in MVC4 and Critical Errors from the jQuery Script Map

There is a chance that you’ll run into this if you’re dropping code in Visual Studio 2012 on Win 8 with Asp.Net MVC, using bundling and minification:

JavaScript critical error at line 1, column 11 in http://localhost:0000Scripts/jquery-1.9.0.min.map

SCRIPT1004: Expected ‘;’

If this is the case, check to see that your wildcard isn’t to greedy. For example, if you have something like this set up in your BundleConfig.cs:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-1.*"));

…you’re telling the bundling engine to grab anything matching the script “jquery-1.anything”, and as a great optimization, the MVC Framework is smart enough to grab only one of library.js or library.min.js, and it prefers the min.js for you.  The downside here is that the bundle builder is using a prefix match here, and it seems to be picking up the .map file as well. This seems to be inadvertently causing the critical error mentioned above (map files aren’t to be shipped to the client as part of the request).

The Fix is In

The good thing is that you’re not stuck on wildcards, and it’s likely better to be using the semantic versioning replacement token (especially with the jQuery libraries).  Update your bundle to the following:

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

The {version} token is a replacement that does a best match against the file according to SemVer.  Now, instead of all the files getting added, and the risk of files being added multiple times, we get a smarter match on the library we are requesting for bundling and minification.

Upgrading to jQuery 1.9.0 Starts Giving you Unhandled Exception Errors

I am running Windows 8, Visual Studio 2012 and working with Asp.Net MVC4. My upgrade was from jQuery 1.8.2 to jQuery 1.9.0 when this error surfaced.

If you upgrade an MVC project to the latest jQuery bits, you man run into an error similar to the following:

Unhandled exception at line 115, column 5 in http://localhost:0000/Scripts/jquery.unobtrusive-ajax.js

0x800a01b6 - JavaScript runtime error: Object doesn’t support property or method ‘live’

There have been a number of methods that were deprecated in the library some time ago, and now jQuery 1.9.0 is executing on those changes and has removed the methods for good. You can read more about the changes on the jQuery site.

This doesn’t leave you stranded…the team has graciously provided a migration path for those who want to take advantage of the new library enhancements, but still need to maintain legacy code.  The unobtrusive ajax script in our MVC projects are still calling some of these deprecated methods, so we need to take advantage of this offering.

To add backwards compatibility to our project, we simple have to drop into the Package Manager Console and type the command:
PM> Install-Package jQuery.Migrate

 

Tada!

Embedding Videos With Windows Live Writer and MetroPress

The Problem

Windows Live Writer, IMO, is still the best little tool out there for creating content for blogs. It does a great job at nearly every task related to editing post, pages, categories and tags, and it provides flexible posting options with the ability to manage multiple blogs.

But, at times, she’s verbose! Embedding a YouTube video, for instance, inserts the following code into your post:


<div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:befb91d4-acb8-41d9-a0da-ec64375d826f" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"><embed src="http://www.youtube.com/v/uA7Z8WfD3bU?hd=1" type="application/x-shockwave-flash" wmode="transparent" width="448" height="252"></embed></div>
Unfortunately, that breaks [MetroPress](http://metropress.codeplex.com/) because the embed tag and script cannot load inside a Windows Store app. The fix is quite simple: rather than using the built-in “Insert Video” feature, you simply need to copy and paste the embed code from YouType, which looks more like this:
<iframe width="560" height="315" src="http://www.youtube.com/embed/uA7Z8WfD3bU" frameborder="0" allowfullscreen></iframe>

This embed code is snapped from Share –> Embed on the YouTube site under your video.

image

You can see that the new embed code is cleaner, and better still it is allowed in a Windows Store app and the video plays embedded in your posts just fine.

image

A Little Background

MetroPress is a handy way to augment your blog with an offline-capable reader for your followers.  From their site:

In a nutshell, this framework is a flexible app template that can be easily customized and extend it to create more awesome Windows store applications.

Using the quickstart, it takes about an hour to get your blog prepped and the project built up so that you can release a Windows Store (Windows 8) application.  Mine passed certification on the first attempt.

You can get MetroPress on their CodePlex project site.

Seed Windows Azure Mobile Services Tables with Less Than 10 Lines of Code

Seed Windows Azure Mobile Services Tables with Less Than 10 Lines of Code

Looking for an easy way to build realistic test or sample data out for your app?  You only need two packages and a few lines of code to seed whatever kind of table you need.

I won’t lie, when you want to throw a few dozen records into a table, this is pretty sexy:

var peopleTable = _client.GetTable<person>();
var people = Angie.FastList<person>();
foreach (var person in people)
{
    peopleTable.Insert(person);
}

How to Make it Happen

  1. Create a Windows Azure Mobile Services instance and add the tables you need. In my example above, I’m using a table called “Person”.  There is only one field created to start with called “Id”.  Leave this as-is because we’ll use Dynamic Schema (on by default) to flesh out the table.
  2. Create a new Console app in Visual Studio 2012.
  3. Install two packages from the Package Manager Console:
    1. Install-Package Heyns.ZumoClient&nbsp; – [ZumoClient][1] is a use-anywhere .Net 4.0 library that wraps Windows Azure Mobile Services, provided by [Deon Heyns][2].
    2. Install-Package AngelaSmith – [AngelaSmith][3] is the object initializing smarty-pants that can populate your properties with realistic-looking data, created by [Dave Paquette][4] and [James Chambers][5] (that's me!).
    

With those things in place, you simply need to instantiate your client, table and a list of Person objects.  Finally, iterate over your collection and push it to the cloud.  That looks like this:

_client= new MobileServicesClient("https://yourapp.azure-mobile.net/", "yourkey");

var peopleTable = _client.GetTable<person>();
var people = Angie.FastList<person>();
foreach (var person in people)
{
    peopleTable.Insert(person);
}

And you’re set!  Run that bad boy, wait a couple of minutes or so, then check your Mobile Services table in the Windows Azure portal.

image

Going Further

You may have more complex data to set up, or you may even have requirements on how the properties need to be filled. For this, you can use the fluent methods on Angie to tell her how you want the data created.

Here’s how you would get 100 users worth of scores in a leaderboard on Windows Azure Mobile Services:

var entryTable = _client.GetTable<leaderboardentry>();

var entries = Angie.Configure()
    .ListCount(100)
    .FillBy("UserName", delegate() { return string.Format("{0}{1}", Susan.FillFirstName(), Susan.FillLastName()); })
    .FillBy("LastUpdated", delegate() { return Susan.FillDate(DateRules.Within1Year); })
    .MakeList<leaderboardentry>();

foreach (var entry in entries)
{
    entryTable.Insert(entry);
}

Next Steps

Okay, time class participation. These are early versions of these libraries but you can help make them more awesome.  Pop over to GitHub and fork and contribute!

I’ve also written a primer on using AngelaSmith here on my blog.

Good luck!