With a dash of JavaScript

Visual Studio

Post navigation

Worker and Web Roles are some of the great features that Microsoft Azure has to offer. These two features are designed to do computation for you in the cloud. A worker role is basically a virtual machine that can be used as a back-end application server in the cloud. Similarly, a web role is a virtual machine hosted in the cloud, but the difference is that this one is used as a front-end server that requires Internet Information Services (IIS). So you can use a web role if you want to have an interface exposed to the client – for example an ASP.NET web site – that makes interaction from the outside possible.

In the following tutorial, I will focus on web roles. I will show you how to create a web role and host it on an Azure web site. The web role’s task will be to launch a console application – which is a path finder algorithm that I wrote in C++ – that reads input from the client, computes and then returns results. The reason for choosing a web role for this, is to make communication possible through REST, so the client can use a web site or simply do a GET request to fire up the console application in the cloud and get back the results as JSON.

Creating the Azure Web Role

The first step is to download the Microsoft Azure SDK. Since I’m a .NET developer, I downloaded the Visual Studio 2013 version. The SDK includes an Azure emulator, that we will be using locally. The web role has to be hosted somewhere, we will choose a cloud service for that. So, start up Visual Studio and create a Windows Azure Cloud Service project:

Choose ASP.NET Web Role:

Choosing the front-end stack type is up to you, I choose an MVC Web API without authentication:

Go to the WebRole class in the WebRole project and set a break point inside the OnStart() method. Now build and run your cloud service, you will see that an Azure Compute Emulator is started up and the break point is reached:

Press F5 to continue. Your web role web site is now up and running. Right click the Azure Compute Emulator icon in the task bar, and choose “Show Compute Emulator UI”. A new window shows up, click on your web role in the left column:

This shows you the status of the web role. A web role inherits the abstract class RoleEntryPoint that has three virtual methods; OnStart(), Run() and OnStop(). These methods are called as their name suggests and can be overridden. We already overrode the OnStart() method as we saw earlier. Now, the next step is to launch the console application as a process from the web role.

Starting a Console Application Process from the Azure Web Role

Delete the default override of OnStart() in the WebRole class. We want to call a custom method from our web role independently. Create an interface IWebRole that looks like this:

Make WebRole implement this interface. RunInternalProcess(string stringParams) is a custom method that we will call from the client. The method will then launch a console application process and return results back to the client as JSON. We want the process to do the operation asynchronously. Here is part of how the implementation looks like:

As you can see, the method starts a process called TSP_Genetic_Algorithm.exe which is included in the project. It’s important to set the “Copy to Output Directory” property of this executable file to “Copy always”, such that it’s always copied to the project directory. You can do this by right clicking the executable, and choosing “Properties”:

The next step is to make the client call up the web role through an HTTP GET request.

Calling the Azure Web Role from the Client

We need to make it possible for the client to call the web role, we will do this by creating an HttpGet ActionResult. Go to HomeController and inject the WebRole interface there:

This GET request takes in an array of string coordinates, calls the web role with these coordinates, which in turn launches up the process with the input and then finally return the results back to the client as JSON. Beautiful, isn’t it? Build and run your cloud service. Now type this in the browser address field:

The final step is to publish our Azure cloud service so it goes online. This process is pretty straightforward, but it assumes that you have a Microsoft Azure subscription and a target profile. Once you have registered a subscription, right click the cloud service project and choose “Publish…”:

Go through the wizard to create a target profile:

Enable Remote Desktop if you want remote access to your virtual machine in Azure, this is pretty handy. Once done, click on Publish in the last dialog:

The publishing process will start in Visual Studio:

And then complete:

That’s it! Your Azure web role web site is now online, and you can now do the GET request through the web:

You can go to the Azure Portal to view statistics and maintain your web role there:

As part of a dedicated refactoring team in a big customer project, I get to use JetBrains ReSharper quite heavily on a daily basis. If you didn’t know already, ReSharper is the best refactoring tool made for Visual Studio. Not only does it increase programming efficiency by multitudes, it also changes the way you think as a programmer. Especially when you’ve just started out on your programming career. I’ve been using ReSharper professionally for at least three years, and today I can’t even imagine how I survived as a (.NET) programmer without it.

Ironically, it wasn’t until I joined a professional refactoring team that I discovered the downfalls and anti-patterns of using ReSharper. Without doubt, the tool is continuously being developed by a brilliant team, so the downfalls that I see today may very well be investigated in the next versions of the tool. There are also some features that ReSharper simply lack today, that I hope will be added in the future. I will explain what I am talking about in the next sections.

Helper Methods are Extracted as Static by Default

If you press Ctrl+RM you’ll get the option to extract a method. A local helper method is by default extracted as static:

You get to choose whether to make it static, but it is static by default. You’ll find that this is extremely annoying, as there is a chance that you have to insert non-static content in the method at a later time. So, the fix? Remove the static part manually (!). Note, in the following animation below, the lack of intellisense as I start typing the _webRole object:

This may not be a big deal in a small project, but it quickly becomes cumbersome in a big legacy application.

Lack of Listing Multiple Object Properties Feature

Very often you will create objects and want to set their properties. There is no way to list all the properties of the created object, leaving you having to manually type and set each property:

Wouldn’t it be nice to have ReSharper list all the properties for us?

Lack of “Find Usages in Multiple Solutions” Feature

One of the most fundamental things when you are refactoring a huge application with many solutions, is the ability to locate the usage of a component across those solutions. If you right click on a class or method and choose “Find Usages Advanced…”:

ReSharper will show you a dialog where you can choose where to search:

What would be nice is to have the option “Solutions…” where you can specify solutions or simply choose all. This makes our life easier, and saves us the need to open each solution manually and perform the search per solution.

Refactoring Overkill

This one falls under anti-patterns. Every now and then, ReSharper will suggest refactorings that actually break readability of your code. Inverted ifs and complicated LINQ expressions fall under this category. How many times has ReSharper asked you to invert your if statement when it looked perfectly readable? Or how many refactorings were you asked to do by ReSharper on your one single LINQ expression? Chances are, many times. There is no need to invert your if, if you and your code reviewer agree that it looks fine. Although you can probably turn off this type of suggestion, ReSharper should be intelligent enough not to ask you to do this.

Complicated LINQ expressions, where do I start? Once you write a LINQ expression that does something, ReSharper will often suggest to write it differently. As the expression gets more complicated, so does ReSharper. It will ask you to keep refactoring, sometimes up to 3 times (!) on a single LINQ expression. The ending result is a hideous piece of code that takes time to understand. So again, ReSharper should be intelligent enough to take readability into account here.

Different Key Binding Schemes?!

Something that has annoyed me recently is that the key binding schemes of ReSharper seem to vary from environment to another. Ever since I installed ReSharper 8.1 (which I upgraded to 8.2 today, by the way), the schema on my development machine has changed, and I have to memorize different key bindings. This is a hassle when I do pair programming with another developer using his machine, as he would have the older schema. Ultimately I memorized both schemes in order to work efficiently. You would think that simply applying the Visual Studio schema would make things consistent in all developer machines:

In final words, ReSharper is a wonderful refactoring tool that I will be using for years and years to come. That doesn’t by any means make it perfect, and there are still features that I see lacking. Seeing how the ReSharper team is doing an incredible job developing the product (ReSharper 8.2 was just released), I’m not worried that they’ll look into this and make our favorite tool even better. 🙂

I wrote a genetic algorithm (GA) back in 2011 to solve the traveling salesman problem (TSP). I wrote the algorithm in C++ and made a recording of the algorithm that I later uploaded on YouTube. It was during the time that I was obsessed with algorithms. While having a major interest in GAs, my primary focus was on writing a new algorithm to efficiently solve the boolean satisfiability problem (SAT). Which I eventually did, getting my results published in the Scientific Research Journal. Oh, those were fun times! So the recording of the GA has been on YouTube for close to 3 years, and has over 10000 views today. I thought I’d share it with you:

The video shows my algorithm solving the TSP problem, where the number of cities is 100. I used an elitist approach here, with 60 % order crossover, 10 % mutation and the algorithm ran for 10000 generations. What you see is the cities being plotted on a circle, and the different paths being computed by the algorithm. Instead of showing you the different paths, I probably should have only showed you the best paths being picked (elitism). But if I had done that, you wouldn’t have been able to see so many pretty lines being drawn.

If I were to re-write the algorithm today, I would have made it better in many ways. Primarily in terms of readability of the code, but also structurally. Oh, and I wouldn’t use a crappy laptop with 2 GB of RAM 🙂

A release candidate version of TypeScript was finally released last week. New features have been added along the many bug fixes that were made. As of the Spring Update CTP2 for Visual Studio 2013, TypeScript is now fully supported making it a first class citizen. That means after getting the Spring Update CTP2, you won’t need to download TypeScript as a plugin to Visual Studio 2013. Notable features that have been added are simpler, more generic type declarations and order declaration merging of interfaces. Improvements to the lib.d.ts typings library have also been made, adding typings support for touch and WebGL development, making your life easier when working with HTML 5.

Generic Type System

The typing has been enhanced, making it more flexible. It is now possible to use any more freely, making type checking especially softer when working with inheritance. Consider the class Person that extends Human:

Giving the property eyeColor type any in the subclass was not possible prior to the RC version. Giving this possibility now, you are not forced to define the specific type found in the super class, which may be inaccessible at times. When it comes to generics, the same thing is possible. Consider the interface IPerson with a generic function and the implementing class Person:

In addition, declaration merging of interfaces is now also possible. This makes precedence order easier when you work with external libraries. Say you have external interfaces IExternal with some functions:

Notice the precedence order of the declared functions. Declaration merging is absolutely recommended, especially when you don’t want to change how the external libraries are initially referenced in your web application.

These are awesome features from the TypeScript team! I am happy that the community influenced the team to add these features, and I also would like to congratulate the team on reaching version 1.0. Well done! 🙂

AngularJS is largely growing in popularity among front-end developers. According to a JavaScript developer survey conducted in 2013, it was shown that AngularJS was among the top two most used JavaScript frameworks. In a world where there are close to 17 million MVC JavaScript frameworks, this puts AngularJS on top of the game. On the other end of the scale, while not as widely used as AngularJS, TypeScript is slowly becoming the de facto compiler language for writing object oriented JavaScript. So what happens when these two forces meet? A great power emerges! We learned from Uncle Ben (Spider-Man movie) that with great power, comes great responsibility. In this tutorial, I show how these two forces can be combined to produce an ultimate web application.

In AngularJS you create an app.js where you load your modules, controllers, factories and directives. You do almost the same thing in TypeScript, the only difference here is that your controllers, factories and directives are represented as TypeScript classes in an app.ts file. So your app.ts can look like this:

Note the usage of lambda, we do this to reserve lexical scope. Always make sure to use this instead of function() in TypeScript. Now that you’ve set up your bootstrapper, in the next sections we’ll look at how the individual AngularJS components are written in TypeScript.

Controller Classes

Controllers are written as classes, so your MyController.ts class can look like this:

Now if you want to call your TypeScript class methods from your HTML in IE 8 without an alias, then you need to hook your methods (and everything else they use) onto the Angular scope. This can be done like the following, in MyController.ts:

If you haven’t checked it out yet, Portable Class Libraries (PCLs) make it possible to write cross-platform .NET applications targeting multiple platforms and using the same code logic base. Combining this with Xamarin, you can target other platforms such as iOS, Android and Mac. That’s right, it means you can write C# code for those platforms. Pretty amazing, right? PCL comes with Visual Studio 2012. In the following tutorial, I explain how you can create a cross-platform app for Windows Phone 8 and Windows Store, using PCL and the MvvmCross framework to separate concerns.

Setting up the Environment

PCL comes out of the box with Visual Studio 2012, but I recommend that you use Visual Studio 2013. The reason is that you can choose to include the Windows Phone 8 SDK upon installation, and the Windows Store templates come out of the box with VS 2013. The Windows Phone 8 emulator uses Hyper-V, and since we will be creating an app for Windows Store, that means you’ll need at least Windows 8 Professional installed on your machine. Once you’ve got VS 2013 with the Windows Phone 8 SDK installed on your Windows 8 Professional OS, we’re ready to get started.

Note: You can target other platforms by installing Xamarin, but this is not required in this tutorial.

We will start by setting up our PCL. First, delete Class1.cs. Now right click the PCL project and choose Manage NuGet Packages… Search for “mvvm cross” and install “MvvmCross” through NuGet. Delete the ToDo-MvvmCross folder. Go to FirstViewModel.cs and change “Hello MvvmCross” to “Hello World!”:

We’ve finished setting up our PCL. Now navigate to the Windows Phone project and delete MainPage.xaml. Right click the project and choose Manage NuGet Packages… Search for “mvvm cross” and install “MvvmCross” through NuGet. Delete the ToDo-MvvmCross folder. Now right click References and choose Add Reference… Click on Solution -> Projects and choose the PCL project. Now navigate to the Setup.cs class, this class sets up the data binding to our view model among other things. Change it to look like this:

That’s it! Build and run the Phone project, the emulator should start up:

Let’s move on to the Windows Store project. Delete MainPage.xaml, right click the project and choose Manage NuGet Packages… Search for “mvvm cross” and install “MvvmCross” through NuGet. Delete the ToDo-MvvmCross folder. Now right click References and choose Add Reference… Click on Solution -> Projects and choose the PCL project. Now navigate to the Setup.cs class, and make sure it looks correct:

Navigate to App.xaml.cs and remove the following code from the OnLaunched method:

if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}

Delete FirstView.xaml. Right click the Views folder and add a new Basic Page, call it “FirstView.xaml”:

You’ll note that a new folder called Common with helper classes was added to the project. Go to FirstView.xaml.cs and make the class inherit from MvxStorePage instead of Page. Remove the methods OnNavigatedTo and OnNavigatedFrom methods. The class should now look like the following (comments removed):

And we are done! Both applications now use the logic written in the Portable Class Library, and you only need to write the logic once. Pretty cool! Now you can go ahead and make some awesome cross-platform apps. 🙂

So I finally got around to play with TypeScript, a (optionally) typed scripting language that compiles to JavaScript. TypeScript is great especially because of how easy it is to use to bring object oriented design into your JavaScript code. TypeScript code is written in TS formatted files that get compiled into JS. It’s quite easy to learn the syntax and get started with the language. It’s open source and you can get it as a plugin for Visual Studio, which gives full debugging capabilities and rich editor tooling. After installing the plugin, you can either start a TypeScript project in Visual Studio or add a TypeScript file into an existing web solution. Once saved, the TS file gets compiled and a JS file gets added inside your project folder (outside of solution explorer).

Object Orientation

Writing object oriented code in TypeScript is straightforward. A class Person with properties and a method can be written as follows:

It’s possible to structure your TypeScript code in modules, which is a way of code isolation. Modules have many advantages, such as scoping (local vs. global scope), encapsulation, testability‎ and many other things. There are two types of modules in TypeScript; internal and external.

Internal modules

An internal module is the code itself that you write in TypeScript, anything you type is globally scoped and available throughout your code. If we instantiate our class Person, it will be globally available throughout our code:

var person = new Person("John", "Smith", 26, "Brown");

However, if we place our class inside of a module Races, everything inside of it becomes locally scoped. If we then like to instantiate the class out of the local scope, we need to use the keyword export on the class:

I recommend checking out the TypeScript playground where you can do some experimentation with the codes above, and be able to view the compiled JavaScript.

Thoughts and the Road Ahead

TypeScript is an awesome OO scripting language that brings your JavaScript to a new level, it’s a language that I will definitely be using further in web development. There are many other typical OO things that you can do in TypeScript than what I’ve shown. The list of goodies keeps getting bigger, here you can see a roadmap of upcoming versions of the language. Hope you enjoyed this and happy scripting!