Microsoft Typescript

In the last few years Javascript has largely taken over the world, ever since we first laid eyes on Google Suggest and Outlook Web Access to see what could be possible using Javascript (and later AJAX) to make Web Applications as fluid and dynamic as desktop applications, Javascript has been a growing technology. (debatably outstripping it’s parent language Java which it now has little in common with)

The counterbalance to this is that Javascript brings all the bad old ways of any other scripting language – no intellisence, no compilation, difficult to use namespaces and well managed names, fairly poor error handling and a worrying tendency to code bloat.  These problems can be avoided through good development standards and carefully usage, but the language naturally leans into some difficult to manage areas for the average developer.

(how many Dynamics CRM projects have we seen with several hundred lines of Javascript stuffed into the onLoad event – it’s better in CRM 2011 with the proper use of includes Web Resources but can still be a problem)

Despite all these points – Javascript is used the world over because it works in all browsers and adds the vital scripting logic to support basic HTML.

Today however Microsoft have released a simple framework that acts to allow developers to build Javascript in Visual Studio in a more manageable C# Development format that then ‘compiles’ into native Javascript.

http://www.zdnet.com/microsoft-takes-the-wraps-off-typescript-a-superset-of-javascript-7000004993/

This is aimed at providing developers a more structured approach to writing Javascript – in a way this is slightly off-topic for CRM 2011 Consultancy and Development, but as a long-time fan of making sure all your CRM Javascript (whether in CRM 4 files, or CRM 2011 Web Resources) is developed in Visual Studio and stored in a source-controlled Project, is also in a way very on-topic for CRM 2011 development.

TypeScript Hello World

When learning anything new in the development world, it tends to help by stripping all the complexity or ambiguity away by producing the most basic usage imaginable – the hello world example.

First of all – you can download the Visual Studio 2012 extension for Microsoft TypeScript at the following link: http://www.microsoft.com/en-us/download/details.aspx?id=34790

This installs a new Project Type into Visual Studio:

Creating a new TypeScript Project in Visual Studio 2012

Creating a new TypeScript Project brings up a Visual Studio Project containing  the following files:

App.ts – the pre-compiled source file for the TypeScript, this our code for developing the program code which will be compiled into Javascript.

App.js – the raw Javascript which the TypeScript compiler produces from the App.ts

Default.htm – the HTML file which includes the ‘app.js’ as a normal Javascript include.

We can then edit our ‘App.ts’ code file using a more familiar C# syntax as way of writing the code at a higher level of abstraction to the underlying Javascript.

As way of an example, we could create the following simple object:

class MyClass {
    _activatedString: string = "(( hello world ))";
    _deactivatedString: string = ")) goodbye world ((";

    _myHTMLElement: HTMLElement;
    _stateElement: HTMLElement;

    constructor (outputElement: HTMLElement, stateElement: HTMLElement) {
        this._myHTMLElement = outputElement;
        this._stateElement = stateElement;        

        this.deactivate();
    }

    public click() {
        if (this.getActive() == false) {
            this.activate();
        }
        else {
            this.deactivate();
        }
    }

    private getActive(): bool
    {   
        if (this._stateElement.attributes["value"] == "true") {
            return true;
        }
        else {
            return false;
        }
    }

    private setActive(value: bool)
    {
        if (value == true) {
            this._stateElement.attributes["value"] = "true";
        }
        else {
            this._stateElement.attributes["value"] = "false";
        }
    }

    private activate() {
        this._myHTMLElement.innerText = this._activatedString;
        this.setActive(true);
    }

    private deactivate() {
        this._myHTMLElement.innerText = this._deactivatedString;
        this.setActive(false);
    }
}

NOTE: Proof of the TypeScript approach might be in whether WordPress’s CSharp engine is better than the Javascript engine for showing the source code here.

This gives us a simple object that encapsulates two HTML Elements, uses one as the object’s output and the other as a hidden element for storing the object’s viewstate. 

This compiles from the TypeScript to the following raw Javascript:

var MyClass = (function () {
    function MyClass(outputElement, stateElement) {
        this._activatedString = "(( hello world ))";
        this._deactivatedString = ")) goodbye world ((";
        this._myHTMLElement = outputElement;
        this._stateElement = stateElement;
        this.deactivate();
    }
    MyClass.prototype.click = function () {
        if(this.getActive() == false) {
            this.activate();
        } else {
            this.deactivate();
        }
    };
    MyClass.prototype.getActive = function () {
        if(this._stateElement.attributes["value"] == "true") {
            return true;
        } else {
            return false;
        }
    };
    MyClass.prototype.setActive = function (value) {
        if(value == true) {
            this._stateElement.attributes["value"] = "true";
        } else {
            this._stateElement.attributes["value"] = "false";
        }
    };
    MyClass.prototype.activate = function () {
        this._myHTMLElement.innerText = this._activatedString;
        this.setActive(true);
    };
    MyClass.prototype.deactivate = function () {
        this._myHTMLElement.innerText = this._deactivatedString;
        this.setActive(false);
    };
    return MyClass;
})();

In affect this is simply a clever use of the Javascript Prototype pattern which I’ve seen used for CRM 2011 Projects – but you can clearly see the similarities between the .ts and the .js, but the TypeScript here does seem to produce more human readable code and gives a set of syntax that is much in common with C#.

We also can leverage strongly typed fields such as string, number and HTML Element as opposed to Javascript’s var and object.

The big advantage to both OO Javascript and the TypeScript here is to instance the object as a single black-box unit of code, and potentially instance multiple times – so if we look at the HTML which will invoke this Javascript:

<body>
    <h1>TypeScript HTML App.</h1>
   
    <input id="t1_button" type="button" value="Click Me" />
    <input id="t1_state" type="hidden" value="false" />
    <div id="t1_content"></div>

    <input id="t2_button" type="button" value="Click Me" />
    <input id="t2_state" type="hidden" value="false" />
    <div id="t2_content"></div>    
</body>

We can see two sets of HTML controls which our script will use as (mostly) encapsulated objects:

window.onload = () => {
    // declare 1st instance of the class
    var myClass = new MyClass(document.getElementById('t1_content'), document.getElementById('t1_state'));
    document.getElementById('t1_button').onclick = () => myClass.click();

    // declare 2nd instance of the class
    var myClass2 = new MyClass(document.getElementById('t2_content'), document.getElementById('t2_state'));
    document.getElementById('t2_button').onclick = () => myClass2.click();
};

This gives us 2 simple controls each with their own viewstate:

The Resulting HTML Webpage using the Javascript compiled by the TypeScript – showing two controls with their own javascript managed viewstates.

And when working in the TypeScript Visual Studio environment – a good level of intellisense for using the classes we define:

Using the TypeScript Intellisense in Visual Studio 2012 for the MyClass type

So far, so normal web development, but this could provide a useful way of developing and producing (or at least managing) CRM Javascript and certainly could be a help for HTML Webresources.

Depending on how useful TypeScript proves to be for CRM Form Scripting and how much of the Object Orientated Intellisence model we can leverage, this could be a topic to keep in mind for CRM Development.

Handy TypeScript Links

I imagine this will expand depending on how popular TypeScript becomes, but the following links come from more experienced JavaScript developers looking into TypeScript from a similar Hello World perspective:

http://www.devcurry.com/2012/10/hello-typescript-getting-started.html

http://www.amazedsaint.com/2012/10/microsoft-typescript-and-quick.html

http://blog.markrendle.net/2012/10/02/the-obligatory-typescript-reaction-post/

Advertisements
This entry was posted in Consultancy, Development, JavaScript, Technical and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s