csharp

Convention based Concurrency Management in Entity Framework Core

Who does not love convention over configuration? Whenever it makes sense I try to use it in my role as a system architect. It helps my programmers write more robust code out of the box.

Writing concurrency safe code is a corner stone in writing robust code today,  without it data quality can not be guaranteed. And when things go wrong you want to know who and when entities were updated so you can investigate what have gone wrong.

So what I did at my latest assignment was to force this onto the entities by convention using two markup interfaces ICreated and IUpdated(more…)

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

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

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

Wrap client side code in a Web Forms Control

I’m currently between assignments and in the meantime I’m helping fellow colleagues with a Web Forms system. They needed a Combobox for a requirement and after some googling I found out that there is none for free which suits their needs. I have created a Knockout enabled combo called Knockout.Combobox. I decided to take this client side combobox and wrap it in a Web Forms Control.
(more…)

MVVM with Excel and Caliburn.Micro

One of my colleagues needed to modernize a tool we had for Excel. He asked me for suggestions, since he knew I’m into modern UI development. I know very little about the Excel API but after some googling I found out that you are limited to Winforms. There is however a control in Winforms called ElementHost that let you host WPF elements in Winforms. This coupled with a custom Bootstrapper for CM will enable you to develop sleek MVVM tools in Excel.

The Boostrapper will act as an entry point for our Caliburn enabled app. It needs to inherit from BootstrapperBase rather than the standard generic base class Bootstrapper of TModel.

public class Bootstrapper<TModel> : BootstrapperBase
{
    private readonly StandardKernel kernel;

    public Bootstrapper(ElementHost host)
        : base(false)
    {
        kernel = new StandardKernel();

        Start();

        var model = kernel.Get<TModel>();
        var view = ViewLocator.LocateForModel(model, null, null);
        ViewModelBinder.Bind(model, view, null);

        host.Child = view;
    }

    protected override void Configure()
    {
        kernel.Bind<IWindowManager>().To<WindowManager>().InSingletonScope();
    }

    protected override object GetInstance(Type service, string key)
    {
        return kernel.Get(service);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return kernel.GetAll(service);
    }
}

Its constructor takes the ElementHost as argument and then starts CM using the Start method on the base class. We need to hook up the ViewModel manually and its done like.

var model = kernel.Get<TModel>();
var view = ViewLocator.LocateForModel(model, null, null);
ViewModelBinder.Bind(model, view, null);

First we create the ViewModel using Ninject, this way any dependecies for that model will be injected by Ninject. Then we ask CM to locate the WPF view using its convention based helper class ViewLocator. After we get the view we Bind it to the model using another CM helper class called ViewModelBinder.

Last but not least, we need to hook up the WPF element to the Winforms ElementHost.

host.Child = view;

Embedded resources

Alan Rutter asked me how to load embedded resources like themes etc.
App.xaml wont load in a none WPF project so you need to-do this manually like

var dict = new ResourceDictionary {Source = new Uri("Resources.xaml", UriKind.Relative)};
var app = new System.Windows.Application(); //This will load Application.Current
Application.Current.Resources.MergedDictionaries.Add(dict);

Typed javascript contracts using T4 Templates

A big problem with AJAX enabled JavaScript sites are the contract between server and client. A common “contract” is just to use jQuery.ajax with an inline declared URL and some parameters. A big problem with this approach is the fact that there is no real contract between client and server. Another problem is the fact that, as the site grows, so will your list of web methods and URL’s to go with them.

CQRS is winning more ground these days, and it has several advantages over the more classic ways of communication. One of the biggest is that there are no more god service classes with hundreds of methods and URL’s. Most implementations I have seen with CQRS in web projects only leverage CQRS between the server-side web and the message bus/backend. The client still communicates with a standard web method that just redirects the calls to the message bus. Why not leverage the contract safety and other perks of CQRS all the way from the client to message bus?

In the WCF-world we can share a common contract assembly that holds all command and queries, this is not the case with JavaScript. At my latest customer project I came up with the idea to use a T4 template to render all the commands and queries into a JavaScript file. You will even benefit from code completion in Visual Studio, at least if you use Resharper 6 or later.

First we need to create the T4 template. We can not use reflection to get the Command and query types because a T4 template is executed at design time not runtime or compile time. Instead we have to use the tools found in the EnvDTE namespace to retrieve all the projects of the solution and their types. The problem with EnvDTE is that it’s a major pain to work with, but don’t worry, there are remedies out there. From the extension manager in VS install the Tangible T4 Editor, it comes with a T4 template with helper methods for the EnvDTE tools.

Include the Visual Studio Automation Helper from the Tangible editor.

Image

It comes with a helper class called VisualStudioHelper with a bunch of helpful methods to retrieve info from a project and its types. Even though VisualStudioHelper is very helpful we still need some custom helper methods written. You need to write a method that gets all types that inherit a specific base class or resides in a special namespace or any other convenient convention that fits your project . It should look something like this.

public IEnumerable<CodeClass> GetSubClasses(string baseClass, Project project)
{
	return VisualStudioHelper		
		.CodeModel
		.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false)
		.Cast<CodeClass>()
		.Where(c => GetInheritance(c).Any(b => b.FullName == baseClass) && !c.IsAbstract)
		.ToList(); 
}

public IEnumerable<CodeClass> GetInheritance(CodeClass @class) 
{
	foreach(CodeClass @base in @class.Bases) 
	{
		yield return @base;
		foreach(var sub in GetInheritance(@base)) 
			yield return sub;
	}
}

Now we can get all DTO contract types for a specific project like this

var project = VisualStudioHelper.GetProject("MyApp.Core.Contracts");
var contracts = GetSubClasses("MyApp.Core.Contracts.Commands.Command", project)
	.Concat(GetSubClasses("MyApp.Core.Contracts.Queries.Query", project));

After that its just a matter of rendering the JavaScript version of the types, you have to be very specific about how you declare your objects for VS to be able to pick them up with code completion. And at the same time you must ensure that you do not overwrite any existing object closures.

First we create object closures for all namespaces and make sure they do not overwrite any existing closures.

window.MyApp = (window.MyApp || {});
window.MyApp.Core = (window.MyApp.Core || {});
window.MyApp.Core.Contracts = (window.MyApp.Core.Contracts || {});
window.MyApp.Core.Contracts.Commands = (window.MyApp.Core.Contracts.Commands || {});

Then we create each Type as a javascript function (Constructor).

window.MyApp.Core.Contracts.Commands.FooCommand = function(bar) {
    this.bar = bar;
};

I also add the fully qualified name to the object like this

window.MyApp.Core.Contracts.Commands.FooCommand.type = "MyApp.Core.Contracts.Commands.FooCommand";

It’s later used when sending a DTO to the server. Above JavaScript is rendered like this. Helper methods excluded, you can checkout the full example at Github.

foreach(var part in BuildNamespace(contracts)) {
	#>	<#= part #>
<#
}

foreach(var contract in contracts) {
		#>	
	<#

    var properties = GetProperties(contract).Select(p => CamelCased(p.Name)).ToList();
    var args = string.Join(", ", properties);

    #>

    window.<#= contract.FullName #> = function(<#= args #>) {<#
    foreach(var property in properties) {#>

        this.<#= property #> = <#= property #>;<#
    }
	#>

    };
    window.<#= contract.FullName #>.type = "<#= contract.FullName #>";
<#
}
#>

We also need some client code that can send the DTO’s, sadly the .NET WebApi that we use for this particular project does not support dynamic C# objects from arbitrary JSON objects so we had to send the DTO data as a string (Side note, vanilla JSON.NET that WebApi utilizes does support dynamic objects).

function buildContract(contract) {
	return { type: contract.constructor.type, data: ko.toJSON(contract) };
}
var url = "api/commandQuery";
MyApp.cqrs = {
	sendQuery: function(query, callback) {
		MyApp.utils.get(url, buildContract(query), callback);
	},
	sendCommand: function(command) {
		MyApp.utils.post(url, buildContract(command));
	}
};

You send a command or query like this.

MyApp.cqrs.sendCommand(new MyApp.Core.Contracts.Commands.FooCommand("bar"));

The server needs to create static typed C# objects instances, to do this we need to get a little creative with JSON.NET. First we declare a Data contract that WebApi is capable of deserialize to.

public class Contract
{
    public string Type { get; set; }
    public string Data { get; set; }
}

Then we need to create a way of decoding that data into a real object instance of the correct static type. We use some JSON.Net magic for this.

private TDto CreateDto<TDto>(Contract contract) where TDto : class
{
    var type = typeof(Query).Assembly.GetType(contract.Type);
    var jObject = JObject.Parse(contract.Data);
    var dto = jObject.ToObject(type);

    return dto as TDto;
}

We get the Type object instance from the type string sent from client then we use JSON.NET to first create e dynamic object from the string data and then we use the ToObject method that uses reflection to create a static typed version of the dynamic object. We use the above method from our WebApi method like.

public QueryResult Get([FromUri]Contract contract)
{
    var query = CreateDto(contract);
    return client.SendQuery(query);
}

A fully featured example of this technique can be found here