C# MVC 4 and Knockout — Getting started

Posted on January 15, 2013

0


In this post

  1. Intro — Goals and choices
  2. MVC4 — Life after ASP Forms
  3. Linq and the Entity Framework — Simplification of Data Access, giving a more consistent feeling within the C# project
  4. Knockout.JS — Binding data to HTML
  5. TypeScript — Writing JavaScript as if it is Object Oriented, making it less painful to refactor your project like there is no tomorrow.
  6. T4TS and TypeScript — Converting C# classes to TypeScript Classes, keeping the project consistent and less prone to breaking apart.

Intro: goals and choices

This post summarizes the base-setup for one specific approach to build Single Page Applications with C# .NET and JavaScript

Goals

  1. Solid starting point — .NET MVC 4 is new to me and I have been spoiled using ActionScript when building front-ends. I like to have a solid starting point which takes care of all the boring parts. This includes:
    1. Less coding, more result — A lot of code between parts is the kind of “copy & paste” glue where objects move from one environment (database) to another (C#) to another (JavaScript) and back. Each of these steps usually is translated into copies of the Data Objects in the Model.
    2. Strong typed all the way — Strong typed code warns you beforehand when you make mistakes. It forces you to do things better. More solid. JavaScript is a nightmare to me due to the lack of strong typing. Errors only show up when you hit them in runtime.
    3. The use of DTO’s — DTO’s or “Data Transfer Objects” are stripped down objects made specifically for transfer of data between two points (JSON and C# in this case). They create some overhead in coding as they copy the objects in the Database, but they are for now the most solid and efficient solution.
    4. Proper support for constant Refactoring — JavaScript projects break easily. Change one public variable or one method name somewhere and all dependent elements will no longer work. Without any further warning. When you have two separate code-bases (1: C# and 2: JavaScript) Refactoring is like misery. You rather not do it at all once things work. And this is a very bad thing.

Specific choices

  1. Knockout.JS — Knockout.JS is one of several JavaScript frameworks to perform data bindings to HTML pages. It is easy to use, properly documented and it works. I needed to start somewhere.
  2. TypeScript: OOP in JavaScript — See my remark on refactoring. TypeScript helps me to do proper OOP in JavaScript, including Strong Typing and the detection of broken references.
  3. T4TS — T4TS is a script-based “conversion tool” to convert C# classes to TypeScript Interfaces.
    1. C# Objects reflected in JavaScript — All C# Objects I mark to be converted to JavaScript will  be present in TypeScript, allowing me to call them “as if” they are my C# objects. Changes in the original C# classes will automatically reflect in TypeScript when I update the TypeScript objects.
    2. Automated process — Instead of typing all manually, T4TS does it for me using code, meta-tags and reflection on the tagged classes.
    3. Default not for Knockout — By default, T4TS generates basic JavaScript objects useful for JSON type data. These objects are kind of useless when you want to use Knockout to the max.
    4. Hacking T4TS: adding Knockout-style output — After hakcing the script of the T4TS generator a bit, it now outputs Knockout-specific Object Representations as well. In short: each “variable” in a Knockout object is actually a Method and each Knockout-specific class is output as koMyName where that same class is still converted to a class named: MyClass.

Findings

  1. Awesomeness — The first Working Proof of concept, binding data to an HTML form took less than one day. Building interactive forms and Single Page Applications in Knockout.js is close to effortless once you get the binding-“language”.
    1. Using the <!– ko –> tags –– I found that in two cases the <!– ko –> tags are more reliable than when used in an HTML element.
      1. <!– ko if –> — This is a conditional tag. If the condition is not met, the code within the IF statement  is not executed
      2. Nesting with <!– ko foreach –> — Nesting is a bit tricky in Knockout. It does not always work when applied on an HTML element like: <div data-bind=”foreach … <!– ko foreach is more reliable.
  2. Trouble in JSON with optional variables in autogenerated Data Objects — The JSON converter does not like objects with optional variables ( MyType (optional) var = “somevalue”). When sending an object from the database with optional variables, the entire objects ended up as “undefined” on the Client side.
  3. TypeScript — TypeScript does what it is supposed to do. It forces for a more elaborate approach which slows down in the beginning. Especially for objects from the Server. I included T4TS for that reason: to convert my Classes to JavaScript with zero coding.
  4. T4TS needs adjustment to serve Knockout — T4TS is not made with frameworks like Knockout in mind. Interactive objects in Knockout use methods instead of variables to get and set values. This to allow events to be fired where needed. I added some code in the T4TS parser to overcome this limitation.
  5. TypeScript namespaces — TypeScript works with namespaces like .NET. But for some reasons they are called “modules”. Each Class in each TS-file within the same “module” is part of the same environment. Within TypeScript

MVC 4: A short intro

MVC 4 is the successor of .NET forms. MVC4 tries to implement the “build fast, deliver fast” approach of Ruby on Rails by offering a different approach to building sites and web-applications than ASP.NET Forms.

Controller-centric

One of the manjor changes is that MVC4 no longer is page-centric, but that it is controller centric instead.

Each request enters the Controller first and then is processed as needed. The calls to the controller look like this:

http://www.YourSite.com/ControllerName/MethodName/<parameters&gt;

Less boilerplate code

Using ASP.NET I needed to create a lot of boilperplate code. .NET MVC, being contoller-centric, also makes it easier to switch between different types of output. It is less rigid, less interwoven with the View.

One single .NET MVC method in your Controller can produce XML, JSON or HTML depending on the input parameters.

Better OOP feel

For some reason, MVC4 gives me a better OOP-feel. I address my application as an instantiated Object from my Controller Class via a browser. Parameters I pass are automatically mapped to input-variables on my method. The result is returned to the caller. In this case: the browser.

Suited for Unit tests

As your web-application operates as a instantiated set of objects from your Controller Classes, you can (unit)test that application immediately on the Controller Classes. No need to call for pages. Simply call the method you want to test and verify the output.

Linq, Entity Data Models and the MS Entity Framework

Short

Linq, Entity Data Models and the use of the Entity Framework seems to be the way forward in .NET applications. I have no experience with this yet in high-performance systems but reading into Linq in combination with the Entity Framework, it seems the Linq-requests are neatly translated to SQL Code before the database is approached. So querying your tables via Linq will not lead to “SELECT * FROM MyTable” where the entire result-dataset is then filtered and processed in memory by Linq.

Definitions

  1. Linq — Simply put, Linq is an overlay to do queries and transformations on data objects like Lists and Dictionaries.
  2. Entity Data Models — These are auto-generated data models (using the Entity Data Model Wizard) derived from the Database. The Data Model is translated to Classes and objects. Tables are treated as objects with methods to do your CRUD actions (Create, Read, Update, Delete). Connections are managed on the background. Calls to the database can be specified using Linq, making the entire data-access approach in your application more unified.
  3. MS Entity Framework — The MS Entity Framework is a Data Access Layer with some nifty additional possibilities. Summarized: everything is now neatly defined and abstracted as objects in collections. Updates are done via those objects and passed to (auto-generated) objects representing the tables.

Findings

  1. Feeling of consistency — Where ASP.NET with ADO gave me the feeling that I had to do a lot of different translations into different types of languages, Linq with the Entity Framework mostly cuts out a lot of extra coding overhead.
    1. Calling data from the database is as easy as:
      • List<MyTable> result = DbContext.MyTable.
        Where ( record ==> record.MyValue==”something”)
    2. The “Where” clause is a Linq-clause using the Linq-syntax.
  2. Less code — I use less code in my MVC / Entity Framework  project than in any previous project.
    1. With conversions — Conversions to JSON and back are a breeze (using NewtonSoft.Json in my case)
    2. For Database Access — As this is all abstracted to an Object Model using Linq, I just pass parameters and objects and done.

.NET Forms in MVC 4

I took a brief look at this. It is relatively easy to bind the data to HTML, but I am not really blown away by the page-per-page setup it works into hand. My goal is to build a Single Page Application. So no opinion on this yet.

Knockout.JS

Findings

  1. Zero code — Knockout.JS allows me to bind data and create complex interactions in HTML with zero code.
    1. Knockout tags — The knockout tags take care of binding, hiding, presenting and parsing the data; to change CSS classes on objects. To auto-update elements when the data changes on the represented objects somewhere in the application.
    2. Knockout Data Objects — To do so, Knockout has and uses Knockout Data Objects. These objects work with methods to set and get data and internally maintain an interaction model based on the Observer pattern. When data changes, all observers of that object (including View Elements in your HMTL) will be notified.
    3. HTML View Objects — When you apply a “data-bind” tag to an HTML element, this element is turned into a Knockout View Element that observes the Data Object it represents and displays and which will respond to changes in the data it observes.
    4. Nice event model — When I update my Model, my Data Object, the HTML viewobjects bound with Knockout will automatically respond. This reduces the code to get things done tremendously.
  2. Fast results — I was pleasantly surprised how simple it is to build complex interactions within Knockout.JS.

TypeScript

As said before, I do not like the loosely typed way of working in JavaScript.

I like my pre-compiler to point out where I go wrong, instead of having to find my stupid mistakes in the Browser JavaScript Debugger by running the application and hitting that specific point.

Short

  1. Strong typed JavaScript — TypeScript does a nice job in offering a Strong-Types programming environment
  2. Import and use existing JavaScript — TypeScript allows you to import and use existing JavaScript.  It parses the JavaScript and makes best guesses to what you can and cannot do. For existing frameworks there are TS resource files available, allowing TypeScript to pretend it knows the ins and outs of frameworks like jQuery.
  3. Immediate result — TypeScript converts the TypeScript code to JavaScript the moment you save it. Add those scripts to your HTML and done.

T4TS (and TypeScript)

As said before, T4TS helps you to convert C# classes to TypeSCript objects.

Benefits:

  1. Reflection of changes — The biggest benefit of this is that any change in your C# Object is reflected in your TypeSCript object the moment you generate the TypeScript code again. Any variable you call that no longer exists will be marked as an error in the compiler.
  2. Solidness / Project consistency — You can address the JSON objects in the same way as the C# counterparts. As updates reflect in TypeScript, the project remains consistent even if and when you do a lot of refactorings.

Conclusion

  1. C# and TypeScript: Solidness and Project consistancy — Where — due to the loose structure of JavaScript — refactoring can be one of the biggest enemies for reliability in mixed JavaScript / C# projects, TypeScript and T4TS help detect many inconsistencies immediately within the Visual Studio environment. This allows for more restructuring and will lead to better code on the long run.
  2. Faster and more consistent results — Yes. It is amazing. jQuery, Knockout and .NET MVC 4, using JSON for data exchange work together amazingly well. .NET MVC removes a lot of boilerplate coding and allows me to do things one way, instead of having to make several “jumps” to different formats using hand-written conversions from one format to another.
  3. HTML 5 + Knockout.JS: an improvement over Adobe Flex — Adobe somehow never really got it with Flex. Building more complex interactions using the standard Flex architecture never has been fun. The key of Knockout is the focus on the Model and how that model is bound to the View. Anything you build in Knockout is driven from the Model. All events fired in your application are related to the Model. State changes? Stored in your Model and reflected through bindings. Rendering data and parts of the screen? All triggered by events from the (View)Model.
  4. Other frameworks — Knockout.JS is not the only player. I will investigate others later.
Advertisements
Posted in: C# MVC4