ASP.NET MVC 4: What else?

Even ASP.NET MVC can be improved. Dino explains the value of templates, and makes a case for the productivity gains that could come if there was a way of making more interactive custom templates that are honed for your own particular requirements.

You’ve probably, quite a few times, seen that commercial in which George Clooney praises a coffee machine and ends wondering what else if not that one. Paraphrasing the sentiment for ASP.NET MVC, I’m totally in favour of ASP.NET MVC. When it comes to Web development for the IIS platform, what else if not ASP.NET MVC?

However, when it comes to the ASP.NET framework I look into the latest ASP.NET MVC bits and wonder what else could be added to it to make it even better? In terms of technology and solutions I really believe that ASP.NET MVC is close to the top. And probably it was close enough to the top already with ASP.NET MVC 3.

Version 4 adds a few new features such as bundling and minification of script files, facilities for asynchronous coding, and the popular Web API. However, all of these are improvements to the ASP.NET platform as a whole and can be applied to Web Forms as well as ASP.NET MVC. There’s just one aspect that is really new in ASP.NET MVC 4, applies only to it and definitely makes ASP.NET MVC a much better product-mobile display modes. In this article, though, I don’t plan to cover mobile display modes. Instead, I do intend to focus on an aspect of ASP.NET MVC development that I reckon Microsoft seems to neglect a bit: the organization of ASP.NET MVC projects and subsequently overall quality of the code produced. So this article aims at dissecting the code of the basic project template emphasizing both the good and the bad.

Why Do I Want a Project Template?

I always liked project templates and wizards to create ad hoc skeletons of applications. Too many years ago I was leading a group of ten developers responsible for a set of applications and tools to back up a photo and imaging platform. We were creating new small applications all the time; we wanted to have the code standardized in terms of naming and structure but also we wanted applications to be standardized and similar looking in terms of graphics and features. It was the 1990s; so there was no web, no CSS and no designers around.

I spent my first few weeks in the new role creating a bunch of Visual Studio MFC wizards for the people to create new applications in a fraction of the time, at the same speed (or even faster) than with copy-and-paste, but working on a brand new project every time.

The wizard I created for Visual Studio 97 (or sort of) asked a few basic questions to the developer; simple questions like “do you want this feature” or “tell me the prefix to use while naming classes.” In a few seconds, the new application was ready and running. Today every Visual Studio developer can achieve the same by choosing one of the project templates that come with ASP.NET MVC.

Project templates, however, are not very interactive. You can hardly specify whether or not you want a certain feature and how you want a given section of the application to be organized. Sure, you can choose among a few predefined templates but, hey, that’s just the problem. They are predefined and they are limited. And adding more and more predefined templates adds noise and confusion to the Visual Studio dialog box of templates. Microsoft seems to be on the right way here with the introduction of Custom MVC Templates. You can read more about Custom MVC Templates here: http://bit.ly/10aWq8Z. Basically, the latest Visual Studio 2012 Update offers the option of creating comfortably custom project templates using the Visual Studio 2012 SDK.

Especially now that you’re going to have this additional option, why do you use a project template and why should you consider creating your own?

A project template is the starting point of a new project, gets you the scaffolding you need and saves you a bit of time (and annoyance) whenever you use it. The gray area is the definition of “scaffolding”. I believe that the key to a successful template is how much you make customizable the addition of new features. ASP.NET MVC offers Empty, Basic, Internet, Intranet, Mobile, Single-Page templates.

Honestly, they have more of examples than templates. 90% of the time I use the Basic template; remaining 9% of the time I use the Empty template. I’ve used the Internet template very rarely. I’ve never used for business even the Mobile template even though building mobile sites is my core business at this time.

What’s wrong with these predefined templates?

Somewhere Beyond the Basic Template

As I see things, a template is a pattern used to replicate the same structure; as such, it must be extremely simple in its implementation while it can represent even a fairly sophisticated structure. The Empty template is just perfect; but its structure is extremely simple. Here are the main characteristics:

  • No controllers
  • No views
  • No view model classes
  • App_Start folder
  • A too long list of assembly references and Nuget packages (most of which are just useless)

The Basic template, instead, gives you a bit more. It gives you:

  • A view layout
  • A indefinitely long list of script libraries (I usually drop all of them except jQuery and then re-add whatever I may need)
  • A basic style sheet

The Basic template is too basic as it would need at least one controller with one method to produce a realistic skeleton of a web application. It turns out that for each and every project you need to perform always the same steps:

  • Add a new controller class
  • Add the controller subfolder under the Views folder
  • Manage in some way the layers you may (actually, should) have underneath the controller class

In addition, there are projects in which you need some additional features such as localization, authentication plus some bootstrapping code for mobile features and controller-specific adapter classes to better bind the front-end with the back-end.

It’s easy to see that the last two options are quite hard to generalize to a pattern that suits a wide audience of developers. For this reason, I really love to have the ability to create my own templates. The first two-localization and authentication-instead are general enough to be addressed in an out-of-the-box template. Localization isn’t really hard to do. All it takes is a Resources folder with a built-in RESX file whose entries are referenced from within the views. This gives the structure one needs and also teaches a method to newbies.

Teaching a method is key, and I’m not sure this is what you find in richer templates such as the Internet Application template. The Internet Application template does provide a built-in infrastructure for authenticating users. Nicely enough, in ASP.NET MVC 4 this template also supports authentication through external OAuth-based services such as Twitter and Facebook. Is it really reusable?

1714-Fig01.png

Figure 1: the authentication example

As I see things, what you get from the Internet Application template is a working solution that is great if it hits your nail just on the head. Otherwise, it may easily be a waste of time. Let’s focus on the authentication example. You edit the basic files by linking the authentication layer to your Twitter or Facebook application and compile the sample project. You get what’s in Figure 1. The code just works; user credentials are validated; the authentication cookie is created. Except that user information is transparently stored in a local MDF database created in the App_Data folder. Is this a bad thing?

Most of the time, grabbing the Twitter or Facebook name of the logged user and saving it as your application’s user is precisely what you want to do. However, the Internet Application template binds you to a particular membership infrastructure-the simple membership provider as implemented in Web Pages. At the end of the day, the entire authentication infrastructure you obtain from the template comes from Web Pages. It may or may not work in all cases. It doesn’t work for me; but I assume it can work for other development teams.

The bottom line is that project templates are a fantastic thing as long as you can tailor them to your needs. When the project template offers you a “sample” instead of a “template”, well, it just misses the goal and doesn’t teach you a method because the solution is too specific. The ability to create custom template that comes with recent Visual Studio 2012 Fall Updates is more than welcome and I definitely plan to cover that in a future article.

Where Templates Do a Good Job

Let me share an example of where, in my opinion, project templates in ASP.NET MVC 4 do a good job of teaching an effective programming method. Nearly any web site needs to do some work upon application startup. Except those situations when the startup work is really hard and expensive, you usually add initialization code to the Application_Start method of the global.asax code-behind class.

By the way, when the startup work is really a time-consuming operation you might want to consider a different approach based on the warm-up module of IIS. This module is used to run an ASP.NET component that preloads and caches any required data. The warm-up ASP.NET component is a class that implements the System.Web.Hosting.IProcessHostPreloadClient interface. You can read more about it here: http://bit.ly/6stQJ.

Whether you use a preloader or the Application_Start method, however, the big trouble is organizing a possibly long list of actions in a way that is both readable and easy to maintain for developers. Up until ASP.NET MVC 4, the following was the typical startup code you got from project templates:

The two methods were usually inserted as helper routines in the same code-behind class. They were marked public and static for the sake of testing. This was probably a good approach for basic sites with just the need of setting up routes upon startup. For more sophisticated (and common) forms of initialization-things like caching data-this approach could lead soon to rather bloated code.

A better and cleaner approach is found in the template code for ASP.NET MVC 4. Here it is:

All xxxConfig classes are static classes each saved to its own file; all xxxConfig files are located by default in a new project folder: the App_Start folder. The pattern is very clean: for each new task you need to perform at the application bootstrap you create a new xxxConfig class and call one of its methods from Application_Start. This keeps logic very well separated and easy to extend while saving the global.asax file from becoming bloated. Here’s the default content for RouteConfig:

As you can see, it’s the same content you would have found right in global.asax until ASP.NET MVC 3.

Controller Classes

In ASP.NET MVC 4, you are allowed to create controller classes in just any folders of the project. Up until ASP.NET MVC 3, you were forced to create controller classes rigorously under the Controllers folder. As far as views are concerned, instead, you still must create a Views\XXX folder where XXX matches the short name of the controller class. You can circumvent such a limitation only using a custom view engine that internally recognizes view files from alternate paths.

Summary

ASP.NET MVC comes with project templates and that is where most developers start from. In my opinion, project templates can be improved and transformed into tools to teach a method to just about every developer. Today, it ends up that seasoned developers use their own templates and other developers spend a lot of extra time to fix what Microsoft could deliver more appropriately. If there’s an aspect of ASP.NET MVC that I like to be improved are project templates; but the release of an SDK for creating custom templates is anyway great news. Stay tuned for more information on that.