Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

Javascript and CSS Minifying/Bundling with the Microsoft.Web.Optimization Nuget package

So I’ve been wanting to write about this since the build and only gotten around to do it now.

When you write C# code, you rather have multiple small files with clear separation of concerns. This allow you to have small and clear classes and the compiler will never complain about it. However, in Javascript, you want to have smaller files. Most of the time in the .NET environment, there wasn’t any integrated way of doing so. Either it required an EXE call or outputing .min.js files.

This caused problems as we had to alter our Development version of our HTML to fit our Production environment. Microsoft released this tid bit early because it’s probably going to be integrated in the .NET 4.5 framework but is making it available to us now.

Please be aware that “Microsoft.*” DLLs are not part of the official framework and when they do, they will probably be changed namespace to “System.*”.

Pre-requisites

First, you will need NuGet to install the following packages:

  • Microsoft.Web.Optimization
  • WebActivator

How it works

Now, the way the JS/CSS minifying works is that it will dynamically inspect all your files, read them, minify them and then cache the result to be served later. This allow us to modify our files and have all the files re-minified. When one of our JS/CSS file get modified again, this process will restart until either the cache expire or a file change.

Setting up the base work

For the minify-er to work, it will require the registration of an HttpModule. It’s not already included in the Microsoft.Web.Optimization package but it will be necessary for us to add it if we want it to work.

using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Microsoft.Web.Optimization;
using MvcBackbonePrototype.Bundle;

[assembly: WebActivator.PreApplicationStartMethod(typeof(MvcBackbonePrototype.AppStart.BundleAppStart), "Start")]

namespace MvcBackbonePrototype.AppStart
{
    public static class BundleAppStart 
    {
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof (BundleModule));
            RegisterFolders();
        }

        private static void RegisterFolders()
        {
            // configure Microsoft.Web.Optimization
        }
    }
}

The previous code will do the following, when your application start, it will register a dynamic HttpModule.

Now that the base work is done, we’ll jump right ahead to the configuration of the folders.

Configuring the package

Now that the HttpModule is properly registered, we need to tell the Module when to activate itself. In my specific scenario, I wanted to have jQuery, underscore.js and Backbone.js in that specific order.

By default, the Module will load most core frameworks first (jQuery, MooTools, prototype, scriptaculous) and then load the rest of the files that doesn’t match the wildcards after. The filters are done so that jQuery plugins will load after the jQuery core library and jQuery UI will load after jQuery.

However, there is nothing done for underscore.js and Backbone.js.

private static void RegisterFolders()
{
    var js = new DynamicFolderBundle("js", typeof(JsMinify), "*.js", false);
    BundleTable.Bundles.Add(js);
}

The previous code correctly configure the module to minify all files in a folder by just adding the suffix “js” to the folder (eg.: /Scripts/js).

However, it will register the the other modules in alphabetical order rather than the proper order.

Let’s fix that.

Custom Orderer

public class BackboneOrderer: DefaultBundleOrderer
{
    public override IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
    {
        context.BundleCollection.AddDefaultFileOrderings();

        var backboneOrdering = new BundleFileSetOrdering("backbone");
        backboneOrdering.Files.Add("underscore.*");
        backboneOrdering.Files.Add("backbone.*");
        context.BundleCollection.FileSetOrderList.Add(backboneOrdering);

        return base.OrderFiles(context, files);
    }
}

We first inherit from the default order. Then, we add the default file ordering which will take care of the jQuery ordering for us. Then, we add the other files that we require to the list. The only thing left is to alter our RegisterFolders method to fix that.

private static void RegisterFolders()
{
    var js = new DynamicFolderBundle("js", typeof(JsMinify), "*.js", false);
    js.Orderer = new BackboneOrderer();
    BundleTable.Bundles.Add(js);
}

That’s it. We are nearly done!

Modifying your _Layout.cshtml / masterpage

My masterpage head section first looked a lot like this:

<script src="@Url.Content("~/Scripts/Framework/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Framework/underscore.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Framework/backbone.min.js")" type="text/javascript"></script>

This was of course replaced by the following:

<script src="@Url.Content("~/Scripts/Framework/js")" type="text/javascript"></script>

And that’s all! All your files will be minimized, bundled and properly cached.

Bonus

If you want to have your URLs with a “version number” on it, I suggest that you use the following methods to resolve your URLs instead of the MVC way:

<script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/Framework/js", true)"></script>

Categories: asp.net | nuget | mvc
Permalink | Comments (0) | Post RSSRSS comment feed

Is the Ajax Control Toolkit dead?

So I’ve got an engagement to speak about Ajax with Visual Studio 2010. Of course, I’m talking about jQuery but there is obviously the Ajax Control Toolkit available for the people who are still on ASP.NET WebForm.

With such a huge focus right now on ASP.NET MVC, is the Ajax Control Toolkit still relevant?

The website is still there, the link toward the forums doesn’t work anymore and of course there is this gem :

AJAX Control Toolkit Release Notes - September 2009 Release Version 3.0.30930

We are 1 year and a half since the last major release. Of course, the CodePlex project is still there but the reviews are not encouraging me to use it.

Hell, the project could not even be mentioned as actively maintained anymore. One commit a month is hardly what I call support for such a project.

So the question remains… is it still relevant today? Will it ever be updated in the future?


Categories: asp.net | ajax
Permalink | Comments (0) | Post RSSRSS comment feed

Using Ninject with ASP.NET MVC 3 dependency injection

Ninject is my favorite container for doing dependency injection. However, it always seemed a bit complicated to use with ASP.NET WebForms.

Things have improved with ASP.NET MVC 1 of course but now, with the release of ASP.NET MVC 3, things have become way easier to do.

Here is what my Global.asax.cs looks like when I want to register an IoC tool for ASP.NET MVC 3:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterDependencyResolver();
}

private void RegisterDependencyResolver()
{
    var kernel = new StandardKernel();

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

Well that look easy enough no? Well, to be fair… NinjectDependencyResolver doesn’t exist. It’s a custom class that I created to allow the easy mapping of the Kernel.

The only thing it needs is the Ninject StandardKernel. Once all the mappings are done, we give the kernel to the resolver and let MVC handle the rest.

Here is the code for NinjectDependencyResolver for all of you to use:

public class NinjectDependencyResolver : IDependencyResolver
{
    private readonly IKernel _kernel;

    public NinjectDependencyResolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    public object GetService(Type serviceType)
    {
        return _kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _kernel.GetAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }
}

Categories: asp.net | mvc | ninject
Permalink | Comments (5) | Post RSSRSS comment feed

ASP.NET MVC - How does the Html.ValidationMessage actually work?

When you create a basic ASP.NET MVC application, you normally will have "Html.ValidationMessage" inserted automatically for you in the Edit and Create views. Of course, if you try to type strings in a number field, it will fail. Same things for dates and such. The good question now is... how does it do it?

Well, the ValidationMessage method only look to see if the model you gave him with the name given have received errors. If it did, it will display the specified message. So now that we covered the "How", I'll show you where it does that.

The answer lies within the DefaultModelBinder that comes activated by default with ASP.NET MVC. The ModelBinder do a best guest to fill your model with the values sent from a post. However, when it can match a property name but can't set the value (invalid data), it will catch the exception and add it as an error in a ModelStateDictionary. The ValidationMessage then picks up data from that dictionary and will find errors for the right property of your model.

That's it! Of course it's pretty simple validation and I would still recommend you to use a different validation library. There is already a few available on the MVCContrib project on CodePlex.


Categories: asp.net | mvc
Permalink | Comments (0) | Post RSSRSS comment feed

Simple explication of the MVC Pattern

Since the last time I wrote a blog post was more than a few months ago, I would like to start by saying that I'm still alive and well. I had changes in my career and my personal life that required some attention and now I'm back on track.

So for those that know me, I was participating to the TechDays 2009 in Montreal and presenting the "Introduction to ASP.NET MVC" session. I will also be presenting the same session in Ottawa (in fact this blog post is written on the way to Ottawa with Eric as my designated driver).

So what is exactly ASP.NET MVC? It's simply the Microsoft's implementation of the MVC pattern that was first described in 1979 by Trygve Reenskaug (see Model-View-Controller for the full history).

So in more details, the MVC is the acronym of Model, View and Controller. We will see each component and the advantages of having them separated properly.

Model

The model is exactly what you would expect. It's your business logic, your data access layer and whatever else is part of your application logic. This I don't really have to explain. It's where your business logic will sit and therefore should be the most tested part of your application.

The model is not aware of the view or of the controller.

View

The view is where sit your presentation layer for your application. In a web framework, this is mostly ASPX pages with logic that is limited to showing the model. This layer is normally really thin and only focused on displaying the model. The logics are mostly limited to encoding, localization, looping (for grids) and such.

The view is not aware of which controller invokes it. The view is only aware of the model to display.

Controller

The controller is the coordinator. It will retrieve data from the model and hand it over to the view to display. The controller can also be associated to other cross-cutting concerns such as logging, authorization and performance monitoring (performance counter, timing each operations, etc.).

Advantages

Now, why should you have to care about all that? First, there is a clear cutting separation between WHAT is displayed to the user and HOW you get the information to display. In the example of a web site, it become clearly possible to display different views based on the browser, the device, the capabilities of the device (javascript, css, etc...) and any other information available to you at the moment.

Among the other advantages, it's the ability to test your controller separated from your view. If your model is properly done too (coding against abstraction and not implementations), you will be able to test your controller separated from your model and your view.

Disadvantages

Mostly a web pattern than a WinForm pattern. There is currently no serious implementation of the MVC pattern for anything else other than web frameworks. The MVC pattern is hence found in ASP.NET MVC, FubuMVC and other MVC Framework. Thus it limits your choices to the web.

If you take a specific platform like ASP.NET MVC, other disadvantages (that could be seen as advantages) slips in. Mostly, you lose any drag and drop support for server controls. Any grids are now required to be hand-rolled and built manually instead the more usual abstraction offered by the original framework.

Conclusions

Since we mostly require to have a more fine grained control over our view, the abstraction offered by the core .NET Framework are normally not extensible/customizable enough for most web designers. Some abstraction might even become unsupported in the future and thus bringing us to a more precise control of our views. The pattern also allow us greater testability than what is normally offered by default in WebForms (Page Controller with Templating Views).

My recommendation will effectively be a "it depend". If an application is already built with WebForms and doesn't have any friction, there is no point in redoing the application completely in MVC. However, for any new greenfield project, I would recommend at least taking a look at ASP.NET MVC.


Categories: architecture | asp.net | mvc | pattern
Permalink | Comments (0) | Post RSSRSS comment feed

5 reasons why you should use ASP.NET MVC

I'll be fair with you readers. I've only toyed with the ASP.NET MVC framework. It looks great as of now but it's the first full blown MVC framework that we have that is backed by Microsoft. However, there is a lot of opposition nowadays that tend to be formulated like this:

Why should I use ASP.NET MVC? WebForms works well.

Other problems come from the lack of server controls. When a developer look at that and he then wonder why he should have to write HTML and Javascript when before he could have retrieved all that beautiful information with a simple postback.

So without ranting any further, here is 5 reasons why you should use ASP.NET MVC.

1. Testability

When the MVC model is properly applied, it allow for a better separation of your business logic and your presentation code. If the view is not included inside your model, you can easily test without requiring a web server. By default, when starting a new MVC project, Visual Studio offer to create a new Unit Test project based on Microsoft's Unit Test framework. Other Unit tests framework can also be configured to be used by default instead of Microsoft's solution.

The way the code is also made, the controller is the one handling the calls from the route. They can be instantiated outside of a web request which makes them easy to test too.

2. Perfect control of the URLs

ASP.NET MVC use URL Routing to better control the request and forward them to your controllers. Instead of 1 to 1 mapping, they allow pattern matching. The default being "{controller}/{action}/{id}" with the default being "Home/Index". This technically allow you to set the URLs exactly how you want. You don't have to create folder for every level deep it goes. The URL routing allows you to make clean URL that will be easy to remember.

Would you rather try to remember http://localhost/Sales/DisplayProduct.aspx?ProductID=23213 or http://localhost/Product/Detail/23213 ? Even better, if you are an e-Commerce site and want some fast link.... you can directly bind those URL to http://localhost/23213 to make it more easy to remember. Doing that in WebForm while keeping all this unit testable would just be too time consuming now is it?

3. Better Mobility Support

In WebForm, you would have to detect on each page that the browser is a mobile and adapt your rendering for the mobile on each and every form. You could also redirect the user to different page when it's a mobile. What is excellent with MVC is that it's not the view that is receiving the request. It's the controller. The controller can then dynamically decide which view to render while keeping the same URL. So to see a product view, you don't even need to send different URL to different provider. You just detect which device you are handling and redirect it to the proper view. As you support more and more mobile device, you can keep on adding view that are more specific to each device. Want to support this new HTC? Create a view, detect the browser and ensure the right view is displayed. Want to support some iPhone goodness with some device specific HTML? Create the necessary view, reuse the browser detection and display the view.

You can keep on doing that ad infinitum and as much as you want depending on your audience. Having Mobile support now is more convenient than it has ever been.

4. View Engines

Now if you only built ASP.NET WebForms, this term might be weird for you. Let's just say that you have been using the same view engine all this time without wondering if you could choose. The WebForm view engine is... well... what you have been using all this time. This includes server tags (<% %>), binding tags (<%# %>) as well as control tag (<asp:TextBox ... />).

The Spark Engine is a good example. MvcContrib also offer 4 different view engine (Brail, NHaml, NVelocity, XSLT). Each of those engine are created to fix some specific problems. Different view engines can be used on different view. One page could be handled with WebForm view engine, one with Spark Engine, one with XSLT, etc. Different view, different problem different solution.

You might not have to use those, but the simple fact that they are available will make your life easier if they are needed.

5. Built-in and shipped jQuery support

Let's keep the best for the end. jQuery is shipped with any new project instance of ASP.NET MVC. Since Microsoft announced support for jQuery, it's been the big buzz in the javascript world. Since ASP.NET MVC don't rely on Postback, a strong javascript framework is needed to provide for all the UI the previous server control were offering. jQuery easily offer you AJAX, DOM manipulation, event binding and  this across browser.

Of course, jQuery is not an advance to MVC itself. But it is a serious offering from ASP.NET MVC. No more download or "I'll write my own" stuff. I don't know for all of you but if I have to do javascript, I normally do a document.getElementById. This will work in most browsers but as soon as you start going funky, some browser will misbehave. jQuery simply allow you to write $("#myControlId") or many more shortcuts to simply do what you need across browsers. Just by having jQuery available stops me from writing incompatible code.

Conclusions

Lots of point goes toward MVC. Way more could be added. You certainly don't want to miss Kazi Manzur Rashid's blog about ASP.NET MVC Best Practices (part 1, part 2). Scott Hanselman, Phil Haack also have great posts about ASP.NET MVC.

Don't be fooled. Web Forms are not necessarly evil. They just aren't leading you to a pit of success.


Categories: architecture | asp.net | c# | mvc | unit test
Permalink | Comments (11) | Post RSSRSS comment feed