Wednesday, April 9, 2014

Bundle Knockout Data-Bind

In one my projects I ran into a scenario where I need to specify multiple bindings for a textbox. Here is the code I used to this multiple bindings

<input type="text" data-bind="value: model.Allergies.Value,
css: {focusctrl: model.Allergies.ColourType() === 1,
correctctrl: model.Allergies.ColourType() === 2},
event: { focus: function() {$root.resetColour(model.Allergies)} }" />

The problem here is have several of these text boxes (about 50, I guess not a good design, but is what the user wants). I don’t want to repeat this binding several times (DRY). I want to bundle these bindings (like a function) so that I can avoid duplication and keep the code clean.

Luckily Knockout provides the functionality I am looking. It provides “ko.applyBindingsToNode” to dynamically do the databinding. So I defined a custom binding in which I am in turning doing the databinding I want. Here is my custom binding

ko.bindingHandlers.notesvalue = {
    init: function (element, valueAccessor, allBindingsAccessor, data) {
        var field = valueAccessor();
        field.focusctrl = ko.computed(function () { return field.ColourType() === 1 });
        field.correctctrl = ko.computed(function () { return field.ColourType() === 2 });
        ko.applyBindingsToNode(element, {
            value: field.Value,
            css: { focusctrl: field.focusctrl, correctctrl: field.correctctrl },
            event: {
                focus: function() {
                    if(field.ColourType() === 1){

In the above code, I am just using the initializer and doing the bundling of the value, css and event data-binding. As you see, in the above code I am also defining computed attributes. That’s neat.

With my bundling code my databinding is reduced to as below

<input type="text" data-bind="notesvalue: model.Allergies" />

This is something I can live with. J.

Saturday, February 22, 2014

Creating Durandal SPA application without Visual Studio template

As you know there are several Visual Studio Templates which gives a quick start for your SPA development. If you are like me, then you want to know what is the plumbing code for the SPA development. In this blog I will give you step by step instructions on building a Durandal SPA application using any Visual Studio Templates

Before we start, we need all the dependencies of our application. Download all the below dependencies from their websites

In addition we also need couple of nuget packages. Which we will download while setting up the project.
Once all the necessary scripts files are downloaded, let’s fire up Visual studio. Below are the steps we need to follow to create a Visual Studio durandal project

  • Create MVC Empty project
  • Create Content & Scripts Folder
  • User Scripts create Durandal and copy all the files downloaded from durandal under js. Include them in the solution
  • Again under Scripts Create foundation and copy the scripts from zurb foundation and include them in the solution
  • Copy Knockout under scripts folder, similarly copy jquery, require, text
  • Under content copy durandal.css, foundation.css, normalize.css
  • Under content create app.css which is used by our SPA
  • In the root project create folder App & under it create viewmodels & views. This is where we will keep all our SPA scripts
  • Under App_Start create BundleConfig.cs which will include the bundle configuration for all the javascripts and css.
  • Install the Nuget package: Install-Package Microsoft.AspNet.Web.Optimization
  • Include the following code in the BundleConfig.cs
    public class BundleConfig
        public static void RegisterBundles(BundleCollection bundles)
                new ScriptBundle("~/scripts/libraries")

                new StyleBundle("~/content/css")

·         In the global.asax on the Application_Start initialize the bundle config

  • Add Home Controller
  • Add a view without using layout page option and use the below code
@using System.Web.Optimization
    <meta name="viewport" content="width=device-width" />
    <title>My First SPA</title>
<body class="main">

    <div id="applicationHost">
        <div class="splash">
            Page loading ...

    <script src="~/Scripts/require.js" data-main="@Url.Content("~/App/main")"></script>

With this we are done with MVC setup. Now we need to create the javascript files

  • Create main.js which is starting point for Durandal and include the below code
//require configuration for durandal
    paths: {

//defining global libraries
define('jquery'function () { return jQuery; });
define('knockout', ko);

//starting the app
define(['durandal/system''durandal/app''durandal/viewLocator''durandal/composition'], function (system, app, viewLocator, composition) {

    app.title = 'Hello World';

    //specify which plugins to install and their configuration
        router: true,

    app.start().then(function () {
        //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
        //Look for partial views in a 'views' folder in the root.

        //Show the app by setting the root view model for our application.

  • Create shell.js & shell.html under viewmodels & viewfolders. Shell is like a layout page in MNC and include the below code
     o   shell.js
define(['plugins/router'], function (router) {
    return {
        activate: activate,
        router: router

    function activate() {
        var routes = [
                        { route: ['''home'], moduleId: 'home', title: 'Home' },

        router.makeRelative({ moduleId: 'viewmodels' }) // router will look here for viewmodels by convention
            .map(routes)            // Map the routes
            .buildNavigationModel() // Finds all nav routes and readies them
            .activate();            // Activate the router


     o   shell.html
        <br />
        <div class="content"
data-bind="router: { transition: 'entrance', cacheViews: true }"></div>

  • Finally define home.js and & home.html. This is like an index page in MVC
     o   home.js
define([], function () {
    var vm = {
        activate: activate

    return vm;

    function activate() {
        return true;


o   home.html
    Hello World!

We are done. Now compile and run the application to see our SPA application that was built without any template.

Source :

Friday, February 21, 2014

Team Foundation Server and Git Mirroring

I typically use TFS for all my development. I also work on some open source projects. I want to host those open source projects on GitHub for public access. At the same time I want to keep all my projects on a single place, which is my TFS. So I want keep TFS as my master source and push my changes to GitHub for public access. In other words I want to mirror my TFS projects on GitHub.

It turned out that the mirroring TFS and Git seems to be simple. First we need to setup TFS using local git repository. Check the below MSDN link for more details:

Once you have local GIT & TFS configured. You do the development and push the code to TFS as you do always. Whenever you want to push the code to GitHub go the command prompt and navigate to the .git folder that is under the repository directory. Run the below command line to mirror your TFS code to GitHub

(replace username, passwod and repo with your values)

With above command all the changes done in TFS will be mirrored. With this command line you can decided when to sync your TFS changes to Git. If you want to do this automatically you can use one of the Git hooks.

Friday, February 14, 2014

ASP.NET SPA Naming Conventions

As we started embracing rich client side technologies such as Single Page Applications and some popular JavaScript libraries, we will all face the challenges of diversities in .NET and JavaScript. One of those diversities is the naming convention.

As Javascript is based on java, its naming conventions will be similar to that of Java. For example in JavaScript we use camel casing for methods, where as we use Pascal casing in .NET. Similarly .NET naming guidelines discourage the use of underscores, but they are freely used in JavaScript.

With SPA technologies we need to pass data between the JavaScript objects and .NET objects. That means objects will be passed from one technology to another. The objects defined in .NET will be used in JavaScript and similarly objects defined in JavaScript will be used in .NET.

Being a hardcore .NET developer I could say use .NET naming conventions throughout, why should I learn or use other naming convention? On the counter argument, there is a popular saying, be a Roman in Rome, so we have to follow JavaScript naming conventions in JavaScript. Doing so will make our code readable by non .NET folks. So the dilemma is to use .NET naming conventions or JavaScript naming conventions.

As ASP.NET is a conglomeration of technologies, we should find an amicable solution for this. I would recommend to use a hybrid naming conventions. I propose to use JavaScript naming conventions in JavaScript and .NET naming conventions in .NET. For the objects that will be passed across layers use .NET naming convention. By following this approach, the .NET side will have a clean naming conventions and JavaScript will have a hybrid naming convention.

Wednesday, February 12, 2014

Ranking Functions

Today we are going to discuss about ranking functions and their benefits.Lets start with a basic question ,
  • What is a Function ?
A function is a method which expects some parameters and will return an output.SQL Server has many functions.Since our point of interest for now is ranking function so we will discuss the same first.
  • What is a Ranking Function ?
Ranking functions return a ranking value for each row in a partition. Depending on the function that is used, some rows may receive the same value as other rows.SQL Server 2005 introduced four new functions, ROW_NUMBER, RANK, DENSE_RANK, and NTILE that are collectively called as ranking functions.. Ranking functions are non-deterministic.Non-deterministic as the name suggests cannot be determined(i.e output is not known to us).
Lets start with a simple example to make a better understanding.First i will create a table consisting some column and rows as follows:
CREATE TABLE tblSample (ID INT IDENTITY, Column1 INT, Column2 INT, Column3 INT)
INSERT tblSample  VALUES (0, 1, 8)
INSERT tblSample  VALUES (0, 3, 6)
INSERT tblSample  VALUES (0, 5, 4)
INSERT tblSample  VALUES (0, 7, 2)
INSERT tblSample  VALUES (0, 9, 0)
INSERT tblSample  VALUES (1, 0, 9)
INSERT tblSample  VALUES (1, 2, 7)
INSERT tblSample  VALUES (1, 4, 5)
INSERT tblSample  VALUES (1, 6, 3)
INSERT tblSample  VALUES (1, 8, 1)
Now we are good to go.Lets start with a basic ROW_NUMBER Function:
SELECT *, ROW_NUMBER() OVER (ORDER BY Column2) AS RowNumber FROM tblSample
Above query will select all the rows from tblSample and will order Column2 and will assign sequential numbers (like sequence object or Identity) to each the result will be:

From the above result you may see the column 2 has been ordered and the sequence number(in RowNumber column) has been assigned to each row.This will clear the definition of a ranking function i.e  Ranking functions returns a ranking value for each row.
Lets take another scenario where you want to group the rows in a particular format.If you closely look at the values in column 1 you will see column 1 has two numbers 0 and 1.Now you want to group the sequence numbers according to column 1.Here we will use partition on column 1.see below query :
Above query will partition or you can say group the column1 into two parts one containing 0 and other as 1.output will be :

Above result,all the 0 of column1 has different set of sequence numbers and 1 of coulm1 has different set of sequence.
It is possible to combine multiple ROW_NUMBER functions (or multiple of any of the other ranking functions) with different ORDER BY clauses in a single query:
SELECT *, ROW_NUMBER() OVER (ORDER BY Column2) AS RowNumber1,ROW_NUMBER() OVER (ORDER BY Column3) AS RowNumber2 FROM tblSample
That was all about ROW_NUMBER().Lets see how other function Function we are going to discuss is about RANK() & DENSE_RANK().Both the functions are pretty much same.the tables and values are going to be same for better understanding.
lets get back to the previous query we used for rownumber to get a better understanding about rank and dense rank.
DENSE_RANK() OVER (ORDER BY Column2) AS DRank FROM tblSample
Output of this query will be:

RANK gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.
DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.

Friday, February 7, 2014

Knockout Date Format Extender

As you know Knockout is great on two-way binding and provides a clean mechanism for showing data on the page. There will be scenarios where you want to format your data to make it user friendly. This is especially true when you are showing dates. You don’t want to show the default javascript format to your users. You can certainly format dates while doing the databinding. But formatting dates inside your binding quickly becomes clumsy and sometimes you lose your two-way binding.

In this blog I will show you how to modularize the date formatting and use it throughout the application. Thanks to the Knockouts extenders which allows us to define our date formatting in an elegant way. If you are not aware of Knockout extenders, please check documentation on their site

Before getting into the extender, I want to tell you about a small javascript library, Momentjs, I use for all my date related functionalities. Momentjs is small javascript library for parsing, validating, manipulating and formatting dates. For more information check their website

Using MomentJS, I can do the date formatting to MM/dd/YYYY format by the following syntax.


MomentJS provides several formatting options. For more information check their website.
Coming back to knockout extender, let’s create an extender called dateformat which format the observable with the specified format.

    ko.extenders.dateformat = function (target, format) {
        var result = ko.computed({
            read: target,
            write: function (newValue) {
        }).extend({ notify: 'always' });

        //initializing with the formatted value

        //return the new computed observable
        return result;

We need to define this extender only once. In Durandal you can define it in the main.js.

This extender can be consume while defining the observable as below:

    var DateOfBirth = ko.observable(new Date('1/4/2000')).extend({ dateformat: 'L' });      

That’s all we need to do. The databinding in the view is same as earlier.

<span data-bind="text: DateOfBirth"></span>

You can use this dateformat extender throughout your website with different format options.