Virtual Warfighter

We have been working on a product of our own for the past months, a game for the OpenVR platform (HTC Vive, etc). The game will release this Friday, please check it out here!

http://store.steampowered.com/app/517020

Also I might once in a while write game/VR related blogs here, but its still mainly a blog about enterprise business code bases.

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

Mini test suite for async CQS backend

Our backend consists of a WebApi backend sporting an async CQS API (Not involving Event sourcing). I wanted a fluent syntax setup for our scenario tests, here is an actual example from the resulting code. (Code removed that are customer specific)

[TestClass]
public class When_doing_a_complete_booking : BusinessTest
{
	private Booking _result;
	private DateTime _date;

	[TestInitialize]
	public void Context()
	{
		Guid bookingKey = Guid.Empty;
		_date = DateTime.Now.AddDays(5);

		_result = Given(db => /* Setup here */)
			.When(() => new SearchQuery{ Date = _date, ...})
			.And(result =>
			{
				bookingKey = result.First().BookingKey;
				return new ReserveCommand { BookingKey = bookingKey, ... };
			})
			.And(() => new ConfirmCommand
			{
				BookingKey = bookingKey, 
				...
			})
			.Then(db => db.Set<Booking>().FirstOrDefaultAsync(b => b.BookingKey == bookingKey));
	}

	[TestMethod]
	public void It_should_book_correctly ()
	{
		Assert.IsNotNull(_result);
		Assert.IsTrue(...);
	}
}

(more…)

Client server event aggregation with Angular

I dont fancy Angular much, its slow and Knockout with its MVVM approach is much cleaner, and faster since computed and observables only mutate and change view state when they actually need to (That will change with Angular 2.0). Anyway, my current customer sports Angular and then you just have to form inline😀 We needed immediate update and you know I love event aggregation and probably know that I have a library for it, you can read more about it here!

I created a little wrapper for the the vanilla javascript client, install it using nuget
Install-Package SignalR.EventAggregatorProxy.Client.Angular

Basically it works by extending the Angular $rootScope and adds a eventAggregator function to all scopes. The eventAggregator function resolves the scope and then creates a closure with two methods, subscribe and publish. You can now listen to a event like (Serverside or client side event).

$scope.eventAggregator().subscribe(MyApp.MyEvent, onEvent);

(more…)

Parallel executed Tasks with isolated scopes

My current customers infrastructure is heavily dependent on external suppliers of data. Because of the nature of the data the system often have to-do the requests in real time while the end-customer is waiting for the response. Parallel tasks comes in handy when you want to aggregate data from several end points, both because it puts less strain on the Thread Pool and that your response time will be faster because you do not need to wait for each to complete (Parallel vs Sequential).

The problem starts with frameworks that does not play nice with sharing their resources over multiple Tasks/Threads, an example of this is the Entity Framework DbContext. One way is to marshall the lifetime of the context yourself and spawn one for each parallel task. But this is not a solid design, if you use a IOC you want any object in the current graph to receive the same instance of the DbContext without bothering with lifetime code. I created a little class called TaskRunner for this purpose (more…)

Abstract DI container Scopes

I saw an increasing demand for mini workflows / domain sub-parts in one of my projects. Most containers have some kind of support for sub scopes or nested containers, but I do not want to expose the Container API. If you have few places were you need nested containers you can implement this directly for your container of choice. An example of this is a container specific implementation of Web API’s IDependencyResolver. But in our case we had several different needs for scoped contexts near the domain. My solution was to abstract the context in a interface IScopedContext. (more…)

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

MVC Custom errors, HTTP status codes and SecurityException

We use Windows Identity Foundation in my current project. WIF introduced the Claim based authorization in .NET 4.5 which is a welcomed addition since we were forced to use outdated tools like EnterpriseLibraries Rule authorization to achieve something similar before it.

Whenever a claim is not met WIF will throw a System.Security.SecurityException exception which will not play nicely with MVC Custom errors because it will render a status 500 instead of the correct status 403. This is not very user friendly since the user will think something is wrong instead of understanding that he or she needs to order additional privileges to access said part of the system.

The solution is really simple and I did not find it when googling, thus this blog post😀 (more…)