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.


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		
		.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false)
		.Where(c => GetInheritance(c).Any(b => b.FullName == baseClass) && !c.IsAbstract)

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



  1. Interesting to make the server ‘front-end backend’ a small pass-through for deserializing / serializing queries and commands, making the client side web application a true front-end like the traditional role of .Net MVC controllers / WebApi controllers. I can see how this speeds up rapid development, getting rid of unnecessary plumbing code in the WebApi, communicating directly with the backend ‘bus’. Have you thought of a security layer available that can hinder certain users from executing certain commands / queries?

    1. Hi Max. The project this was written for has zero domain logic, everything is sent to the main frame (zOS) backend. We do however send a header with the messages and the AD-user being one of them so the backend can do security checks there. Plus the site is protected with standard ASP.NET security.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s