Monthly Archives: October 2012

Unit Testing with Typescript and Resharper

UPDATE –  I have been unable to get this to work with newer versions of resharper, hopefully full support is on the way from Jetbrains. I’d recommend using Chutzpa in the interim 

As a c# developer there are a few tools which I cannot live without. Visual studio obviously (and VS11 is the best yet IMHO) and the other is Resharper. When I write my c# code I like to follow TDD principles and ensure my code is highly testable. These days if I don’t have tests around my code I feel very exposed when refactoring, it’s this safety net that I want to ensure I have in the TypeScript world too.

In my previous post where I tested out some of the features of the TypeScript language I built a small GA based decrypter which can be used to crack a simple code. However I had no tests around this class and going forward if I am to feel comfortable working in TypeScript I’m going to need unit tests. The good thing about Resharper is that while it handles the day to day C# development tasks with ease, it also has a wealth of functionality for web technologies including JavaScript programming. Looking in the options under Unit Testing we can see that Resharper supports two different JavaScript testing frameworks, Jasmine and QUnit. I looked this up and it appears Resharper supported QUnit since v6 and Jasmine from V7.

This is encouraging as it means that I should be able to run my JavaScript unit tests within the Resharper test runner as I do in c#. As an aside, Jasmine is a more BDD style testing framework compared to QUnit which I prefer and maps closer to NUnit which is what we use at work.

In Visual Studio I created a new TypeScript project and copied my Decrypter class into a libs folder. I also created a new Tests folder where I added another new class called DecrypterTests which is where I will add all more tests. Now as I want to target QUnit for my testing I needed to understand the QUnit API. On their website it shows a very simple example of what it takes to create a QUnit test. Only two method are needed from the api those being “test” and “ok”.

test( "hello test", function() {  ok( 1 == "1", "Passed!" );});

Seeing as I want to work with QUnit in TypeScript and have full intellisense and static typing I need to create a TypeScript definition file. Definition files are a way for JavaScript library authors to create a separate file to their js library which applies static typing to the api. This static typing “evaporates” at compile time and resulting JavaScript is not impacted. As QUnit does not currently have a TypeScript definition file I manually created one in my project which covers the two methods I want to use.

declare module test {
    export function (description: string, method: Function): void;
}

declare module ok {
    export function (condition: bool, error: string): void;
}

You can see that there is not much to the definition file. When you add a definition file in TypeScript you are supposed to add a “.d.ts” in order to clarify that this has no implementation. Now I should have all the pieces in place so that I can write a test for my Decrypter class.

The method I want to write a test is the GenerateRandomKey method which is supposed to create random key which is 50 chars long. In order to test this functionality I now need to import 3 references into my test file. Firstly the TypeScript file for my Decrypter class, then its compiled JS file, and finally a reference to the QUnit definition file I created.


///<reference path="../libs/Decrypter.ts" />
///<reference path="../libs/Decrypter.js" />
///<reference path="../libs/qunit.d.ts" />

You may notice that I haven’t included a reference to the QUnit.js file. This is because Resharper handles this for us by references the file automatically when it goes to run the tests. Therefore we can just omit the references.


test("Decrypter Library - GenerateRandomKey", ()=> {

    //Arrange
    var decrypter = new Decrypter();

    //Act
    var key = decrypter.GenerateRandomKey();

    //Assert
    ok(key != null, "The key should not be null.");
    ok(key.length == 50, "The key lenght should be 50 chars long.");

});

After we have the correct references we can go about writing our test. This case is dead simple but illustrates the point. The QUnit.d.ts file provides me with full intellisense and type checking. The only thing left to do is run the tests to make sure they pass. I can do this in Visual Studio by right clicking on the “Tests” folder and choosing “Run Unit Tests”. Resharper automagically finds the QUnit tests and executes them.

So now we have the ability to write unit tests in TypeScript that target our TypeScript code and executing them inline without jumping back to JavaScript.

Hope this helps,

Advertisements

Decompiling Windows 8 Apps

So you’ve got Windows 8 install and all these cool news apps that you can download but  you want to learn more about how Microsoft writes its JavaScript apps or maybe you want to understand how secure your app code is?  Well here is a quick guide to gaining access to an apps directory and having a nose through all that interesting information.

For the sake of this post I will decompile Microsoft’s own live apps which are written in both JavaScript and some .net. The first thing we need to do is find out where these apps actually reside on our system.  And easy way to do this is open up task manager and find an app that runs inside of metro.  These are normally shown as “Suspended” when you’re in desktop so that makes them easier to find.

As you can see in my list of apps I have the Mail app running.  If select the mail app and then right click and choose “Open File Location”  I find that I am blocked by permissioning.

Ok so that seems right, Microsoft don’t want me looking at all their code so I will have to do a little more to gain access.  Of course I know I should have access as I need to run the apps so at the very least I should have read access.

If we look at the “Details” tab on task manager you will notice that the mail app is is nowhere to be seen.  This is in part due to the way Windows 8 runs JavaScript apps but also in part due to how the app has been built.   JavaScript apps running in Windows 8 require a container in order to execute. Basically it needs access to IE in order to perform rendering etc. Therefore Microsoft have created an exe called “WWAHost.exe” which hosts these kinds of apps.

That said we are not even 100% sure that the mail apps and people apps etc run in the container.  Therefore its back to our old friend process monitor in order to see what’s going on when we run the apps.   After a quick capture I can see that when running the Mail app there is a lot of activity in the process LiveComm.exe.

If I look at the process information for one of these entries I can find the location of where this process is actually running.

Ok that looks promising, taking the location of the exe and popping into explorer I can now browse directly to the folder and see its contents.  As expected this looks like the apps execution directory and we can see all the files for each of the common “Live” apps.

Now all you need to do is go browsing through the js files to learn how to develop your apps with the same way Microsoft has or dig our reflector for .net stuff.

You should be able to use this approach for most types of apps.  Obviously C++ apps will probably be the most secure when it comes to decompilation.  Also note, you cannot change any of files as all assets etc are digitally signed and will be checked when you try and run them in Windows8.

Happy hacking

Cracking a problem with TypeScript

Last week Microsoft announced TypeScript. A new JavaScript superset which adds static typing annotations as well as language support for classes and modules to the JavaScript language. As a C# developer since the .net 1.0 beta days, you can imagine I am pretty comfortable in a static languages and while that is fine most of the time the trend is for more apps to run in the browser. This normally involves me dusting off my JavaScript skills and entering back into the wild work of dynamic scripting.

It is this wild world of the future where HTML5 apps which run in the browser is where TypeScript should offer a lot of help to application developers. The concept of making coding in the browser easier is not a new one and languages such as CoffeeScript and Dart are showing that devs have an appetite for it. Both of the aforementioned languages have tried to tackle the problem in different ways, but what I like about TypeScript is that it is not trying to abandon JavaScript but instead apply a level or rigor to it that hopefully will become standards compliant in the future.

With all that in mind, I decided to build a little sample app to test out some of the features. Before you get started you will want to download the Visual Studio plugin to help with the development of your app. Also I recommend having a read through the TypeScript spec which has a wealth of information on what features the language offers. The app I decided to build was a little code cracker which is based on a Genetic Algorithm. This is not a very advanced implementation of GA as the fitness function and mutations are not very sophisticated. However is does give me the level of complexity I needed to test the language out.

The problem

In my app I wanted a simple ui where someone could enter a numeric code of 50 chars which I would then attempt to crack. Using a population of random keys to start with, each key’s fitness needs to be tested against the crack key, the strongest key based on fitness is the only survivor and its DNA becomes the basis for the next generation. Each generation has a mutation factor of 10% which ensures that the key should evolve over time an eventually the 50 char crack key will be found. Below is an example of my UI and my typescript code to run the algorithm.

$(Document).ready(() =>
{
    var decryper = new System.Crytography.Genetics.Decrypter();
    var crackButton = $("#crackCodeButton");
    $("#inputCodeBox").val(decryper.GenerateRandomKey());

    crackButton.click(() =>
    {
        var code = $("#inputCodeBox").val();
        var processingStatusElement = document.getElementById("processingStatus");
        var decryper = new System.Crytography.Genetics.Decrypter();

        decryper.Decrypt(code, processingStatusElement);
    });
});

Importing Libraries

This first thing you can see in this code is that I am using the JQuery library from within TypeScript. This is a fundamental design decision from the TypeScript team, in that any JavaScript library can be consumed within typescript with no changes required. What is also cool is that any JavaScript library currently out there can have an additional typing annotations file (think C++ header file) which a developer can import into their TypeScript project and start to work with the library in type safe way. This static typing on the api is one of the major benefits of using TypeScript IMHO.

Currently if a JavaScript library makes breaking changes to its api these changes can be very difficult to pick up in your code using tests alone. TypeScript will make this positively easy. A further benefit is that none of this typing information is outputted or checked in your JavaScript code which makes the resulting JS closely match your TypeScript. This I believe is an advantage over CoffeeScript and Dart for example which the resulting code can be vastly different from your source.

Namespaces, Classes and Interfaces

Next up I wanted to see how in TypeScript we can build hierarchical api’s with all the richness that we get in .net. Again I am no l33t JavaScript programmer so how you go about building hierarchical apis currently I am not sure but my hunch is that it cannot be done. I see a lot of people simulating OOP concepts like inheritance using protypes etc but all of these to me feel like hacks.

In TypeScript the designers have set about designing a language that they hope will fall inline with the emerging ECMAScript 6 standards. While there are no guarantees, I think this is a good strategy and one that shows their willingness to make TypeScript the most open of all the higher level browser languages. To support hierarchical namespaces in the language developers can use modules which allow classes and interfaces to be grouped under a logical area. In my sample I created a fake namespace using dot notation which TypeScript supports. One cool thing to note about modules is that you can define them across files, and the TypeScript compiler is smart enough to locate them all and show all your classes in the visual studio intellisense.

module System.Crytography.Genetics {

    interface IDecrypter {
        Decrypt(code: string, statusElement: HTMLElement);
        GenerateRandomKey(): string;
    }

    export class Decrypter implements IDecrypter {

        public Decrypt(code: string, drawingPanel: HTMLElement) {
        }

        private GenerateKey() {
        }

        private CheckFitness() {
        }

        private CreatePopulation() {
        }

        private GenerateMutatedKey(currentkey: string): string {
        }

        public GenerateRandomKey(): string {
        }
    }

}

In the code above you can see that I have defined a simple module with and interface and class for my Decrypter. What’s great about this is that interfaces become a first class citizen within TypeScript which means you build the appropriate levels of abstractions and code to contracts. A lot of the semantics of defining classes and interfaces from c# translate well into TypeScript and other than a few naming issues I found creating interfaces, inheriting them and defining functions and constructors etc to be very familiar. Full TypeScript code below if you’re interested in the detail

module System.Crytography.Genetics {

    interface IDecrypter {
        Decrypt(code: string, statusElement: HTMLElement);
        GenerateRandomKey(): string;
    }

    export class Decrypter implements IDecrypter {
        private _code: string;
        private _keyGenerated = false;
        private _workingKey = "";
        private _fitnessLevel = 0;
        private _keySize = 50;
        private _population = new Array(5);
        private _mutationPercentage = 10;
        private _drawingPanel: HTMLElement;
        private _generations = 0;

        public Decrypt(code: string, drawingPanel: HTMLElement) {

            var start = new Date().getTime();
            this._code = code;
            this._drawingPanel = drawingPanel;

            while (!this._keyGenerated) {
                this.GenerateKey();

                this._keyGenerated = this._workingKey == this._code;
            }

            var time = new Date().getTime() - start;

            this._drawingPanel.textContent = "It took " +
                time / 1000 + " seconds to decrypt the key.  Generation Count: "
                + this._generations;
        }

        private GenerateKey() {
            this.CreatePopulation();

            this.CheckFitness();
        }

        private CheckFitness() {

            this._generations++;

            for (var i = 0; i < this._population.length ; i++) {
                var keyFitness = 0;
                var key = this._population[i]

                for (var j = 0; j < key.length ; j++) {                     if (key.charAt(j) == this._code.charAt(j)) {                         keyFitness++                     }                 }                 if (keyFitness > this._fitnessLevel) {
                    this._fitnessLevel = keyFitness;
                    this._workingKey = key;
                    this._drawingPanel.textContent = keyFitness
                        + " of " + this._keySize + "chars found";
                }
            }
        }

        private CreatePopulation() {
            for (var i = 0; i < this._population.length ; i++) {
                var key = "";
                if (this._workingKey.length == 0) {
                    key = this.GenerateRandomKey();
                }
                else {
                    //Ensure strongest candidate survives.
                    if (i == 0) {
                        key = this._workingKey;
                    }
                    else {
                        key = this.GenerateMutatedKey(this._workingKey);
                    }
                }

                this._population[i] = key;
            }
        }

        private GenerateMutatedKey(currentkey: string): string {
            var newKey = currentkey;
            var charChangeCount = (currentkey.length / 100) * this._mutationPercentage;

            for (var i = 0; i < charChangeCount ; i++) {
                var index = Math.floor(Math.random() * currentkey.length);
                var newChar = Math.floor(Math.random() * 10).toString();
                newKey = newKey.substr(0, index) + newChar + newKey.substr(index + 1);
            }

            return newKey;
        }

        public GenerateRandomKey(): string {
            var key = "";
            for (var i = 0; i < this._keySize ; i++) {
                key = key + Math.floor(Math.random() * 10).toString();
            }

            return key;
        }
    }

}

.Netters will feel very comfortable

The language often feels like a blend of C# and Visual Basic. Little things crop up as you work with the language such as the way the “var” keyword behaves, mimicking the c# one with type inference. Also it helps that all the curly braces are in all the right places which is what you would expect from a c-based language. “Implements” for example is the keyword you use to inherit an interface which can map back to Visual Basic. Best of all however is that “Fat Arrow” “() =>” is supported so you can avoid the verbosity of “function”. I wonder if the design team made a conscious effort to do this or if it just naturally fell out. That’s said however, there are obviously enough differences to make TypeScript distinctly separate from both C# & VB.

Conclusion

Overall I found using TypeScript extremely satisfying and I am excited as to what the future hold for the language. We already know that they intend to support Generics. But long term could we see statically typed versions of LINQ, RX etc. Also the tooling I can see coming on leaps and bounds. I have already heard mutterings on twitter of TypeScript support from JetBrains which would be awesome!

If you want to try the app you can find it here.  Two words of caution however,  I only tested on IE10 and also I block the UI thread while performing the computation.  Yeah yeah I know……………..shoot me! 🙂