Friday, December 20, 2013

WebForms to SPA Modernization

With Single Page Application getting much attention now-a-days and is being treated as the next generation of web development. I wanted to get into that wagon. As of now there are two stable competitors providing SPA framework. They are Durandal and Angular. Both of them are popular and provide the necessary framework to build a SPA application.

I first tried to decide between Durandal and Angular for my development. In my analysis I felt that Durandal is a good fit for my situation. One of the primary reasons is that Durandal is a good fit for .NET development. Check my blog on this.

As my objective is not just to modernize this one WebForm app, but to actually onboard the SPA development. I cannot do this with just Durandal. I hence need to develop apps in both Durandal and Angular. As a startup I will use Durandal. Later I will get into Angular. I will blog on my learnings while modernizing my ancient web form application and also learning SPA.

Here are the blogs related to Web Form Modernization: (I will update this section continuously)

Thursday, December 19, 2013

JQuery UI MVC Extensions (Juime)

Juime (JQuery UI MVC Extensions) is an Imaginea’s open source MVC library which provides rich JQuery UI widgets without getting into the nitty-gritty details of javascript. Built on top of JQuery UI, it provides an easy but advanced themeable widgets that can be used to build rich interactive web applications that run on all major browsers. All this can be done without leaving the well-known MVC framework and without expert knowledge of JQuery.

Juime is a rapid application development utility which is aimed to improve developer productivity while building new generation web applications and reduce the need for learning of the JQuery UI & ajax. Further it can act as a quick jump start into the modern web application development. ASP.NET MVC developers feel home with this.

Juime was built on the following design principles to provide simple yet efficient developer experience:
  • Abstract complex JQuery and JQuery UI scripts
  • Lightweight as it has only dll and a minified javascript
  • Follows the ASP.NET Web Forms & MVC object hierarchy so that it is easily consumed
  • Cross browser support
  • Ease of use
  • Open source with community support

What is Single Page Application (SPA)

Long long back I read about Rich Internet Applications (RIA). As per the Wikipedia, RIA is a web application that has many characteristics of desktop application. RIA was to some extent achieved by using proprietary tools such as Silverlight, Flash, but this wasn’t truly achieved in Internet targeting larger audience. Up to now building a RIA using simple Html and JavaScript is a big pain and is not guaranteed to work on all browsers. Now-a-days the web technology has matured to certain extent that we can reliably develop RIA on Internet (cough..cough)

Single Page Application (SPA) is one of the recent tools that aids developers to bring RIA into reality for larger audience. It promises to provide better user experience and more closer look to the desktop applications which is what RIA’s goal is.

SPA by definition means one page application, in other words there will be only one page in the entire application or website. You can ask me, for any size application how this can be possible, how my entire site can has one page. Every site I have built or viewed has at least few pages and can spawn to several hundred pages. Then let me ask you this question, what does page mean to you?

As per definition a page is one which loads and unloads. If you count the number of pages loads and unloads in an application, then that application has that many pages. In SPA there will be only one page load and unload. If you observe gmail, yahoo mail or several other sites, there are no unloads and everything works on the same page.

This is paradigm shift of what you think of a page. Once we get a hang of this notation, SPA seems simpler. So in a SPA we load the page only once and all subsequent page changes or transitions are done through ajax or javascipt. As long the page structure (menus, footers, headers etc) does not change there is no need to change the page but we can change the page content through javascript.
Hence SPA is a single page application which shows different content based on the user needs without changing the base page or structure.

Wednesday, December 4, 2013

Two-way Data binding with Knockout

Two way data binding is a new concept for ASP.NET developers. Typically in web forms you might have bound to a GridView, DropDownList etc. This is one way binding. Once you bound the data to a control the data changes in the control are not reflected back to your source. For WPF or XAML developers two way data binding is a common concept. They embraced this binding from long time using the MVVM design pattern.

Knockout brought this two way MVVM data binding to the web. Knockout enables you bind your web controls in javascript. Once bound you can change the control values without DOM manipulation. Also the user changes are directly reflected in your model. In some situations Knockout also replaces you need for JQuery for DOM manipulation. Please note that this binding is done in javascript and is on the browser. ASP.NET MVC or Web Forms on the server side does not have the two way binding.

In this blog I will show a small example on how to do the two way data binding in javascript and manipulate the DOM and model objects.

As you see in the below screenshot there are two textboxes and a label. The label shows the full name entered in textboxes.

Whenever user changes any of the first name or last name textboxes the full name will automatically change. This is due to the magic of two way binding with Knockout.

Let’s see how to setup this two way binding.

First you need to download the latest version of Knockout. Which can be downloaded from its website

Here is the code using the two way binding
<html>
<head>
    <title>Two-way Data binding with Knockout</title>
    <script src="Scripts/knockout-3.0.0.js"></script>
</head>
<body>
    <h2>Person</h2>
    First Name: <input type="text" data-bind="value: firstName" /><br />
    Last Name: <input type="text" data-bind="value: lastName" /><br />
    Full Name: <span data-bind="text: fullName"></span>

    <script>
        var person = function (first, last) {
            self = this;
            firstName = ko.observable(first);
            lastName = ko.observable(last);
            fullName = ko.computed(function () {
                return firstName() + " " + lastName();
            });
        }

        ko.applyBindings(new person("Prasanna", "Kumar"));

    </script>
</body>
</html>

Here are the salient points from the above code

  • We first a ViewModel which stores the data. In the above example, person is the view model, with three properties, firstName, lastName and fullName. fullName is a computed field.

        var person = function (first, last) {
            self = this;
            firstName = ko.observable(first);
            lastName = ko.observable(last);
            fullName = ko.computed(function () {
                return firstName() + " " + lastName();
            });
        }
  •  In the above view model, the properties are bound by using ko.observable & ko.computed
  •  Once bound the properties should be accessed using ()
           return firstName()
  •  The textbox and label can be binded by using the data-bind attribute
       Last Name: <input type="text" data-bind="value: lastName" />
Full Name: <span data-bind="text: fullName"></span>
  •  Finally call the applyBindings to invoke the two way binding
              ko.applyBindings(new person("Prasanna", "Kumar"));

As you see Knockout made two-way binding very easy and with minimal syntax we were able to effectively do a two-way binding.

Thursday, November 28, 2013

ASP.NET SPA Recommendation

Please check the latest blog on this

If you are an ASP.NET MVC developer and considering SPA into your application, I recommend using Durandal. Unlike other SPA frameworks Durandal is built on top of several popular frameworks such as Knockout, JQuery and hence the learning curve can be less and can be adopted quickly.

Durandal heavily depends on KnockoutJS for databinding. KnockoutJS is backed by Microsoft. Hence it seems to be an easy choice. Please note that I am not recommending to go with Durandal as you are a Microsoft developer, but this should be one of your criteria.

Microsoft has a very good tooling support for Knockout and also Durandal. This tooling will help you to quickly adopt Durandal. (Recently VS 2013 started tooling for AngularJS). In addition Microsoft’s new TypeScript can make the Durandal development easy.

I have spent lot of time comparing other SPA technologies such as Angular, Backbone. After that I felt that Durandal is a good fit for my requirement. During my analysis it came again and again that Durandal is recommend for ASP.NET developers.


Monday, November 25, 2013

Modularize with RequireJS

What is modularization? Modularization breaks large code base into smaller blocks of manageable code, thereby improving maintainability, reusability and extensibility. Modularization when done properly decouples the functionality and reduces the dependencies.

Why modularization? Imagine a large application with huge amount of code, without encapsulation, with conflicting global scope, with huge dependencies, with tight coupling and developed with JavaScript. Now imagine you need to support this huge code base. Won’t it be easier if the code is properly managed with loose coupling and reduced dependencies?

Modularization sounds great and has been a tenet in all traditional programming languages such as C#, VB, Java. Developers in these languages code modularized code without even thinking about it. Unfortunately this is a big deal in JavaScript as the current version of JavaScript does not provide a clean way of modularizing the JavaScript code. So what to do now?

Thanks to the RequireJS, writing modular code is JavaScript is easier and you can do it now.

In this blog I will walk you through how to easily modularize your javascript code using one of the most popular and commonly used JavaScript library, RequireJS. RequireJS has several other advantages in addition to modularization, but in this blog I will only focus on modularization and walk you through converting a small javascript code into a modular javascript code using RequireJS.

Here is a small javascript code which calculates the discount for a product in an ecommerce application

function getPrice() {
    console.log("Getting price")
    return 120;
}

function calculateDiscount(price)
{
    console.log("Calculating discount")
    var discount = 10;
    return price * (100 - discount) / 100;
}

var actualPrice = getPrice();
var price = calculateDiscount(actualPrice);
alert(price);

The above code can be huge if have thousands of products and several discount promotions. Typically in server side code using C# we classify this code into classes as mentioned below.
  • Product object which returns the price of a product
  • Discount object which calculates the discounted price based on the promotion
  • Main or caller class which calls into this calculation 

RequireJS provides the similar approach in JavaScript. We can define Product, Discount and Main modules in Javascript and partition this code. Here is the modularized code using RequireJS

product.js
define([], function () {
    return {
        getPrice : function () {
            console.log("Getting price")
            return 200;
        }
    }
});

discount.js
define([], function () {
    return {
        calculateDiscount : function(price) {
            console.log("Calculating discount")
            var discount = 10;
            return price * (100 - discount) / 100;
        }
    }
});

main.js
require([product', discount'], function (product, discount) {
    var actualPrice = product.getPrice();
    var price = discount.calculateDiscount(actualPrice);
    alert(price);
});

As you see the product.js and discount.js scripts are enclosed with define attribute, but the main.js is enclosed with require attribute. The primary difference between these two are, require attribute defines and runs the code within. Hence you need require if you want to execute immediately. This is similar to the document.onload event.

On your page you just need to include the main.js and all the other javascript files will be automatically loaded by RequireJS. Here is the syntax for the script include tag.

<script data-main="scripts/main" src="scripts/require.js"></script>

RequireJS makes modularization easy and doable with today’s technologies. 

Thursday, November 7, 2013

TypeScript Debugging

Any programming language is not complete without good debugging capability. Remember the hours you spent trying to identify where the problem is. Debugging is particularly hard in JavaScript world as the tools are still emerging.

For transcompilers likes TypeScript debugging will be much harder without proper tools. The typescript you wrote will be converted to javascript and you may have to debug the javascript and not the typescript you wrote. Imagine how hard it will be to debug the code you haven’t written. Fortunately typescript provides a very good debugging tool which helps you to debug the code as you wrote in typescript and not to worry about the generated javascript.

TypeScript provides this debugging capability with the help of source maps. Source map is file used by browsers to map the javascript code with its original source code. Whenever you save the typescript file a source map file is automatically generated by the Visual Studio.


The actual debugging is similar to debugging the C# or VB code. Just put a break point and run the application using Internet Explorer. By default Internet Explorer recognizes the source maps.


When the debug point was hit the Visual Studio helps you step through the code as shown below


The debugger helps you exam variables, look at call stack and provide other features you typically use while debugging.

TypeScript provides very good tooling which helps easy adoptability. Debugging is one of those great tools.

Please go to my TypeScript blog series for other blogs in TypeScript.

Friday, October 25, 2013

TypeScript Up & Running

In this blog I will walk you through setting up TypeScript in your Visual Studio. Please check my other blogs on TypeScript for more information on TypeScript

As of now TypeScript 0.9.1.1 is supported only in VS 2012 and VS 2013. If you are using Visual Studio 2013, TypeScript is already installed. Hence skip the below installation steps and go directly to the next steps below.

VS 2012 developers download the TypeScript plugin from the below link


Running the setup file bring the below screens.
Follow the instructions and complete the setup.

Fire up the Visual Studio to start your first TypeScript application. You can create a Html Application using TypeScript by using the “HTML Application with TypeScript” template as shown below.




The above template creates a javascript project.
If you want to use TypeScript in your ASP.NET application, create the MVC project using your favorite template such as “ASP.NET MVC 4 Web Application” and add a TypeScript file by choosing adding New Item as shown below. I prefer to keep my TypeScritpt files under Scripts/app folder.

On the Add New Item Dialog choose the “TypeScript File” under the Visual C# as shown in the below screenshot
When you click Add you will be presented by another dialog asking about adding TypeScript Typings from NuGet package. The TypeScript Typings will add tooling support for popular Javascript files, such as JQuery, to your project.

You can search and add these typing files now or add them as needed by using the context sensitive menu. For now click “No”. This create a sample TypeScript file as shown the below screenshot

You can also add a TypeScript file using the context sensitive menu as shown below

By the above two options you can add a TypeScript file to your project.
Now as needed you can add TypeScript Typings for your favorite JavaScript files. I will walkthrough on how to add one for JQuery. On the Solution explorer right click on your JavaScript file and choose “Search for TypeScript Typings” menu option.

This will popup the NuGet package manager and performs search for the TypeScript Typings for the JavaScript file you selected (in our case it is jquery).

As you see above all the TypeScript Typings are packaged by DefinitelyTyped. Instead of NuGet packages you can also download these typings from the DefinitelyType GitHub site using the below link


The Typings from NuGet will be added as shown below.

Once we add all the necessary Typings we are up & running with TypeScript in our project.
Please go to my TypeScript blog series for other blogs in TypeScript. 

Monday, October 21, 2013

What's TypeScript

Here is the TypeScript’s definition from Microsoft:

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript and is a language for application-scale JavaScript development.

TypeScript is a not new language, but a thin layer on top of existing JavaScript strengthening it with tooling, IDE services and refactoring. It enables easy embrace of JavaScript while building enterprise applications using todays technologies (see my blog on this). Thanks to Microsoft, now everyone can build scalable large JavaScript applications targeting all browsers and platforms.

TypeScript is a superset of JavaScript which starts and end with JavaScript. All your existing JavaScript is TypeScript. Unlike other transcompilers, like CoffeeScript, TypeScript is a syntactic sugar built on top of JavaScript to support large applications and teams. By building on JavaScript, TypeScript can make your JavaScript development at very high level or close to the metal.

TypeScript is not a replacement for JavaScript and not for better performance or optimization. It only aids in writing, maintaining and verifying code. TypeScript estimates what happens during runtime and performs static checking while you are writing code thereby protecting you from unwanted side effects and dramatically increasing your productivity. It also incorporates design patterns and best practices. TypeScript also provide a mechanism for documentation and statement completion for most of your favorite JavaScript libraries.

The interesting thing about TypeScript is that the TypeScript’s compiler and tooling support is also written in TypeScript. With its local and non-intrusive code generation, TypeScript works wherever JavaScript works i.e., browsers, node, cloud, Windows 8 etc.

In this blog I outline the important features and tooling supported by TypeScript. In my next blog I delve into these in detail.

TypeScript Features:

The feature set of TypeScript is similar to that of any object oriented program such as C# or VB.NET. With these feature set Microsoft is trying for easy adoptability to JavaScript.
Type System
TypeScript as the name indicates provide an ability to define types in JavaScript. With the static types, TypeScript provides syntax highlighting helping you identify bugs before even running the code. These static types are supported for both variables and parameters. This type system is optional and is only used to aid writing code.

TypeScript supports all the primitive types such as number, string, boolean, null. It also support complex types such as DOM elements, custom types such as JQuery elements and a special type called Any

Class
Similar to other object oriented programs, TypeScript included Class syntax thereby making .NET and object oriented programming developers feel home and easily group related functions and variables within this container. Similar to classes in other programming languages, these classes helps in code abstraction, inheritance, reusability and maintainability.

TypeScript classes align with ECMA Script 6 proposal which supports classes in JavaScript.

Properties
TypeScript provides properties using get and set accessor declarations. These properties similar to that of the C# or VB.NET

Methods
The Method support is similar to that of JavaScript and other languages. TypeScript uses prototype to chain the method calling.

Interface
Interfaces helps to provide consistency across modules and teams. Interface also helps to provide documentations for custom or external JavaScript libraries.

Inheritance
Similar to OO, TypeScript provides Inheritance. The syntax is similar to that of Java with extends and super keywords

Modules
Modules are similar to the namespace concept in .NET. They wrap the classes in a naming container, help to organize the classes and modules and avoid naming collisions. They also provide a mechanism to exposes classes or have internal classes.

Accessibility
TypeScript provides accessibility options for classes and their members. The class members’ accessibility can be set by using public and private and the class accessibility can be restricted or allowed using the export keyword.

Open ended
Both the modules and classes are open ended, meaning you can define them in any place and they all belong to the same class or module. You can think of this like a partial class.

TypeScript Tooling:
In order to build enterprise scale JavaScript applications a robust tooling is needed. TypeScript provides such tooling in Visual Studio 2012 and Visual Studio 2013. TypeScript tooling is not limited to Visual Studio, but also support Eclipse, Web Storm, Sublime Text, emacs, and vim. But Visual Studio provides best developer experience.

Below are some of the tooling support in Visual Studio:

  •          IntelliSense and statement completion – TypeScript parses your team’s code and provides intellisense and statement completion, so that you don’t have to remember all the syntax. It also provides intellisense and statement completion for custom and popular javascript libraries using declare files mentioned below.
  •          Syntax highlighting – TypeScript helps you identify the coding issues while writing code by providing static error messages
  •          Refactoring and code navigation – Similar to C# or VB.NET, TypeScript has the same great code tools, such as Rename, Go to Definition, Go to Declaration.
  •          Automatic compilation – The TypeScript is compiled to JavaScript whenever it is saved or the Visual Studio project is compiled. Hence you don’t need to manually compile the typescript files.
  •          Declaration files – TypeScript uses these files to annotate the types for existing libraries such as JQuery and provide better tooling

Microsoft is planning to add more tooling support such as split screen view, generated code grouping in their next releases.

Try Out TypeScript
Microsoft designed a playground to try out TypeScript and it’s capabilities before deciding to use it in your project. In that playground they also included some samples.


With so many features and tools, TypeScript is must for application development and is too expensive in time for not having TypeScript in your armor.
Please go to my TypeScript blog series for other blogs in TypeScript.

Friday, October 18, 2013

TypeScript Hello Word

In this blog I will walk you through on how creating a JavaScript “Hello World” using TypeScript is similar to the C# or VB.NET’s “Hello World” app.

I will first create a Greeter class in C# which will return Hello World message when invoked. Later I will show how this class can be converted to a JavaScript’s Hello World with minimal changes, without learning or using JavaScript.

Here is my C# code of the Greeter class which greets when invoked.

    public class Greeter
    {
        string greeting;
        public Greeter(string message)
        {
            this.greeting = message;
        }

        public string Greet()
        {
            return "Hello " + this.greeting;
        }
    }

This Greeter can be invoked in a MVC view as mentioned below

    var greeter = new Greeter("World");
    @Html.Raw(greeter.Greet());

In order to convert this Greeter C# class to Greeter TypeScript class (or Greeter JavaScript function) you need to make the following two minimal changes:
  • In TypeScript there is no scope for class declaration. Hence public is not needed and need to be removed
  • The datatype declaration is different from the C# code. These are the changes for the data type declaration
    • string greeting -> greeting: string
    • string Greet() -> Greet() : string
Here is the TypeScript code for our Greeter class

    class Greeter
    {
        greeting: string;
        constructor(message : string)
        {
            this.greeting = message;
        }

        public Greet() : string
        {
            return "Hello " + this.greeting;
        }
    }

There is no change to the invoking code. As we are invoking this Greeter class from TypeScript instead of View, we have to change HtmlHelper to JavaScript alert

    var greeter = new Greeter("World");
    alert(greeter.Greet());

As you see with minimal changes we converted our C# code to TypeScript. Here is code in both C# and TypeScript juxtaposed.

C#
TypeScript
public class Greeter
{
    string greeting;
    public Greeter(string message)
    {
        this.greeting = message;
    }
    public string Greet()
    {
        return "Hello " + this.greeting;
    }
}
class Greeter
{
    greeting: string;
    constructor(message : string)
    {
        this.greeting = message;
    }
    public Greet() : string
    {
        return "Hello " + this.greeting;
    }
}
var greeter = new Greeter("World");
@Html.Raw(greeter.Greet());
var greeter = new Greeter("World");
alert(greeter.Greet());

As you see how natural it is for C# or VB.NET developer to move and adopt TypeScript in your code.

Please go to my TypeScript blog series for other blogs in TypeScript.