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.

Wednesday, October 16, 2013

Why I need TypeScript

If you are a .NET developer, not a JavaScript expert and want to develop large scale applications using the modern web technologies as mentioned in my blog, then you need TypeScript. TypeScript is for people who has little to moderate knowledge in JavaScript and don’t want to learn JavaScript.

As you know in the recent years JavaScript exploded and rapidly growing year after year. With its unprecedented growth, JavaScript is now expanding beyond browser to web servers, cloud, devices and Windows 8.  Unless you keep up with this growth you will be left out. TypeScript helps you to embrace JavaScript by simplifying your large scale JavaScript development and reduces the hardships in building such a large scale application.

TypeScript simplifies your development using the language syntax you are comfortable with. It is a superset of JavaScript and brings all the JavaScript goodness without the complexity of JavaScript. It generates clean and high quality JavaScript that runs in all browsers. Hence you don’t need to test your code in all browsers, thereby significantly reducing your QA time. Further it helps bringing structure into your JavaScript development.

Below are other reasons why you need TypeScript for your development:
  • TypeScript is JavaScript hence interoperability between TypeScript and JavaScript is simple and all your existing JavaScript is automatically TypeScript thereby allows you to continue use your existing JavaScript libraries
  • TypeScript integrates with your favorite Visual Studio and provides great tooling for your JavaScript development by adding statement completion, static typing, error checking  and debugging, thus allowing average developer to avoid the pitfalls while developing JavaScript
  • TypeScript provides the same great intellisense and compile time checking for most of your favorite JavaScript libraries such as JQuery. This is done with the help of its declare files. Using these declare files you can enable tooling for your own custom JavaScripts without modifying them.
  • The generated JavaScript runs on every browser and operating system making your development cross browser and platform compatible.
  • It enhances JavaScript by adding types, inference, structural constructs and modules. Thus making it look like modular and object oriented programming
  • It transcompiles to JavaScript code and aligns with the emerging ECMAScript6 standard.

With all the TypeScript goodness and Visual Studio tools, TypeScript dramatically increases developer productivity, reduces QA effort and provides overall web development productivity unlike any other  Javascript productivity tools. I am sure TypeScript will become a language of choice for every .NET developer.

Great TypeScript looks and sounds amazing. I am convinced that TypeScript is for me. How I can I get started?
Please go to my TypeScript blog series for other blogs in TypeScript to get started and know all about TypeScript.

Tuesday, October 15, 2013

TypeScript, a new JavaScript kid on the block


With ever growing demand on building large and scalable enterprise applications, you need right set of tools at your dispose. TypeScript is one of such and an absolute tool for your enterprise JavaScript development. With TypeScript, Microsoft addressed several problematic areas encountered during typical enterprise scale applications that heavily use JavaScript. They enables broad set of developers to building large scale JavaScript application with ease and reduced or eliminated the hardships in creating such large JavaScript applications.

Below are the series of blogs I wrote/writing on learning and using TypeScript in your small to large scale applications that leverage JavaScript.
With these series of blogs you will get all the information necessary to develop your small to large scale applications with TypeScript.

Tuesday, October 8, 2013

Technologies for Modern ASP.NET MVC Development

As the web technologies made a radical shift towards presenting better user experience, in this blog I try to list out all the technologies that needs to include while building a medium to large application using Microsoft.NET technologies.

Development Environment
  • Visual Studio 2013
  • HotTowel template for developing application using SPA
Browser Technologies
  • JQuery
  • JQuery UI
  • TypeScript
  • Technologies that are used by HotTowel template
    • BreezeJS
    • DurandalJS
    • Knockout
    • require.js
    • Bootstrap
  • HTML 5 & CSS 3
  • JQuery Validate
Server side technologies
  • .NET 4.5.1
  • ASP.NET MVC 5
  • ASP.NET Web API
  • Juime (a wrapper to JQuery UI)
Supporting Technologies
  • Automapper
  • Autofac
  • Json.NET
  • Elmah, Glimpse & MiniProfiler
  • Scale Out State Server for caching
Database technologies
  • SQL Server 2013 or RavenDB
  • Entity Framework
Unit Testing & Continuous integration
  • xUnit
  • Jasmine               
Source Control & Collaboration
  • Team Foundation Server

The above surely looks long. The beauty of web technologies is that they make all these technologies play well together.

On the server side we can try node.js as it has better performance over MVC. But I still prefer MVC as it is my core strength.
Please suggest additions, changes or subtractions from the above list.

Sunday, October 6, 2013

Building Single Page Application

Finally I decided to work on the Single Page Application. I have been postponing the learning and development applications in using SPA.

Now I got a website I need to develop to advertise the open source project (Juime), which I am working. I decided to develop this website using SPA and related technologies. Here are the technologies I am decided to use for this website

Development Environment
   ·         VS 2013 Preview
   ·         SPA using HotTowel template

Client Side Technologies
   ·         JQuery
   ·         Technologies that are used by HotTowel template
                o   BreezeJS
                o   DurandalJS
                o   Knockout
                o   require.js
                o   Bootstrap
   ·         TypeScript
   ·         HTML 5 & CSS 3
   ·         JQuery Validate

Server side technologies
   ·         .NET 4.5.1
   ·         ASP.NET MVC 5
   ·         ASP.NET Web API
   ·         Node.js

Supporting Technologies
   ·         Automapper
   ·         Autofac
   ·         Json.NET
   ·         Elmah, Glimpse & MiniProfiler

Database technologies
   ·         SQL Server 2013
   ·         Entity Framework 6

Unit Testing
   ·         xUnit
   ·         Jasmine               

The above technologies surely looks long. The beauty of web technologies is that they make all these technologies play well together.

On the server side I will initially use MVC on the server side and later replace it by Node.js.

I will blog everything I learned in the process of learning and developing my website using all the above mentioned technologies. But while blogging my main focus is in the SPA and its related technologies.

Saturday, October 5, 2013

Strongly Typed Fluent MVC Extensions

In my earlier blog, I blogged on how to create a fluent MVCextension. In that blog I created a simple Label extension with two fluent methods that are chained together. In this blog I will convert that Label extension to a strongly typed extension which takes the model property and binds to it.

Below is the code from the previous blog. I will add the strongly typed extension to this code.

    public static class LabelExtensions
    {
        public static Label FluentLabel(this HtmlHelper helper)
        {
            return new Label();
        }
    }


    public class Label
    {
        private string target, text;

        public Label Target(string target)
        {
            this.target = target;
            return this;
        }

        public Label Text(string text)
        {
            this.text = text;
            return this;
        }

        public override string ToString()
        {
            return String.Format("<label for='{0}'>{1}</label>Fluent", target, text); ;
        }
    }

We can easily make this fluent label to a strongly typed fluent extension by adding an additional extension which takes model as the input parameter. Below is the code for this:

    public static Label FluentLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
                                        Expression<Func<TModel, TProperty>> expression)
    {
            //getting the name
        var name = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        return new Label().Text(metadata.Model as string);
    }

With this addition extension we can make our Label as strong typed model Label. Here is how we can consume this Label

       @(Html.FluentLabelFor(m => m.Name).Target("firstName"))