Sunday, December 16, 2012

Using TypeScript for Google maps API

After seeing Anders Hejlsberg video on TypeScript - ( lead architect of C# at Microsoft ) - I wanted to see how I can start using TypeScript for any of the current projects. Therefore, I created a page showing a Google Maps map.

TypeScript?

I'm assuming that you're familiar with TypeScript, but in short: TypeScript is a superset of JavaScript that adds more strongly typed behavior to JavaScript and is compiled to JavaScript. Therefore, everything in JavaScript is available in TypeScript, but also more: classes, interfaces, modules and more.

So, how do I get started?

Here's what I did:

Download and install TypeScript

First thing you need to do, is download TypeScript, and install it.

Then, you can either start a new project with the new project type 'HTML website with TypeScript', or you can just start using it an existing web app. I'm went for the last option, since I've got a sandbox project in which I try out different techniques.
So, what I did was create a TypeScript file in my /Scripts folder and started creating TypeScript.

To be honest, most of the times when I'm using JavaScript, I'm not taking full advantage of the weak typing in JavaScript. By far, most of the times I'm calling JQuery functions, JQuery plugins or other API's. At this point, I'm mostly interested in getting IntelliSense and compilation errors for calling the API's, than in building my own TypeScript domain with classes etc.

Get TypeScript type definitions

If you want to get started with calling the API's - you need to know the Definetely Typed repository on GitHub. This holds "TypeScript type definitions repository for popular JavaScript libraries.". The type definitions define the classes and interfaces of the API.

- Find the API you want to use, get the .d.ts file and place it in your project
- In your TypeScript, start 'using' this file by placing this at the top of your .ts file:


/// <reference path="GMaps.d.ts" />
/// <reference path="jquery-1.8.d.ts" />


Yes, JQuery as well, because it will give you awesome jQuery IntelliSense.

Now let's see what happens:



Sweet! JQuery with IntelliSense, thanks to the defintion files we loaded at the top. So, let's move on quickly create a new maps object:



That's easy too. However, the Maps class requires MapOptions in the constructor, which is an interface in the .d.ts file:

export interface MapOptions {
        backgroundColor?: string;
        center?: LatLng;
        disableDefaultUI?: bool;
        disableDoubleClickZoom?: bool;
        draggable?: bool;
        draggableCursor?: string;
        .....

So we need to create our own MapOptions that implements this interface like so:

     var opts: google.maps.MapOptions = {
         center: new google.maps.LatLng(-34.397, 150.644),
         mapTypeId: google.maps.MapTypeId.ROADMAP,
         zoom: 8
     };

     var map = new google.maps.Map(mapDiv, opts);

I just looked up the Google Maps API example and noticed that these three properties needed to be set. Pass this opts into our maps and we're set.

Compile .ts to .js

If you add a TypeScript file to your project, it does not automatically compile this file to a JavaScript file. You can change the .csproj file and make sure it does this when the project compiles, but you can also do it manually. I did the latter.

Since the NuGet console is basically a PowerShell console, i did it from there. First, navigate to the correct folder ( use 'ls' to list the items in the folder, 'cd' to change folder ). Use 'tsc [filename]' to compile the file:





In your page you just have to make sure:


  • You include a reference to jQuery
  • A reference to the Goolge Maps API with you API key
  • Have a div with id 'maps'
Like so:


And you're set!

Thursday, December 13, 2012

Using jquery.validate.unobtrusive with Twitter Bootstrap

I'm a fan of Twitter bootstrap! I love the looks and the cleanliness of the HTML and css. I'm also a fan of the unobtrusive validations in ASP.NET MVC. So, I tried combining the two, and it turns out to be as easy as 1,2,3.

Here's a snippet with displaying a person object. I'm using the layout that Bootstrap uses too ( with the control-div around the label and input )

Edit person @Model.Name

@using (Html.BeginForm(this.Html)) {
Fields @Html.HiddenFor(person => person.Id)
@Html.LabelFor(person => person.Name, new {@class="control-label"})
@Html.TextBoxFor(person => person.Name) @Html.ValidationMessageFor(person => person.Name, null, new { @class = "help-inline"})
@Html.LabelFor(person => person.Age, new {@class="control-label"})
@Html.TextBoxFor(person => person.Age) @Html.ValidationMessageFor(person => person.Age, null, new { @class = "help-inline"})
}


And here's the only thing required to make unobtrusive validations work with this markup:

    $.validator.setDefaults({
        highlight: function (element, errorClass, validClass) {
            $(element).closest(".control-group")
                .addClass("error");
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).closest(".control-group")
                .removeClass("error")
                .addClass("success");
        }        
    });
 
The result
Edit - it was already on StackOverflow for quite some time: http://stackoverflow.com/questions/10217175/mvc-twitter-bootstrap-unobtrusive-error-handling

Saturday, December 8, 2012

Method pre-condition checking: IF, Assert and Contract.Requires

Recently I picked up on a different way of checking method pre- and post-conditions in c#: Code Contracts. In this post, I'll describe the three methods that I know of by providing an example and checking unit-test behavior:
  1. Good old 'if ()' checking with throwing exceptions
  2. Assertions, from the System.Diagnostics.Debug library
  3. Code contracts, form the System.Diagnostics.Contracts library, shipped with .NET framework 4
I've been playing around with it and I'm trying to make up my mind if I prefer any of the System.Diagnostics ways over the 'good-old' IF and exceptions.

Everyone uses division in order to demonstrate illegal argument handling, since division by 0 cannot be done, so why should I do it any differently? Let's look at a method:

        public static int Divide(int numerator, int denominator)
        {
            return numerator/denominator;
        }

Now, what we want to do is make sure that the denominator is larger than 0. Using the three mentioned methods, it would look something like this:


        // CASE 1: Throws exception in case pre-condition ( denominator > 0 ) is not met
        public static int DivideWithExceptionThrowing(int numerator, int denominator)
        {
            if (denominator == 0)
            {
                throw new DivideByZeroException("Denominator should be larger than zero");
            }
            return numerator / denominator;
        }

        // CASE 2: Fails assertion if pre-condition is not met
        public static int DivideWithAssert(int numerator, int denominator)
        {
            Assert.IsTrue(denominator > 0, "Denominator should be larger than zero");
            return numerator / denominator;
        }

        // CASE 3: Fails to meet contract requirements in case pre-condition is not met
        public static int DivideWithContract(int numerator, int denominator)
        {
            Contract.Requires(denominator > 0, "Denominator should not be larger than zero");
            return numerator / denominator;
        }
In case the last way of checking the pre-condition is new to you, check out this excellent guide. Although the namespaces are included in .NET framework 4.5, you do need to download the Visual Studio add-on for code contracts ( even if you are using VS2012 ) from here. After that you have to open solution properties and go to the code-contracts tab in order to set things up.
Also - I needed to set CONTRACTS_FULL compilation symbol in order for my ReSharper to stop fading out my Contract.Requires line, saying that it will be skipped ( as described here ).

Note that I can set the exception that needs to be thrown in case the pre-condition is not met, using Contract.Requires<ExceptionType>() syntax.

So now, how should we unit-test our three methods? I've set up three tests that supply a zero as denominator. Therefore - I'm checking for the exceptions using the ExpectedException attribute for all of these cases:

        [TestMethod]
        [ExpectedException(typeof(DivideByZeroException))]
        public void Divide_DividesByZero_ThrowsException()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithExceptionThrowing(numerator, denominator);
        }

        [TestMethod]
        [ExpectedException(typeof (AssertFailedException))]
        public void Divide_DividesByZero_FailsAssertion()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithAssert(numerator, denominator);
        }

        [TestMethod]
        [ExpectedException(typeof(DivideByZeroException))]
        public void Divide_DividesByZero_FailsToMeetContractRequirement()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithContract(numerator, denominator);
        }

Note here that if you have set up static checking ( see the code contracts tab in project properties ) - you will see that the contract checking will point out that things are going to cause problems. Be sure to do this on the calling assembly - that is the test project in my case:


When running these tests, one will get a popup saying that the contract requirements failed to be met:


By clicking ignore - the test will continue, the exception will be thrown and the test will pass. However, this is inconvenient and we can easily disable this by setting the "Runtime Checking" to "None" on the assemblies that are being called by the test.

Now - it's happy testing from this point:


Bottom line...

Obviously the contract checking is more advanced and the other two:

  1. The most important benefit is of course compile time feedback on the written code. The static contract checking. You can detect an error even before running a test or the application.
  2. It's less verbose than the IF-Exception way, because it takes up a third of the number of lines.
  3. It provides more control over the exception that will be thrown than Assertions. As far as I know, either an AssertionFailedException is thrown or not.
I cannot find any downsides at this point. Feel free to leave any feedback about aspects I might have overlooked.

Thursday, December 6, 2012

Managing localized resources made easy

Working with resource files can become messy since ( as far as I know ), there is no way 'sync' the resource entries between the different cultures. Sometimes we find ourselves having entries defined in the en-GB locale, but not in nl-NL or the other way around.

As of today, we're using this tool: ResX Resource Manager on CodePlex. It does two things very well:
  1. Display the resource entry and the translations for each culture
  2. Indicate missing entries, that are not defined for all cultures


Just as I was writing this blog, I ran into another tool: http://resxmanager.com/. It's kind of a WYSIWYG tool for managing the resource files, directly on your website. Looks promising, however we're sticking with the CodePlex one.

Saturday, December 1, 2012

MoneyMedic API

I'm proud to anounce that I published my first NuGet package today. It's a wrapper for the MoneyMedic API. In order to get started with the MoneyMedic API, follow these steps:

1. Get the NuGet package

See the NuGet pacakge page

2. Load the MoneyMedic API module into your Ninject kernel 

The API is built as a Ninject module. I'm using interceptors for the API calls - so you need Ninject, Interceptors and load the API module into your kernel:

3. Start using the API 

For instance - getting the list of invoices in your account:

Unit testing guru: Roy Osherove

Sure, I learnt how to write unit tests in university. Writing tests to check if te result of adding two integers is actually the sum of the two. However, it took me some work experience to realize the powerfullness of unit testing. When trying to make my offshore team see how they could benefit from testing their code, my collegue found this website: the art of unit testing by Roy Osherove. He's the author of the book with the same name, which is on my to-read list. Roy is described on his blog as:
Roy Osherove is the chief scientist at Bouvet.no, and the author of The Art Of Unit Testing and Notes to a software team leader. He is also one of the original ALT.NET organizers. He consults and trains teams worldwide on the gentle art of unit testing, test-driven development and how to lead software teams. He frequently speaks at international conferences on these topics and others.
He's got hours of instruction video's and video's of his talks on his website. I see the most recent ones are talks he did on mock objects. What I find particularly interesting are his pair programming sessions - here. For instance this one:
Some of the lessons I learned from Roy:

  1. The first thing I noticed is how much attention he pays to naming methods, variables, parameters etc. etc. He is very perfectionistic about it. But I think it is because he forces himself ( and the guy he's working with ) to find the essence, the concept of the thing he is working on. 
  2. Not only make sure your code is very well readable ( maintainability ), but also make sure your tests are very intuitive and readable for the other teammembers. 
  3. ReSharper is your friend. He is a test-driven development guru and you can see him writing tests first and then take advantage of ReSharper to generate all the stuff that is not there yet. 


There is probably a lot more lessons I'll learn once I get through his hours of video's and his book. Anyway - check him out if you want to learn about Unit testing and TDD.