Useful snippets

Seperate KO View formating and ViewModel state

A normal scenario with Knockout is that you want date and number observables to be formatted to the current culture of the client, this is easily implemented in a Knockout extender, something like.

ko.extenders.numeric = function(observable, options) {
    var textValue = null;
    return ko.computed({
        write: function(value) {
            textValue = value;
            var parsed = Number.parseFloat(value);
            if(!isNaN(parsed)) {
                observable(parsed);
            } else {
                observable(null);
            }
        },
        read: function() {
            var value = observable();
            if(value == null) {
                return textValue;
            }

            return value.toLocaleString(); //This  can be replaced with for example the Globalize plugin 
        }
    });
};

Use it like

this.amount = ko.observable().extend({ numeric: true });

The problem with this approach is that the ViewModel will no longer work against numbers it will work against formatted strings, so this.amount() will return a string instead of a number. This is very bad practice in a View/ViewModel seperation stand point. (more…)

Implicit dependencies and ‘copy local’ fails to copy

A common scenario with .NET Solutions is that you have a Project, lets call it Project X, that have dependencies to a library without explicitly using it from code. You have a host project typically a Web or Windows client Project that uses Project X, even with copy local set Visual Studio will fail to load that implicit dependency and you will receive a Runtime error when trying to run the project.

One solution is to add this reference to the host project even if it does not have any direct dependency to the library. I think this is bad practice and will get very hard to maintain in a large project with lots of dependencies and assemblies.

A better solution that I use is to create a little helper method

static RepositoryBase() {
   Util.EnsureStaticReference<System.Data.Entity.SqlServer.SqlProviderServices>();
}

It should be called as close to the dependency as possible for readability. In above example I have a Repository base class which uses Entity framework. I call it from the static constructor.

The implementation of EnsureStaticReference looks like this

    public static class Util
    {
        public static void EnsureStaticReference<T>()
        {
            var dummy = typeof(T);
            if(dummy == null)
                throw new Exception("This code is used to ensure that the compiler will include assembly");
        }
    }