Decaying Code

Where code comes to die

Nuget with custom package sources on a Build Machine

My build was failing due to moving to a new build machine. We do have custom packages that are used internally and they could not be found by NuGet on the new server.

This post might be more about me remembering where it is but the location of the package sources for NuGet is found here:

%APPDATA%\NuGet\NuGet.Config

Here is what mine looks like:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <add key="enabled" value="True" />
  </packageRestore>
  <packageSources>
    <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
    <add key="LocalFeed" value="C:\LocalPackages\" />
    <add key="MyCompany" value="\\myServer\NugetPackages" />
  </packageSources>
  <disabledPackageSources />
  <activePackageSource>
    <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
  </activePackageSource>
</configuration>

The same file can be found on the build server (with some options missing). The main part is the packageSources section.

If you are depending on a local repository or a different repository than the public NuGet Gallery, it’s where you need to update your sources to have your package available.

KnockoutJS vs jQuery – A wonderful team

KnockoutJS is an MVVM JavaScript framework for your browser. It allows you to easily bind raw data to a model and update elements bound to that model.

jQuery is a DOM manipulation framework that has made JavaScript not suck.

Both have their reason to exist and they should actually not compete. It’s all about using the right tool for the right job.

The problem

When building rich HTML page with a lot of input/tag manipulation, the most common manipulation is changing what is displayed. Be it the content of a text box or the content of a tag, we need to update those elements a lot. What we often end up is a lot of jQuery code that selects element and then updates it.

It becomes very quickly clear that increasing the amount of code would make it look like spaghetti code. Another big disadvantage of having all of your UI driven by jQuery is that you end up with a lot of selectors. Unless you are selecting by ID, tag or classes (and depending on your browser), selectors will eventually slow your browser.

So how do we fix spaghetti event binding and keep our head cool?

Fixing the problem with KnockoutJS

Let’s start with some basic HTML:

<div id="myModel">    
    <label>Firstname</label>
    <input type="text" id="firstname" />

    <label>Lastname</label>
    <input type="text" id="lastname" />

    <span><strong id="fullname">Displaying full name here</strong></span>
</div>

That’s the most simplistic example. We have a first name and a last name and we want to concatenate both of them into an tag to display the user and that, in real time. This might seem like an easy problem but keep in mind that real-life problems will actually be more fierce. With that said, let’s start coding.

What would that look like in jQuery?

$(document).ready(function () {
    $("#firstname").on('keyup', UpdateFullname);
    $("#lastname").on('keyup', UpdateFullname);
});

function UpdateFullname() {
    $("#fullname").text($("#firstname").val() + ' ' + $("#lastname").val());
}

We basically have no less than 5 selectors. All based on IDs so they are going to be fast but still… it’s five selectors. We could probably optimize things a bit but this is as close as production code I’ve seen in the wild. The trick for the real-time requirement in this scenario is the ‘keyup’ event. As we add more elements to our model we might have to add more event binding to invoke that function on other elements. Maybe other functions will require that same function too and you end-up with a flurry of selectors left and right with a big JavaScript file of 800 lines of code in no times.

What about KnockoutJS?

$(document).ready(function () {
    ko.applyBindings(new FullnameViewModel(), $("#myModel")[0]);
});

function FullnameViewModel() {
    var self = this;
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');

    self.fullname = ko.computed(function() {
        return self.firstName() + ' ' + self.lastName();
    });
}

Of course, for the KnockoutJS version to work properly, I have to change the HTML a little bit. I’ll also take the time to remove unused attributes (required by jQuery in this case) to work. Here is how it looks now.

<div id="myModel">    
    <label>Firstname</label>
    <input type="text" data-bind="value: firstName, valueUpdate: 'afterkeydown'" />

    <label>Lastname</label>
    <input type="text" data-bind="value: lastName, valueUpdate: 'afterkeydown'" />

    <span><strong data-bind="text: fullname">Displaying full name here</strong></span>
</div>

So what can we understand from that? Yes, it takes a bit more JavaScript to do the work but now, the whole “business rules” are actually encapsulated in one JavaScript function. If we need to reuse part of how the full name is built, it’s actually part of your model. It’s something you can write tests for. As more rules are added to the view model, less time is spent debugging which selector I am to use and more about writing business rules of our presentation layer.

Why should I go with Knockout?

  • If your application actually has some business rules that need encapsulating, Knockout will provide you an easy way to do it.
  • If you are unit testing your JavaScript, it is much faster and easier to test only the ViewModel without any actual HTML in the back. You could potentially run something like PhantomJS to test your ViewModels.
  • If you are going to reuse part of the model in other bits of HTML or simply if your HTML is still changing a lot
  • If you need to be able to serialize your whole model in JSON to send to the server.

What should I still use jQuery for?

  • Basic DOM manipulation/selection
  • Ajax requests
  • Effects and animation

Give KnockoutJS a try!

Try it out by going first to KnockoutJS.com and doing the live tutorial. It will be easy to get your feet wet. Then, use it in Visual Studio since it’s part of the template!

Easy deployment with IIS and Web Deploy with Visual Studio

You’ve probably all seen the Publish Method called “Web Deploy” in your Visual Studio 2010/2012 publish popup. On my end, I’ve used the classic “push to a local folder then copy/paste” method of deploying.

Today, I’m going to show you how to install it on your IIS and make it work with Visual Studio

Installing Web Deploy

The first thing to do is downloading the IIS extension and executing it. It should open the Web Platform Installer and suggest you the right version of Web Deploy and then click Install.

Then we need to go to IIS to confirm that it is properly installed. Right clicking on a Site should bring you this menu:

webdeploy_installed

Deploying through Visual Studio

IMPORTANT

You need to run Visual Studio as an Administrator for this to work.

Now when you try to publish an application through Visual Studio, select “Web Deploy” from the drop down and type in your URL.

Visual Studio 2010:

publishing_through_webdeploy

Visual Studio 2012:

publish_vs2012

In Visual Studio, you could always use the option called Build Deployment Package so that if you have to give a package to your sysadmin (or a client) to deploy, it can be done with single Zip and an package to import. Included in this package can be, folder authorization, registry keys that are required and more.

Why should I use Web Deploy?

  • You are not required to be an administrator on the server to publish an application.
  • Allow for partial differential deployment (only what changed)
  • You can push the database with Entity Framework and run migrations on the different databases
  • Synchronize web servers between themselves (IIS6/IIS7/IIS8)
  • Easily give a package for a client to deploy
  • Easily deploy from a Build server (Continuous integration)
  • Automatically backup before publishing

Conclusion

Web Deploy is already in V3 and barely been talked about in our spheres. Maybe we are too development oriented and are not looking at making our tasks easier. In any case, installing the web deploy extension on an IIS server should only take you a few minutes and will be worth it very fast by making your deployments easier than ever.

For more information, do not miss the MSDeploy blog. Or the initial blog post by Scott Guthrie… over two and a half years ago.

Introduction to NSubstitute

Moq has been for a long time my favorite tool to do mocking. Today, I’ll be introducing another tool I’ve recently start to use.

While Moq was more based around creating a mock, configuring it and then retrieving the object, NSubstitute is more about creating the object and then configuring it.

In NSubstitute, there is no direct concepts of Mock that is presented to the user.

As an example, here is a simple way to do a mock:

IProductRepository repository = Substitute.For<IProductRepository>();

That’s it. As of this moment, you have a mocked repository. Injecting it is very simple at that point.

Since we don’t have a Mock object to work with, how do we go and configure our mock to return what we want?

NSubstitute include an already familiar concept called "Extension Methods" to our users. The one that is going to be used the most is “Returns”. There is two available signature for Returns. Let’s see the decompiled signature for “Returns”.

public static ConfiguredCall Returns<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
public static ConfiguredCall Returns<T>(this T value, T returnThis, params T[] returnThese)

You return an instance that has already been built or you return a function that will build (or return) the instance at the moment of invocation. As for the array at the end, those are what is going to be returned/invoked in subsequent calls.

That’s really as simple as it get. Since mocking framework are supposed to be easy to use and not get in your way, I think that NSubstitute might have just taken the place of Moq for me as my go-to framework from now on. Simple, lightweight… I like it!

Installing NSubstitute

Website / Source / Nuget

Nuget command line:
Install-Package NSubstitute

Better JavaScript notifications with Toastr

A use case I’ve always been pondering about is how to create a small popup that will tell the user that an operation has succeeded or failed.

What I usually did is write by own Success/Error functions to handle displaying the message to the user. Integrate a bit of jQuery here, a bit of jQuery UI here, download a custom script there…

Recently, I’ve found Toastr. What is great about that tool is how it integrates with pretty much anything a designer can throw at you. CSS classes are replaceable, icons are defined inline in the CSS to avoid external dependencies on images, etc.

Basically, you don’t need the CSS file that comes bundled with it. You only need the JS file if you already got the style all figured out.

Here is how I configured it on my end :

toastr.options = {
    toastClass: 'myCustomDivClass',
    iconClasses: {
        error: 'error_popup',
        success: 'success_popup',
        info: 'info_popup',
        warning: 'warning_popup'
    },
    positionClass: '', // I position it properly already. not needed.
    fadeIn : 300, // .3 seconds
    fadeOut: 300, // .3 seconds
    timeOut: 2000, // 2 seconds – set to 0 for “infinite”
    extendedTimeOut: 2000, // 2 seconds more if the user interact with it
    target: 'body'
};

Basically, this will configure a basic DIV tag element and append it to the of the BODY tag. This is very important in some browser because in some scenarios, form elements might appear over the “toast”.

Another basic boilerplate that you might want to add to your code is this:

$.ajaxSetup({
    error: function() {
        toastr["error"]("<h2>An error has occured.</h2>");
    }
});

This will ensure that any AJAX errors that happens within jQuery is handled using Toastr.

Installing Toastr

Nuget Package / Source

Nuget command line:
Install-Package toastr

Hidden bug: Parameter passing

There is a bug in the following piece of code. The bug could potentially break behaviours.

private int ReturnDefaultYear(int? year)
{
    if (year < 1970) // LowerYearBound defined as a int elsewhere
        year = null;

    var result = year ?? 1970;
    return result;
}

Found it yet? I’ll give you a hint. When passing parameters in .NET, value types are copied (int, double, float, etc.) but reference type (string, nullable, etc.) have their reference passed around. So when you change them, their value is not lost when leaving the method scope. They are persisted up to the highest level.

In this scenario, the parameter that was passed for “year” would become null.

Try running this simple code in a Console Application and you will understand the problem:

class Program
{
    static void Main(string[] args)
    {
        int? test = 1;
        Console.WriteLine(ConvertTest(test));
        Console.WriteLine(ConvertTest(test++));
        Console.WriteLine(ConvertTest(test++));
        Console.WriteLine(ConvertTest(test++));

        Console.ReadLine();
    }

    public static int ConvertTest(int? test)
    {
        if(test > 1)
            test = null;
        return test ?? 0;
    }
}

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…

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.

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.

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