Algorithm Computation in the Cloud: Microsoft Azure Web Roles

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:

cloud

Choose ASP.NET Web Role:

cloud2

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

cloud3

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:

cloud4

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:

cloud5

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:

public interface IWebRole
{
   string RunInternalProcess(string stringParams);
}

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:

public string RunInternalProcess(string stringParams)
{
    var path = HttpContext.Current.Server.MapPath("..\\TSP_Genetic_Algorithm.exe");
    var result = RunProcessAndGetOutputAsync(stringParams, path).Result;
    return result.Replace(" ", "\n");
}

private static async Task<string> RunProcessAndGetOutputAsync(string stringParams, string path)
{
    return await RunProcessAndGetOutput(stringParams, path);
}

private static Task<string> RunProcessAndGetOutput(string stringParams, string path)
{
    var process = CreateProcess(stringParams, path);
    process.Start();
    var result = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    var taskCompletionSource = CreateTaskCompletionSourceAndSet(result);
    return taskCompletionSource.Task;
}

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”:

cloud15

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:

private readonly IWebRole _webRole;

public HomeController(IWebRole webRole)
{
    _webRole = webRole;
}

Create an HttpGet ActionResult, it can look like this:

[HttpGet]
public ActionResult Solve(string[] c)
{
    var coordinates = c.Aggregate(string.Empty, (current, t) =&gt; current + (t + " "));
    _results = _webRole.RunInternalProcess(coordinates);
    return Json(new { results = _results }, JsonRequestBehavior.AllowGet);
}

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:

http://127.0.0.1:81/Home/Solve?c=200,300&c=400,300&c=400,400&c=400,200&c=500,200&c=200,400&c=400,300

And here are the results:

cloud11

Publishing the Azure Cloud Service

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…”:

cloud7

Go through the wizard to create a target profile:

cloud8

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:

cloud9

The publishing process will start in Visual Studio:

cloud10

And then complete:

cloud12

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

cloud14

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

cloud13

Hope you enjoyed this tutorial!

Advertisements

ReSharper Downfalls and Anti-Patterns

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:

Capture

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:

animation

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:

properties

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…”:

find_usages

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

find_usages_2

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:

Capture

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. ๐Ÿ™‚

My Genetic Algorithm Solving the TSP Problem

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 ๐Ÿ™‚

TypeScript Release Candidate

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:

class Human {
    eyeColor: string;
}

class Person extends Human {
    eyeColor: any;
}

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:

interface IPerson<Value> {
    then<T>(f: (v: Value) => Person<T>): Person<T>;
}

class Person<Value> implements IPerson<Value> {
    then<T>(f: (v: Value) => Person<T>): Person<T>;
    then<T>(f: (v: Value) => any): Person<T> {        // This is also possible
        return undefined;
    }    
}

Declaration Merging Precedence

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:

interface IExternal {
    a1(): void;
    a2(): number;
}

interface IExternal {
    b1(): string;
    b2(): Date;
}

When these two interfaces are merged, they become this interface:

interface IExternal {
    b1(): string;
    b2(): Date;
    a1(): void;
    a2(): number;    
}

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! ๐Ÿ™‚

When Two Forces Meet (AngularJS, TypeScript)

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.

Capture

Setup

As a .NET developer, I use Visual Studio 2013 and the TypeScript plugin for Visual Studio. This is what I recommend that you use unless you are for some reason against the Windows platform. Then using the NuGet packet manager, you can install the necessary AngularJS core files. In addition to this, make sure to install the AngularJS TypeScript definitely typed files which provides typed AngularJS components that can be used in your TypeScript code.

Bootstrapper

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:

var appModule = angular.module("myApp", []);

appModule.controller("MyController", ["$scope", "MyService", ($scope, MyService)
    => new Application.Controllers.MyController($scope, MyService)]);

appModule.factory("MyService", ["$http", "$location", ($http, $location)
    => new Application.Services.MyService($http, $scope)]);

appModule.directive("myDirective", ()
    => new Application.Directives.MyDirective());

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:

module Application.Controllers {

    import Services = Application.Services;

    export class MyController {

        scope: any;
        myService: Services.IMyService;
	    data: any;
		
        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.myService = myService;
	        this.data = [];
        }

        private GetAll() {
            this.myService.GetAll((data) => {
                this.data = data;
            });
        }
	}
}

Factory Classes

Similarly, factories or services are written as classes. So your MyService.ts class can look like this:

module Application.Services {

    export interface IMyService {
        GetAll(successCallback: Function);
    }

    export class MyService {

        http: ng.IHttpService;
        location: ng.ILocationService;

        constructor($http: ng.IHttpService, $location: ng.ILocationService) {
            this.http = $http;
            this.location = $location;
        }

        GetAll(successCallback: Function) {
            this.http.get(this.location.absUrl()).success((data, status) => {
                successCallback(data);
            }).error(error => {
                successCallback(error);
            });
        }
	}
}

Note the interface IMyService here. Always use interfaces to abstract your classes in TypeScript, just as you would usually do in a typed language.

Directive Classes

Directives are also written as classes. So your MyDirective.ts class can look like this:

module Application.Directives {

    export class MyDirective {

        constructor() {
			return this.CreateDirective();
        }

        private CreateDirective():any {
            return {
                restrict: 'E',
                template: '<div>MyDirective</div>
            };
        }
    }
}

Databinding with Alias

Finally, to be able to use your TypeScript classes from your HTML, you need to databind using alias. So your HTML can look like this:

<html data-ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
	<div data-ng-controller="MyController as mc">
		<div data-ng-repeat="element in mc.data">
			<label>{{element}}</label>
		</div>
		<my-directive></my-directive>
	</div>
</body>
</html>

Databinding without Alias

Unfortunately, databinding with alias does not work in Internet Explorer 8. Neither do directive elements(!). To make it work in IE 8, you need to change your HTML so it looks like this:

<html xmlns:ng="http://angularjs.org" id="ng-app" data-ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lte IE 8]>
            <script>
                document.createElement('ng-include');
                document.createElement('ng-pluralize');
                document.createElement('ng-view');
                document.createElement('my-directive');
                document.createElement('ng:include');
                document.createElement('ng:pluralize');
                document.createElement('ng:view');
            </script>
            <script src="libs/es5-shim/es5-shim.js"></script>
            <script src="libs/JSON/json3.js"></script>
        <![endif]-->
</head>
<body>
	<div data-ng-controller="MyController">
		<div data-ng-repeat="element in data">
			<label>{{element}}</label>
		</div>
		<my-directive></my-directive>
	</div>
</body>
</html>

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:

module Application.Controllers {

    import Services = Application.Services;

    export class MyController {

        scope: any;
		
        constructor($scope: ng.IScope, myService: Services.IMyService) {
            this.scope = $scope;
            this.scope.myService = myService;
			this.scope.data = [];
			this.scope.GetAll = this.GetAll;
        }

        GetAll() {
            this.scope.myService.GetAll((data) => {
                this.scope.data = data;
            });
        }
	}
}

Notice how everything is hooked onto scope. That way, databinding is correctly achieved in IE 8, and you are able to call your GetAll() method from the HTML by simply typing GetAll() without alias.

Hope you enjoyed this tutorial! I’m planning on holding a workshop about this and doing TDD at this year’s Norwegian Developers Conference 2014, so make sure to book your tickets! ๐Ÿ™‚

Creating a Cross-Platform App for Windows Phone 8 and Windows Store (PCL, MvvmCross)

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.

Let’s Get Started

Start Visual Studio 2013 and create a new project, choose Windows Phone:

Capture

Right click the solution and choose Add -> New Project… Choose Windows Store:

Capture2

Right click solution again and choose Add -> New Project… Choose Portable Class Library:

Capture3

Make sure the following are checked:

Capture4

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!”:

public class FirstViewModel : MvxViewModel
{
	private string _hello = "Hello World!";
        public string Hello
	{ 
		get { return _hello; }
		set { _hello = value; RaisePropertyChanged(() => Hello); }
	}
}

Take a look at the App.cs class, this is the start up class of our library that registers our view models:

public class App : Cirrious.MvvmCross.ViewModels.MvxApplication
{
   public override void Initialize()
   {
      CreatableTypes()
         .EndingWith("Service")
         .AsInterfaces()
         .RegisterAsLazySingleton();
				
         RegisterAppStart<ViewModels.FirstViewModel>();
   }
}

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:

public class Setup : MvxPhoneSetup
{
    public Setup(PhoneApplicationFrame rootFrame) : base(rootFrame)
    {
    }

    protected override IMvxApplication CreateApp()
    {
        return new PortableClassLibrary1.App();
    }
		
    protected override IMvxTrace CreateDebugTrace()
    {
        return new DebugTrace();
    }
}

Now we need to make sure that our Phone app uses Setup.cs. To do that, navigate to App.xaml.cs and add this to the end of the constructor:

var setup = new Setup(RootFrame);
setup.Initialize();

Add this field to the class:

private bool _hasDoneFirstNavigation = false;

Now add the following code to the Application_Launching method:

RootFrame.Navigating += (navigatingSender, navigatingArgs) =>
{
    if (_hasDoneFirstNavigation)
          return;

    navigatingArgs.Cancel = true;
    _hasDoneFirstNavigation = true;
    var appStart = Mvx.Resolve<IMvxAppStart>();
    RootFrame.Dispatcher.BeginInvoke(() => appStart.Start());
};

Now take a look at FirstView.xaml and how it binds to our view model:

<views:MvxPhonePage
    x:Class="PhoneApp1.Views.FirstView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:views="clr-namespace:Cirrious.MvvmCross.WindowsPhone.Views;assembly=Cirrious.MvvmCross.WindowsPhone"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
		   <StackPanel>
			<TextBox Text="{Binding Hello, Mode=TwoWay}" />
			<TextBlock Text="{Binding Hello}" />
		   </StackPanel>
        </Grid>
    </Grid>

</views:MvxPhonePage>

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

Capture5

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:

public class Setup : MvxStoreSetup
{
        public Setup(Frame rootFrame) : base(rootFrame)
        {
        }

        protected override IMvxApplication CreateApp()
        {
            return new PortableClassLibrary1.App();
        }
		
        protected override IMvxTrace CreateDebugTrace()
        {
            return new DebugTrace();
        }
}

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);
            }

Add the following to the end of the OnLaunched method:

var setup = new Setup(rootFrame);
setup.Initialize();

var start = Mvx.Resolve<IMvxAppStart>();
start.Start();

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

Capture6

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):

public sealed partial class FirstView : MvxStorePage
{
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public FirstView()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
        }

        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }
}

Now navigate to FirstView.xaml and reflect the changes that you made in the code-behind file, so your view looks like the following:

<views:MvxStorePage
    x:Name="pageRoot"
    x:Class="App1.Views.FirstView"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1.Views"
    xmlns:common="using:App1.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:views="using:Cirrious.MvvmCross.WindowsStore.Views"
    mc:Ignorable="d">

    <Page.Resources>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">My Application</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                        Style="{StaticResource NavigationBackButtonNormalStyle}"
                        VerticalAlignment="Top"
                        AutomationProperties.Name="Back"
                        AutomationProperties.AutomationId="BackButton"
                        AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                        IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel>
                <TextBox Text="{Binding Hello, Mode=TwoWay}" />
                <TextBlock Text="{Binding Hello}" />
            </StackPanel>
        </Grid>
    </Grid>
</views:MvxStorePage>

Build and run the Store app:

Capture7

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. ๐Ÿ™‚

The World of TypeScript

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:

class Person {

    firstName: string;
    lastName: string;
    age: number;

    constructor(firstName: string, lastName: string, age: number) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }    

    GetFullNameAndAge() {
        return this.firstName + " " + this.lastName ", " + this.age;
    }
}

Using the public keyword on properties, you can also inject the properties in the constructor and write the same, above class as follows:

class Person {

    constructor(public firstName: string, public lastName: string, 
                public age: number) {
    }    

    GetFullNameAndAge() {
        return this.firstName + " " + this.lastName + ", " + this.age;
    }
}

You can easily create an interface to hide implementation. Consider an interface IPerson:

interface IPerson {
    GetFullNameAndAge();
}

class Person implements IPerson {

    constructor(public firstName: string, public lastName: string, 
                public age: number) {
    }    

    GetFullNameAndAge() {
        return this.firstName + " " + this.lastName + ", " + this.age;
    }
}

Inheritance is also quite easy. Consider the base class Human:

class Human {

    constructor(public eyeColor: string) {
    }

    GetEyeColor() {
        return this.eyeColor;
    }
}

interface IPerson {
    GetFullNameAndAge();
}

class Person extends Human implements IPerson {

    constructor(public firstName: string, public lastName: string, 
                public age: number, eyeColor: string) {
        super(eyeColor);
    }    

    GetFullNameAndAge() {
        return this.firstName + " " + this.lastName + ", " + this.age;
    }
}

Now see how this code looks when it gets compiled to JavaScript:

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Human = (function () {
    function Human(eyeColor) {
        this.eyeColor = eyeColor;
    }
    Human.prototype.GetEyeColor = function () {
        return this.eyeColor;
    };
    return Human;
})();

var Person = (function (_super) {
    __extends(Person, _super);
    function Person(firstName, lastName, age, eyeColor) {
        _super.call(this, eyeColor);
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    Person.prototype.GetFullNameAndAge = function () {
        return this.firstName + " " + this.lastName + ", " + this.age;
    };
    return Person;
})(Human);

A bit terrifying, huh?

Modules

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:

module Races {	
	export class Person extends Human implements IPerson {
	
	    constructor(public firstName: string, public lastName: string, 
	                public age: number, eyeColor: string) {
	        super(eyeColor);
	    }    
	
	    GetFullNameAndAge() {
	        return this.firstName + " " + this.lastName + ", " + this.age;
	    }
	}
}

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

Internal modules can also be shared across files, other classes can make a reference to them by typing (at the top of file) for instance:

///<reference path="Races.ts"/>

External modules

An external module is an outside module that you choose to import into your code in order to use it. Consider the example:

import Ethnicities = module('Ethnicities');

class Person {

    constructor() {
    }

    GetEthnicity(country: string) {
        return new Ethnicities.Ethnicity(country);
    }
}

And in a different file called “Ethnicities.ts” we have:

export class Ethnicity {

    constructor(public country: string) {
    }
}

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!