Decaying Code

Where code comes to die

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>

How to insert page breaks in printed web pages using only CSS?

So one of my co-worker had to print a “report”. I say report but it’s more like they wanted the page printed but just more compact and less fluffy/pretty content. Like always, people tend to bring solutions instead of problems and they asked me how long it would take me to do that in SSRS.

Of course, I gave my evaluation on how long it should take but then… we stumbled into problems. My co-worker only have Visual Studio 2010 installed. SSRS requires you to have BIDS which uses Visual Studio 2008. Then, we have SQL Server 2008 R2 installed on our machine but no-R2 on our deployment server. This quickly became a mess.

Then after taking the time to look at the problem, we asked: “Why couldn’t we just print the web page?”

Well for starters, the requirements we had was there was a need for a page break at certain predictable location.

After searching a bit, I came up with this solution directly from W3C (and a bit other sources).

@media print {
    .pagebreak {
        page-break-before: always;
    }
}

And that’s it. Just add the class to the element that should be on a new page and it works.

Now, what about compatibility you say?

It should be compatible with IE (all current versions down to 6), FireFox (all latest versions), Chrome (tested on v16) and Opera (all versions).

DevCamp Montreal 2011– jQuery Presentation

For those who will attend tonight’s presentation fast talk on jQuery, here is my presentation file that I will be using tonight.

It’s available for download by clicking the link bellow!

Download the presentation file here

Siberix – Footer row higher than they should be

So I’ve had to build some reports with Siberix in the last few days and I had some less than pleasing results. I had a grid that was overflowing vertically but for some reason, the last row on the page would take 2-3 times more space than necessary.

After printing the page and looking at the results many times… something clicked when I saw the footer row that I had added. The blank space that was left was exactly the same size as my footer.

So maybe it’s a bug, maybe it’s not but Siberix let’s itself some room on every page to render the footer “in case” that it’s the last page. No concept what so ever of where he’s at when rendering the PDF.

The solution? Make the footer outside the IGrid and it won’t glitch anymore. And yes, I tried to set the IFooter.Repeat to false.

I can understand that a product have bugs but the worst part is that it’s a paying tool and no community built around it like Telerik, ReSharper or other third party tools. My last try was with Stackoverflow but didn’t have any luck either.

Siberix, if you want to increase your sales, make sure you have a community behind it. Just a friendly advice.

I’ve just been nominated ASP.NET MVP

First of all, I’m extremely happy with my nomination as an ASP.NET MVP. I did a lot of presentations in the past 2 years and I’m happy that I’m considered for this award.

MVP

I would like to thank everyone who nominated me and helped me get where I am today.

Mario Cardinal helped me by backing me with the nomination. Éric De Carufel is also a big part of my nomination since we started a small group (ALT.NET) more than a year ago. Since then, we’ve been working non-stop in presenting and “one-upping” each other. I would also thank Joël Quimper for his help and my boss Yves Forget for helping me give time to those presentations.

Most of my presentations has been done at the .NET Montreal Group so I would lastly thank Guy Barette for the opportunities he gave me as well as the inclusion of our group inside the big .NET Montreal community.

So I’ll be participating more in the following months and I will push ASP.NET as hard as before within Montreal.

Thanks again,

-Maxime Rouiller

Ajax with jQuery and ASP.NET MVC

Requirements

What should I learn first?

When doing AJAX with ASP.NET MVC, there is no “UpdatePanel” or high level abstraction that helps you do all the magic. You need to get your hands dirty. That means learning how to do actual JavaScript without having the framework do all the job for you.

My favorite tool is jQuery when it comes to JavaScript. It’s simple, small and allows you to do in a few line of codes in 5 minutes what would take me 3 days an 2000 lines of code.

What should be on your reading list?

Document Ready Event

First, do not forget to put any jQuery code inside the following snippet:

$(document).ready(function () {
    // all code need to go there.
});

Selectors

The three most important selectors (in my opinion) are the following :

Those three selectors will include around 80 to 90% of all the selector you will require. The others, you can pick up along the way!

Manipulation

Here, we are talking about manipulating elements from the HTML page. We will need those since they are required for removing and adding HTML into the page. It’s basically what the UpdatePanel for WebForms do but we’ll do it manually and be more specific in what we want.

Here what I consider essential :

  • remove() – Allows you to remove an element from the DOM. This is useful when wanting to remove an element directly.
  • append()/prepend() – Allows you to insert an element inside the selected tags (either before or after the existing elements of that tag)
  • replaceWith() – Replace the element with what’s given in parameters. When using this, make sure that the replaced element have the same usable selector or it will harder to reselect that element.

And now, we have nearly everything that we need to start being AJAX-y!

I already know all that, let me do AJAX!

So what’s the easiest with jQuery to do AJAX?

$.get()

This method will basically do an HTTP Get on the selected URL and return the data inside the success function callback.

Let’s say I want to add the result of my AJAX request to the following tag:

<div id="result">
</div>

It would be as easy as doing this :

$.get('/Controller/Action/', null, function (data) {
    $("#result").empty(); // clears the content
    $("#result").append(data); // append the data into the div
});

Wasn’t that easy?

The MVC Side

Of course, if your MVC Controller is returning an JsonResult, you could use $.getJSON instead and data would be an object instead of pure HTML. In fact, your controller can even return a simple string and it would work. But how do you make your controller returns only what you need? Actions can be split in 2 with MVC to respond differently whether the request is standard or an AJAX request. Here is what it would look like:

public ActionResult MyAction() 
{
    if(Request.IsAjaxRequest())
        return View("nameOfMyPartialView");
    else
        return View();
}

That’s it! And now if you want to return an object as JSON:

public ActionResult AnotherAction()
{
    if(Request.IsAjaxRequest())
    {
        // The following line return Json to AJAX requests
        return Json(new { name = "Maxime Rouiller"}, JsonRequestBehavior.AllowGet);
    }

    // we still return normal HTML to standard requests.
    return View();
}

I hope you enjoyed this small example. If you are still curious or if you are simply stuck with something, ask away!

NuGet + Visual Studio 2010 + TFS = Warning

Someone asked me if adding a package through NuGet to a Source Controlled project would add the folder “packages” to TFS.

Well I got the answer today and it’s “No”.

Make sure you go inside Source Control Explorer and add that folder. Make sure to also include everything since DLLs are normally excluded by default.

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?

Comparing Unity 2.0 to Ninject 2.2.0.0 in an ASP.NET MVC 3 project

Tools used

  • Ninject 2.2.0.0
  • Unity 2.0
  • Visual Studio 2010

Initial premise

The way to do Dependency Injection in ASP.NET MVC 3 is basically simple compared to previous versions. ASP.NET MVC 3 expose a static class called DependencyResolver. This class has one static method called SetResolver that takes into parameter an IDependencyResolver. This allows you to set a custom resolver that ASP.NET MVC 3 will you to instantiate your controllers with. Really easy stuff. As you can see, this is a really simple interface to implement.

Ninject

Ninject (an open-source tool) already comes with one since December 6th 2010. This allows you to simply set any configured Ninject StandardKernel as a parameter to the resolver and give it to the DependencyResolver.

Unity

Unity, however, doesn’t call it a DependencyResolver. The class we are looking for is UnityServiceLocator. Although it doesn’t seem quite apparent, it’s actually compatible with the DependencyResolver implementation and can be used with it.

Bindings

Ninject

Bindings with Ninject (without extensions) are done like this:

var kernel = new StandardKernel();
kernel.Bind<IHelloWorld>().To<HelloWorld>();

Unity

Bindings with Unity (without extensions) are done like this:

var container = new UnityContainer();
container.RegisterType<IHelloWorld, HelloWorld>();

This shows off how easy it is for both to setup.

Extensions

Ninject

There is a lot of extensions available on top of the actual Ninject project. Ninject is basically only caring about the basic bindings and let the extensions to handle the rest. There is extensions for everything. From injection, conventions, message broker, etc. Here is a few that are, for me, the most interesting:

Unity

There doesn’t seem to be any extensions available through Unity but rather be already included within the library itself. This might not be the best tactic as the releases of Unity are quite far away from each other and waiting for an update might take weeks or even months. Unity seems to be able to handle UnityContainerExtension but there is not much on the web that was developed by the open source community.

Which one to choose?

At that point, there isn’t much that differentiate both. It’s mainly a matter of taste whether you like on syntax or the other. However, on the extension side… there is a definite edge on the Ninject project.

Ninject project is definitely more active and you can see each and every modifications made in the source control on GitHub.

Simplifying Ninject Bindings with Ninject.Extensions.Conventions

So in my previous post, we talked about binding interface/abstract class to implementations with Ninject. It was a rather simple task and it allowed us to do the job quite easily.

But of course the example was a simple case and would never ever even look close to a real production project. A real production project might have 3-4 services with at least 2-3 dependencies each that might or might not be the same. This can easily explode when adding new functionalities to a software. Need to send email? Add a dependency on INotifier. Need to access another service elsewhere? Another dependency. This can grow quite big quite fast and it will be a pain to actually maintain all the bindings.

This is where “Ninject.Extensions.Conventions” (NEC) come and save us some time.

Let’s take the following code and binding from our previous example:

using System;
using Ninject;

namespace ConsoleNinject
{
    class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();

            kernel.Bind<IConsoleOutput>().To<MyConsoleOutput>();

            var output = kernel.Get<IConsoleOutput>();
            output.HelloWorld();

            var service = kernel.Get<Service>();
            service.OutputToConsole();

            Console.ReadLine();
        }
    }


    public interface IConsoleOutput
    {
        void HelloWorld();
    }

    public class MyConsoleOutput : IConsoleOutput
    {
        public void HelloWorld()
        {
            Console.WriteLine("Hello world!");
        }
    }

    public class Service
    {
        private readonly IConsoleOutput _output;

        public Service(IConsoleOutput output)
        {
            _output = output;
        }

        public void OutputToConsole()
        {
            _output.HelloWorld();
        }
    }
}

So we only have one line of binding. Now don’t forget that this line will explode to 4, 6, 10, 20 lines as things move forward. We want to simplify this to the most simplest case.

This line can be replaced with the following:

kernel.Scan( x=>
    {
        x.FromAssembliesMatching("*");
        x.BindWith<DefaultBindingGenerator>();
    });

However, running the code after that won’t work. Why? Because the DefaultBindingGenerator binds I{Name} to {Name}. Quite simple but it’s extendable.

So we need to change the name of our class MyConsoleOutput to ConsoleOutput and then everything works!

There you go! Now we can keep on adding interfaces and implementations without changing the actual binding codes.

On another note, you might want to change which assemblies are loaded for the conventions since this would load all DLLs in the executing directory.