Category Archives: Uncategorized

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

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! 🙂

Windows phone 8 to support chat rooms?

More digging into the emulator images for wp8 has thrown up more interesting finds that should be coming to the platform come the end of this yeat.  This time it looks like Microsoft has some interesting plans for the already cool “groups” functionality.

Digging through the resource files I have numerous mentions to “rooms” being supported.  From what I am gathering this feature would be an addition to the groups functionality whereby you should be able to add a group of your friends to a chat room and all chat live.  Super cool!

This resources are used by the contactsres.dll in system32 and I have a couple of snippets for you below.

Gather your friends and family together. Invite them to a private Room where you can share a calendar, photos, group chat and notes. Or add them to a Group to see social updates from just those folks and text them all at once. Tap the plus sign to get started.

This room will be deleted. You can create a new room in the People Hub.

1 people left the room

Room membership has changed

I must admit this feature sounds awesome and if it turns out to be true fits perfectly in-line with windows phone being the premier social networking phone.

Will WP8 have new parental control features?

Been looking over the WP8 emulator images today and came across this interesting resource string.

The My Family settings for your account prevent you from downloading this item. Your parent can manage My Family settings at windowsphone.com.

This resource string found in the common mobile UX resources seems to suggest that a new feature called “My Family” will be coming to WP8.

WP8 SDK Silverlight Alive!……XNA Dead……Native XAML gone missing!

I suppose you guys have heard that the windows phone 8 SDK has leaked. Well I decided to download the bits and have a quick look around.  This  post is really just summary of some interesting observations I made.  If you want to download the bits yourself you will have to hunt around. I found it on on a torrent site and had good seeding.

Where is the winRT support? 

One of the first things I did once I had installed the SDK was to run up Visual Studio 2012 and see what projects types were available.  What caught my eye was the fact that there appears to be no “Metro style” or “WinRT” project templates installed.  The naming of the projects is pretty much the same as the 7.5 SDK. I’m sure that’s a good thing as you don’t want to confuse people right? Below is a screenshot of the project picker.

You can see I have highlighted a new project type which never used to exist in the 7.5 SDK.  I’ll come back to that shortly.  As winRT tech does not seem to be obviously visible in the project list it seems I will have to dig a little deeper.  Lets see if creating a standard “Windows Phone Application” will provide more detail as to what’s going on in this new release.

new apps for WP8 wont be running on winRT aka native xaml but instead managed xaml

Well that’s a turn up for the books.  From what I can tell these new apps for WP8 wont be running on winRT aka native xaml but instead managed XAML.  To me that looks like standard CLR namespaces being imported and therefore is managed code. Also it seems I have classes that aren’t available in winRT such as RadialGradientBrush. Digging out jetbrains dotpeek proves exactly that, the whole runtime is silverlight.

This raises a couple of questions, firstly why did Microsoft put so much effort into creating native XAML and then not adopt it for WP8?  Secondly what does this mean for developers wishing to develop across 3 screens?

The first question I think is easily answered, it is likely to be timing issue. With the monumental effort to get Windows 8 ready for its October release there probably hasn’t been time to migrate the winRT tech & tooling to WP8. Further, developers who have already created apps on the platform do not want to have to rewrite them for winRT.  Especially as winRT is equivalent to Silverlight 2.0 at the mo and would lead alot of gaps.

 If you’re a html5 developer building apps for winRT and you want to port them to WP8, well you are royally screwed at the moment

The second question is difficult.  It seems the one dev platform for all screens is not here yet. Although porting code is possible it’s not going to be smooth given the current situation. If you’re a html5 developer building apps for winRT and you want to port them to WP8, well you are royally screwed at the moment.

One last point on this, it seems C++ devs get a raw deal as they wont be able to leverage XAML on WP8.  Well not until winRT arrives.  From what we have heard from Microsoft, the key deliverable for this release was about providing native code access.   This is so that all those game developers who need to extract every cycle of  performance out of platform can do so.  It will be good to see popular games from iOS transitioning quicker to WP8.  But that leads to the next topic….

What’s the deal with XNA? 

Well I think with WP8 SDK I think you can official say goodbye to XNA.

One of the other big questions hanging over the the future of WP8 was what’s happening to XNA.  Well I think with WP8 SDK I think you can official say goodbye to XNA.  In this new SDK you only seem to be able to create XNA games that target WP7.1. If you want to use XNA in WP8 then it seems you are out of luck.

But the story gets a little worse than that,  if you remember in my screenshot above I highlighted a new project type called “Windows Phone Direct3D XAML Application”.  Well the good news is that this project can target WP8, however on creating one of these projects your actually going to be developing your game in C++.  The project is set up with a simple c# xaml app with a DirectX drawing surface, then all your access to DirectX must be written in native code.  I can’t see XNA coming back from this personally but hey, you never know. Microsoft are anything from consistent these days.

All in all this leak is a bit of mixed bag, while the WP8 platform looks to be getting some cool new features the dev story is a mixed one.  A few bullet points below for the guys that don’t want to read my waffle above.

  • Managed xaml lives on in WP8
  • winRT is nowhere to be seen
  • 3 Screens development story not being realised in this release.
  • Native code now available on the platform
  • XNA is left out of the WP8 party
  • If you want to build games then dig your C++ book out

Coding challenge: Reading an LCD display

If you read my previous post “Coding challenge: Creating an LCD display” then you will remember I was set a challenge by a friend of mine to create a function that would take an integer and produce a LCD display inside of a console window.

Well I got a follow up challenge from him this week which went like this.

This week’s kata is simply the inverse of last week’s … instead of taking a number and producing a “LCD display”, the task this week is to accept an LCD display and produce a number.  Numbers will always be 3 lines high and 3 characters wide: The easy version: accept a single digit in a single and return the numeric value. The harder version: accept a multi-digit display and return the numeric value.

So with the challenge set it was time to attack the problem.  Again the real difficulty that presents itself in this challenge is the fact that the data must be read line by line.  Therefore you must track the pattern of each digit as you move down through the data and only once you have that data can you start to make some decisions.  First however I still set myself some base rules for this challenge. I have listed them below.

  • All numbers through 0-9 must be matched.
  • Each number must be easily encoded in order to compare with the input data.
  • Extracting the number of digits from the input data can be worked out given the fixed size of the challenge.
  • Each digit being pattern matched must be encoded in the same way as the list we will compare against.
  • We will need to avoid the blank lines in the data.

Given all these, here is my code below. Lucky for me I could seed my function by using the draw method from previous post so made it easier to test.

First I created a unique encoding of all the numerals from 0-9 using a simple read of each line and concatenating the strings together.  This pre-computer value saves time and should be easy to compare against.

        private static Dictionary<string, string> GetMatchPatterns()
        {
           return new Dictionary<string, string>
                        {
                            {"0", " - | |   | | - "},
                            {"1", "     |     |   "},
                            {"2", " -   | - |   - "},
                            {"3", " -   | -   | - "},
                            {"4", "   | | -   |   "},
                            {"5", " - |   -   | - "},
                            {"6", " - |   - | | - "},
                            {"7", " -   |     |   "},
                            {"8", " - | | - | | - "},
                            {"9", " - | | -   | - "}
                        };
        }

And below is the main Read method that actually does the pattern matching.  It’s fairly concise this time round.

        private static string Read(string number)
        {
            var patterns = GetMatchPatterns();
            var stringReader = new StringReader(number);
            var line = stringReader.ReadLine();
            var nCount = (line.Length / 4) + 1;
            var chars = new string[nCount];

            while (line != null)
            {
                for (int i = 0; i < nCount; i++)
                {
                    var currentPos = (i * 3) + i;
                    var data = new string(line.Skip(currentPos)
                                               .Take(3)
                                               .ToArray());
                    chars[i]= chars[i] + data;
                }

                line = stringReader.ReadLine();
            }

            return chars.Select(c => patterns.First(kc => kc.Value.Equals(c)).Key)
                        .Aggregate((a, b) => a + b);
        }

Performance seems good with rendering of the LCD representation of 1234567890 in around 140 ticks.

Stack vs Heap

So in relation to my last post on the LCD coding challenge.  A few more examples came up for solving this kata.  As we were discussing memory and speed etc I casually stated

Well if you convert all you classes to structs then that should make things faster.

I’ve heard this a lot but it occurred to me that I have never really tested the theory.  Also I couldn’t answer the question on everyone’s lips which is how much faster.  Therefore I put a quick spike together to test this and below are the results.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Testing creating 100,000,000 heap objects");
            for (int j = 0; j < 10; j++)
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                for (int i = 0; i < 100000000; i++)
                {
                    var person = new PersonClass();
                }

                stopwatch.Stop();
                Console.WriteLine(string.Format("Elaspsed ms: {0}", stopwatch.ElapsedMilliseconds));
            }

            Console.ReadLine();
        }
    }

    public class PersonClass{}

    public struct PersonStruct{}

And below is the summary of the results.  I create 100 million class heap objects and the same number using structs.  I run this in a loop 10 times.

Testing creating 100,000,000 heap objects
Elaspsed ms: 850
Elaspsed ms: 824
Elaspsed ms: 820
Elaspsed ms: 809
Elaspsed ms: 825
Elaspsed ms: 850
Elaspsed ms: 809
Elaspsed ms: 803
Elaspsed ms: 793
Elaspsed ms: 794
Finished!

Testing creating 100,000,000 struct objects
Elaspsed ms: 255
Elaspsed ms: 248
Elaspsed ms: 246
Elaspsed ms: 251
Elaspsed ms: 244
Elaspsed ms: 245
Elaspsed ms: 245
Elaspsed ms: 248
Elaspsed ms: 244
Elaspsed ms: 246
Finished!

As you can see creating the structs are way quicker as we are no longer allocating memory on the heap and are avoiding putting pressure on the GC.  Based on this non-scientific test we would average over 3 times quicker. 

Moral of the story, if you need to create a lot of simple throw away objects in memory and you want the best performance then consider converting your objects to value types.