Useful snippets

SQL CE and namespaces

We use SQL CE in our unit test project to test our EF6 queries. This works pretty well and Code first setup makes sure each test gets a fresh CE database to work with.

We ran into a problem where two EF types had the same table name but inside different schemas. CE does not support schemas and this resulted in naming conflicts when setting up database. My solution was to create a little convention.

public class BakeSchemaIntoTableNameConvention : IStoreModelConvention<EntityType>
{
    public void Apply(EntityType item, DbModel model)
    {
        var entitySet = model.StoreModel.Container.EntitySets.Single(es => es.ElementType == item);
        entitySet.Table = $"{entitySet.Schema}_{entitySet.Table}";
    }
}

It bakes the schema into the table name like dbo_MyTable. You add the convention like.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add<BakeSchemaIntoTableNameConvention>();

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

You do not want to add this for production code so what I did was create a public event on the context. And call it from the OnModelCreating method.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    ModelCreating?.Invoke(this, modelBuilder);

    modelBuilder.Configurations.AddFromAssembly(typeof (MyContext).Assembly);
}

Call it from your Unittest project like.

ctx.ModelCreating += (s, e) => e.Conventions.Add<BakeSchemaIntoTableNameConvention>();

Microsoft.Rest.ServiceClient opt out retry

If you use Swagger generated REST proxies then you have probably come across the pretty new Microsoft.Rest namespace and namely the abstract class ServiceClient. I noticed a strange behavior when using clients that subclass this base class. The default behavior for this class is to retry when a 500 status code is returned.
I can not understand the reason for this being Opt out, its obvious a feature like this should be Opt in. So keep in mind when using this class you must always call SetRetryPolicy to disable the retry strategy.

var service = new MyService(uri, credentials);
service.SetRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), 0));

Task.WhenAny with take predicate

Not a very common scenario but still it happens, you want to execute a request to several Services, and only one has the correct data. The built in Task.WhenAny only supports to await the first Task complete. That wont do if you want to wait for the first Task to complete that satisfy a specific condition.

Nito.AsyncEx is a helper library for Task programming, it comes with an extension method called OrderByCompletion. It takes a collection of Task<T> and return a new collection that will be ordered on completion status. Using this method its a simple task to create a WhenAny based on a predicate.

public async static Task<TResult> First<TResult>(this IEnumerable<Task<TResult>> source, Predicate<TResult> predicate)
{
    var ordered = source
        .OrderByCompletion();

    foreach (var task in ordered)
    {
        var result = await task;
        if (predicate(result)) return result;
    }

    throw new Exception("Sequence contains no matching element");
}

Used like

var result = await services
   .Select(s => s.GetFooAsync())
   .First(f => f.IsSuccess);
}

Entity framework 6 and fluent mapping

If you google for EF and fluent mapping this is the first hit you get which is not strange since its the official MSDN page about fluent mapping in EF6.

They only discuss overriding the OnModelCreating method and configure the mapping inline in that method. And this is the most common way of dealing with fluent mapping out there in the community. But there is a much better and seperated way of doing it which MSDN fail to show.

System.Data.Entity.ModelConfiguration.EntityTypeConfiguration

This little class is your salvation when working with Fluent mapping in large enterprise systems. Implement it like. (more…)

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");
        }
    }