This post is intended for web developer having basic to medium knowledge of MVC, Javascript, jQuery.ajax(), TypeScript. I am not going to explain the whole application but just the challenging parts and the solutions I implemented. For the rest there is the source code.

My sample application (largely inspired from work needs) is a 3 pages application. A first page manage dynamic questionnaire (with dynamic groups of dynamic questions), a second page can answer those questionnaires and a third can query them.

Getting Started

I am using VS2013 for this and if you don’t have it some option might slightly different. VS2012 at least is required for the Visual Studio – TypeScript plugin to work. To be able to open the solution or replicate it, you will need to install the following:

First install the TypeScriptplugin for visual studio (I wrote this app with TypeScript 0.9.1).

Create a “~/MyScripts” folder, where custom / handwritten scripts will be written, so they are clearly separated from 3rd parties (personal preference, doesn’t matter much).

Remark I’m using chosen instead of the more recent select2 for my combobox as select2 seems to be very slow on IE8.

Remark I’m using jQuery 1.10.2 instead of 2.x for IE8 support.

Remark I’m using EF5 (instead of newer EF6) as EF.Extended (which I use for Future query) doesn’t support EF5 yet. Future query is used to group multiple query in one database command, hence reducing network and connection overhead.

Remark I choose Knockout over AngluarJS for my template engine because Knockout is fully declarative. I.e. it needs absolutely no code to setup and choose templates. Whereas AngularJS is a mix of declarative / imperative and you can’t escape writing infrastructure code when using template heavily.

About WebAPI

Web API looks very much like MVC. It has controllers (inheriting from ApiController instead of Controller) and returning plain objects (instead of ActionResult). The HTTP headers are used to select the in and out serialization method. It also has its own routing mechanisms, where one should set a route that won’t conflict with MVC (so as to be unambiguous).

Unlike the out of the box WebAPI config I specify the {action} in my route, as my WebAPI controller will have many methods, returning heterogeneous type. Unlike most sample on the net where there is one controller per data type with 4 actions (select/insert/update/delete).

Thanks to TypeScript it is strongly typed and would help removing parameter errors. However what I really would like is the server proxy code to be automatically synchronized or generated from my code. Here enter T4!

If you right click somewhere in the Solution Explorer, you can create a new (T4) Text Template

I won’t go into much about detail on the intricacies of T4 templates, MSDN is here for that. Here I want to explain how to explore the current project’s code.

When one create a T4 template, the first line will look like that:

<#@templatedebug="false"hostspecific="false"language="C#"#>

The hostspecific property is the one that will give you access to VS data. It is false by default, you want to make it true.

When it is true you can access the some visual studio service, of interest there are those 2:

Each CodeElement interface has a property Kind which tells you what it is (class, function, interface, attribute, and so on…) and then it can be cast to the appropriate interface for more info (CodeClass, CodeFunction, …).

Now one can explore the code in the current project and write a proxy generator. I won’t go too much in the details of my implementation I will just talk a little more about the result. I got 2 generators, one to generate TypeScript definition of my JSON exchange object, and one to generated TypeScript server proxy. I created an attribute ToTSAttribute, which I use to flag what I want to be recreated in TypeScript.

I modified my EF template to mark my EF class with ToTSAttribute as I want to manage them with this UI. I generate 2 TypeScript interface for each of my class. The normal exchanged interface. And a Knockout friendly interface (more on that later).

About TypeScript

TypeScrit files are .ts files. They are compiled (when building the solution) in .js file with the same name. Sadly at this stage the .js file are not marked as part of building output and, in case of automated build, one should manually add them to be part of the deployed files!

One solution is to edit project to add each of the .js files produced to it. “Unload Project” then “Edit MyProject.csproj”, then use the DependentUpon tag.

There are 2 ways of declaring a member method. One as a method (Who) and one as a property being a function (Who2).the later can’t be overridden. And also the intellisense get sometimes confused about the special property “this”.

Class can’t be extended (you can’t add property to a strongly typed class object), but you can always extend interface, as in:

interface IPoint {getDist(): number;}

interface IPoint {translate(x: number, y: number);}

Interface are best used to describe data exchange objects. The T4 generate interface declarations. Which is complemented with hand written extra properties added and used by client side JavaScript data view model. Also one can’t really safely cast from a class to another (as nothing really happen) whereas interface casting is more appropriate.

About KnockoutJS

KnockoutJS is a library to do MVVM in JavaScript. For that it has a templating engine and introduce observable JavaScript object. There is great documentation and live example on the web site.

To setup KO write a few data template and tag with data binding and then setup a model on the whole page with

ko.applyBinding(model) // whole pageko.appplyBinding(model, domElement) // part of the page

Remark The model could be any object. But if you want 2 way binding (i.e. UI automatically updating from data changes) you need to use observable.

Let’s say you want to make a file system tree view with the following data model:

where the text property (in the data-bind tag), is a path to an observable.

Remark the data-bind tag is where all the knockout magic reside

You can turn any simple value into an observable with ko.observable(value), for array use ko.observableArray(array), for object use ko.mapping.fromJS(obj) (it’s a plugin, need to be downloaded separately), and it will recursively set every property as an observable. The get the value from an observable you just invoke it, like so: myObservable(), to set it: myObservable(newValue). To be notified of change you can subscribe, like so: myObservable.subscribe(function(newValue) {}).

Knockout Template

Where Knockout really shines (more than AngularJS that is) is in how easy it is to define and use reusable template. Here is a recursive template to display the directory object defined just before.

Template are defined in script tag. Referenced by their ID property. When one want to use the template pass the name of the template and data. And that’s all there is to it. The above sample is fully functional!

About the Application

There are 3 views: Manage.cshtml (define the questionnaires), Answer.cshtml (answer them), Query.cshtml (search the answers). The MVC controller methods are empty just returning the views, this being a client side app. Each page share the common Questionnaire.js (generated from Questionnaire.ts). And a page specific javascript file.

I defined 2 sets of KnockoutJS templates. One set is for editing objects, as they are pretty much all the same and numerous. The other set is for viewing and they are used on every screen.Because the templates are shared by all views I wrote them in a partial view (PartialTemplates.cshtml) and the data model for them should be an APPModel class (define in the common Questionnaire.ts).

I also make them inherit from a common interface and add some extra UI properties. Including a app_type property so my model’s methods just take an IAppItemData and use the app_type property to find what kind of item it is. All my extra method have an obvious prefix to avoid colliding with EF generate data classes.

All my server proxy methods return a jQuery deferred which I can act upon its return with the .then() method. I then set the Knockout model for the page by invoking my server proxy and binding the result.

Remark all my editing method are in the root APPModel object. To access them in all the template I use the KO property “$root” which is the model set by the user on that location (as opposed to the current model “$data”, in case of recursive template use).

At the top there are 3 columns set up with bootstrap grid layout (class: “row”, “col-md-4”) each with an identical knockout template (data-bind: template: name) of my column data (“questionaires”, “groups”, “questions”)

Finally the UI looks like that, reusable template marked in red:

The template for editing the items might depends on the item, so instead of being a string it’s a function (returning a string) in APPModel (which I access with “$root”).

Every button call an action on my model, which update the data model which automatically update the UI.

in data-bind I use the click binding to call a method on my control which just create a new element. All method editing the object call the server and only do their stuff if the server method is successful, hence making sure the database is always update.

Of interest in the GetQConfig() method (which returns either all questionnaire data, or only one for a particular questionnaire) which use .Future() to turn multiple EF DB query into a single database call! Behold, there is only one database call done when the method below execute:

Viewing Questionnaire

There is also some templates used on every page to view or answer a particular questionnaire. In the managing screen the selected Questionnaire is automatically previewed lived below, and update live as its configuration changes.

As shown above when of the extra property I add to question is the “app_answer” property, this way I can just get the answer from the questions.

Answering Questionnaire

The model inherit from APPModel, add 5 short methods (4 for the button and one to load the selected questionnaire on demand).

Of interest the comment below is not a comment, but a Knockout template without container DOM element.

Searching Answers

Remark only LIKE and == operators on text field are implemented in this sample.

I was looking for something which can represent a relatively flexible query with multiple AND / OR criteria. Unfortunately it appeared to me that letting the user choose arbitrarily nested query of arbitrary depth will lead to slow recursive SQL (with cursor). Instead I opted for 2 nested query level block, with OR at the top level and AND in sub block, or vice versa.

Coding the answer was relatively trivial. Of interest, I used datatable to render the result in a grid and a bootstrap modal to show individual results.

Also I used individual Knockout model for the popup and the rest of the page:

What’s more interesting is the SQL implementation of the search. Due to the complexity of the search I decided to write as a SQL stored procedure (or sproc), instead of a C# query with EntityFramework. I pass a list of criteria block to SQL as a user defined custom table type.

the groupID is the an arbitrary query block number which is only used to group the the criteria result together by query block.

The answer to a questionnaire is stored across multiple row as shown on this database diagram

In my sproc I will have to match each answer with its question and criteria and check whether there is a match or not, represented as 0 for fail or 1 for success. Then I have to aggregate all the results applying the AND/OR logic displayed in the UI.

Below is the search stored procedure. For clarity sake I replaced the calculation which match a single criteria with ‘1’ so as to highlight how I declare and use the custom table type (at the top) and how I aggregate the answer. The individual row match are in a common table expression and the select below aggregates them and return matching answer sets IDs.

Now this is well and good but calling this sproc was tricky too. EF doesn’t support custom table type. I had to revert to the lower level ADO.NET API. Custom table type are passed as DataTable. With the help of a few extension method calling this sproc and reading its result proved trivial:

Last few words

Well I hope this rough explanation of my sample would have whet your appetite about Knockout, TypeScript and WebAPI. Hopefully it will also help understood the source code better if you want to study the sample more in depth. Finally I hope my T4 template for strongly typed proxy generation will stir some interest too.