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")
                    .IncludeDirectory("~/scripts/foundation", "*.js")

                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: {
        'text': '../Scripts/text',
        'durandal': '../Scripts/durandal',
        'plugins': '../Scripts/durandal/plugins',
        'transitions': '../Scripts/durandal/transitions'

//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.
        app.setRoot('viewmodels/shell', 'entrance');

  • 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.

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.

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.