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

Samedi.NET - “Mocking, où comment tester ce qui est difficile à tester”

If you want to download the slides, they are available here.

You can then download them as PPTX, JPG, PDF, etc…


Categories: presentation
Permalink | Comments (0) | Post RSSRSS comment feed

Introduction to MVC 4 Beta – What I should know, what’s new and should I upgrade now?

What’s new?

A ton of stuff. We are talking here about the WebAPI, async support with the new .NET 4.5 async keywords, async HttpModules and HttpHandlers, Bundling and minifications, Single Page Applications (referred to as SPA), mobile project templates and the integrated AzureSDK.

Wow. That’s a pretty big release isn’t it? Let’s go through all those items one by one and give you all a small explanation of what it is.

WebAPI

WebAPI is an attempt by Microsoft to make the HTTP protocol a first class citizen. It looks like WCF (basic HTTP binding) but it’s not. In fact, it’s not using any of the WCF assemblies. Then, it uses the routes of MVC… but it’s not a content rendering engine.

WebAPI is a new service API to render service data based on the HTTP request. As an example, if you do send the HTTP header “Accept: text/json”, it will return JSON. No more mentioning that in the URL anymore. It’s the closest we have ever been to a RESTful service. Bonus point, it doesn’t use the JSON encoding of WCF (which was awfully slow) but the one from NewtonSoft (JSON.NET).

Bundling and Minification

Remember the previous post I did on how to bundle and minify your JS and CSS files for MVC3? Well now it’s integrated. You don’t need to do that anymore. It’s part of the default template. No more custom package from me. You compile and it works.

The advantage of this technique is that you can now upgrade your jQuery library without having to change its reference in the _Layout.cshtml or your masterpage. It will be automatically upgraded. The team as already received the feedback that the invocation call to the “ResolveBundleUrl” was a tad too long so no point in complaining.

Single Page Application

This is the first draft to making web pages in a single page. They are using knockout.js for the client-side data-binding and rendering, upshot.js for the JavaScript data access layer, WebAPI on the server side and jQuery for the goo that holds the world together. This deserves a whole post by itself but it’s a very promising technology.

Mobile Project Templates

A new project template based on jQuery Mobile. This will make your web pages look like a native mobile application. The UI is touch optimized, and easy to get the hang with.

AzureSDK

All ASP.NET projects now comes with the ASP.NET Universal Providers and will by the same time allow you to upload any web applications to the Azure platform without much modification to your application. This will reduce the friction between how we develop applications for the cloud and how we develop applications for a single server.

Should I upgrade now?

Of course not. This is all but a beta and most of you won’t need any of those new technologies immediately. However, the core MVC remains the same and you could easily upgrade to the best and latest and enjoy the new features.

Please be remembered that it’s only a beta and nothing in the API is promised to stay exactly the same. However, if you are ready to take a controlled risk, Microsoft has given it a “Go-live” license and you are just a few minutes away from running the best and latest from MVC.

Wait… you forgot the async stuff

Yeah… It’s pretty much the same as before but with the new keywords. I would new a whole new post to display those.


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

Browser Detection is bad. Feature Detection is better.

Context (Or a little bit of history)

Those who did websites in the beginning of the decade had to work with IE6, Netscape Communicator/Navigator and Opera. Some more browser introduced themselves along the years but most supported different things.

Netscape supported the blink tag (oh how I hate thee). Internet Explorer supported ActiveX and Opera was not popular enough to think about it.

We were in an era where people thought of the web as the blue “E” icon. People were not aware of browsers that much and those who had Netscape probably had it from an AOL promotion.

Since we wanted to display the same thing to every users as much as possible, people either started detecting browsers to clearly say on which browser their website is supported or they just didn’t do any checking at all!

That’s the main reason some internal web applications still display “Works better with IE6”.

Browser Detection

Browsers back then differed a lot from each other. So we had to know if we could use ActiveX or whether we wanted to piss off our users with a blink tag.

The rendering of all this of course was different per browsers.

Here is the script to detect which browsers you are running. I will not copy it here (too large) but you can see that it grows.

Once people knew which browser was running, they knew which feature was supported! So everything was perfect, right?

Not exactly. What if the feature was deprecated in the next version? What if the browser had that functionality disabled by an option? What if a new browser that your script don’t know come in? Why couldn’t he use that feature if he supported it?

This caused a lot of problem. Mostly because detecting a browser didn’t guarantee you anything beside that the user was sending you a UserAgent string that pleased you.

The browser detection was broken from the start and something had to be done to detect whether something was going to work or not. Irrespectively of the browser.

Feature Detection

Then came feature detection. The first real push for it was by Mr. John Resig himself when he posted “Future-Proofing JavaScript Libraries”. Today, jQuery allow developers to access a ton of features that would have taken individual developers months to develop and maintain. jQuery allows you to implement binding of events without knowing whether you should use attachEvent or addEventListener.

If you have the time, go see the development version of jQuery. It’s commented and will allow you to find their hacks to offer everyone the same functionalities. This allows you to manipulate the browser without having to know which one it is. It allows you to do Ajax in IE6 with ActiveX or with IE7 (or higher) with the proper object without knowing if your browser supports ActiveX.

Today, assuming everyone use a frameworks which smooth the basic differences between the browsers, the only thing you might be checking nowadays is HTML5 feature compatibility.

Introducing Modernizr

Modernizr is a library which does Feature detection and that can be tailor cut to your needs. In its complete version, it allows you to detect easily the following features (not a complete list):

  • SVG/Canvas support
  • Web sockets
  • Web SQL Database
  • Web workers
  • HTML5 Audio/video
  • Hash Change event
  • WebGL
  • Geolocation
  • Much more…

Modernizr once referenced in your webpage allow you to tailor your own code to know if you should gracefully degrade some feature or not.

Here is an example on how you could use Modernizr when implementing geolocation in your application:

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geolocation.js',
  nope: 'no-geolocation.js'
});

This simple code allows you to load a different JavaScript based upon the feature of a browser.

Modernizr offer support for IE6+, FireFox 3.5+, Opera 9.6+, Safari 2+, Chrome, iOS, Android, etc.

Conclusion

With the current quantity of browsers that supports different functionalities at various levels, we should not be implementing for specific browsers but rather for specific features. We would want those feature implemented in all browsers but with the fragmentation of the browser market, it’s just not going to happen soon.

So please, no more “This site works better with [INSERT BROWSER]”. Target a feature, test for it, and offer different (or no) implementation if the feature is not available. This will make your code cleaner and more efficient.

So stop the Browser detection madness and embrace the feature detection.

It might sound counter intuitive to some but it makes sense. So be ready for the future.

If you are using HTML5, use feature detection rather than browser detection.


Categories: jquery | opinion | productivity
Permalink | Comments (0) | Post RSSRSS comment feed

MVC Night in Ottawa with MVP Maxime Rouiller

I will be talking about MVC and it’s environnement today at the OttawaCommunity.net in… Ottawa.

For those who attended, or about to attend, here are the slides that are going to be used:

The Slides


Categories: community | presentation | event
Permalink | Comments (0) | Post RSSRSS comment feed

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

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).


Categories: design | css
Permalink | Comments (0) | Post RSSRSS comment feed

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


Categories: jquery | presentation
Permalink | Comments (0) | Post RSSRSS comment feed

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.


Categories: software
Permalink | Comments (0) | Post RSSRSS comment feed

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


Categories: mvp | community
Permalink | Comments (0) | Post RSSRSS comment feed

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!


Categories: mvc | jquery | ajax
Permalink | Comments (0) | Post RSSRSS comment feed