Angular in a Windows Store app

Angular JS

I was trying to use Angular JS in a Windows store app and had some issues with Angular being “unsafe”.

Using Angular JS in a JavaScript Windows Store app turned out to be pretty easy. Here’s how to do it:

First create a new app.

Install Angular JS though NuGet.

Add a scripts tag to your default.html.

<script src="Scripts/angular.js"></script>

Running the app at this point will result in the following error:

The trick to get around this error is to enable CSP (Content Security Policy) and the most convenient part is that Angular has a directive to set that. All you have to do is add the “ng-csp” attribute to your html tag.

Which results in:

<!DOCTYPE html>
<html ng-csp ng-app>
    <meta charset="utf-8" />

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

    <script src="Scripts/angular.js"></script>

    <!-- AngularDemo1 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>

And that’s it. If you run this, your app should print “10”. Getting WinJS to work with Angular is a whole other story… which I’ll explain in a separate post…

Additional note:

In order to get ng-cloak and ng-show to work property you’ll have to add some styles to you project. These style would be added dynamically in other situations, but because ng-csp is used this is disabled. This is the CSS, which can be found at the end of ‘angular.js’ (I removed a few unsupported):

<style type="text/css">
    @charset "UTF-8";

    [ng-cloak], [data-ng-cloak], [x-ng-cloak],
    .ng-cloak, .x-ng-cloak, .ng-hide:not(.ng-animate) {
        display: none !important;


List item delay in Pivot

In one of my apps I wanted to have the items in a list with the list being in a Pivot control. I wanted to have the items slide in with a little delay, like they are in the Windows Phone mail app. I’ve been looking for that a lot, but couldn’t find anything. Until I stumbled upon the Pivot Control Sample app. The actual solution is demonstrated in this sample. It doesn’t seem to be documented anywhere else…

Here’s how it’s done…

All you have to do to get the delay on the items, or basically any HTML inside the pivot items, is just adding one of three CSS classes: win-pivot-slide1, win-pivot-slide2, win-pivot-slide3. Where the first has the shortest delay and the last the longest.

To see the effect you can alter the “Pivot App (Windows Phone)” template app a little. Just create a new app using that template.

Then, open one of the pages. Section3Page.html for example and change the itemTemplate part of that HTML to:

<div class="itemTemplate"
    <div class="templatecontainer">
        <img class="win-pivot-slide1"
             data-win-bind="src: backgroundImage; alt: title" />
        <div class="itemcontainer">
            <div class="itemtitle label-extralarge win-pivot-slide2"
                 data-win-bind="textContent: title"></div>
            <div class="label-mediummid win-pivot-slide3"
                 data-win-res="{ textContent: 'Section3Description' }"
                 style="height: 82px;"></div>


And that’s it J


Detecting Phone, Desktop or Web with WinJS

I’m my previous post I showed how you can add a website to a universal project and share some JavaScript between all three. This is nice, but I will run into a situation where you’ll have some code that is not supposed to run on one of the platforms. In the C# world you can use compiler directives in situations like this. In JavaScript this is not possible (Although you could create constructions that mimic directives using Grunt for example). WinJS has some functionality build in that can help finding out what platform you are using.

There are two properties on the utilities in WinJS you’ll need:

Here’s a small example of you could use it:

if (WinJS.Utilities.isPhone) {
} else {
    if (WinJS.Utilities.hasWinRT) {
    } else {

Adding ASP.NET to your universal JavaScript Store apps project

While exploring the possibilities of using frameworks like KnockoutJS and Backbone in my store apps I started wondering if it would be possible to share my JavaScript code between Windows Store app, Windows Phone app and an ASP.NET website. After some exploration and fiddling with various options I figured it out.

Here’s how to do it.

If you have a solution with an ASP.NET website, add a universal project to the solution. Or add a MVC project to the solution with you universal projects.

Unload the web application and add to the following line to the file right before the import of “Microsoft.CSharp.targets”. Where App79 would be the name of your shared project of course…

 <Import Project="..\App79.Shared\App79.Shared.projitems" Label="Shared" />

This will enable the connection between the projects. Because linking JavaScript files doesn’t work in web projects (the files are not really in the expected folder) the files have to be copied too.

After some searching I came across the following blogpost by Matt Perdeck, Copying linked content files at each build using MSBuild. He explains how to have the build copy linked files to their target location.

By adding the following lines to the end of the project file, right before the last closing tag, files are copied before the build. He even optimized it a bit, by skipping the unchanged files.

<Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)" 
          Condition="'%(Content.Link)' != ''" />

Close the project file and reload the project. As you can see in the references section the shared project is included.

You need to make sure that the names of the folders in the shared project are available in the web project too. I assume these are already created in the Windows Phone and Windows Store projects.

One nice extra is that you can add breakpoints in the shared project that will hit when running the web project. You can also switch the context to the web application in the .js files.



WinJS Promises

For a while now I wanted to dive a little deeper into Promises, so I decided to write this tutorial.

For this tutorial I used the WinJS version as available on GitHub. If you want to follow along you’ll have to compile the code yourself. Which is very easy, but if you have any issues or questions please let me know and I’ll do a tutorial on that.

What’s a “promise”?

A promise is an object representing a value that is eventually returned by an operation. This object can be passed around like any other object.

Various frameworks have various implementations of promises. Promises are specified in the CommonJS Promises/A proposal. jQuery for examples uses Deferred. WinJS has its own implementation, but they basically work the same. You do something, and specify what happens then and then, until you are done.

The promise object has two functions you’ll use very often.

  • Then() à Allows you to specify what needs to be done when the promise is fulfilled. It also allows you to specify what to do when an error occurs and provide notifications on the progress.
  • Done()à Is almost similar to then, except it returns undefined instead of a promise. It is meant to be used at the end of the promise chain. It takes the same parameters, although unhandled exceptions need to be handled outside the promise chain and won’t be handled inside.

You will use the constructor a lot too. This can wrap some code in a promise and lets you handle the moment it is fulfilled.

Use a promise

One very common use of a promise in WinJS is its xhr() function. This function wraps the XMLHttpRequest in a promise and is used to make ajax calls. When given a URL and a response type the xhr() function returns a promise that is fulfilled when the call is completed, either by returning the data requested or when I fails and returns an error.

Let’s have a look at some code.

// create request object 
var request = 

//call to xhr
        var response = JSON.parse(r.response);

On lines 2 through 6 I create a request object. In this case I’m going to make a call to the YouTube API to request the playlists for a specific user. I specify I’d like the response to be JSON, both in the URL to YouTube and in the response type.

On line 9 I use the request object as a parameter in the xhr function. This function will make the call and returns a promise.

On line 10 the returned promise used immediately and its then function is called. As a parameter the then function takes up to three parameters, all three functions. The first, which is called when the promise is fulfilled successfully. The second parameter is a function the will be called when an error occurs. This allows you to handle the error and have the chain continue. The third function that can be passed to the promise function is used to handle the progress. Promises are not required to use progress.

Lines 11 and 12 parse the response and log the title of the first playlist to the console.

A more interesting situation

The service called in the previous examples returns the playlists for the specified user. But, say we want to know more about all these playlists. We’ll have to iterate over the lists of the playlists returned and make a new call for each playlists. When this is done we need to handle the results.

Promises are a big help in cases like this. Because promises are just objects we can create arrays of them. And the promise type has a function to join an array of promises to be handled as one.

Let’s change to code to the following:

        var response = JSON.parse(r.response),
            promises = [];
        for (var i = 0; i < response.feed.entry.length; i++) {
        return WinJS.Promise.join(promises);
        var playlistResult = [];
        for (var i = 0; i < x.length; i++) {
            var response = JSON.parse(x[i].response);
                    title: response.entry.title.$t,
                    summary: response.entry.summary.$t,
            return playlistResult;
        }, function(err){
        //do something with results from r[]

The request object used as parameter in the xhr function on line 1 is the same object used in the previous sample.

Line 5 through 10 loop over the entries returned from YouTube. Per entry a new promise is instantiated (line 6) and added to the promises array.

The real magic happens on line 11. On this line the complete array of promises is joined into one and returned. After this, the next then function is called when all these promises are fulfilled. An array with results, one item per request, is passed to it.

Inside the then on line 13 I loop over this results, parse them and add them as a new object into an array if playlist results. At the end of the function at line 23 I return this array so it can be processed further into another then or done.

I also added a handler for the errors on line 24. This way I know when something went wrong here.

One major downside to this technique is that the whole chain fails whenever one promise returns an error.

Custom promises

Often you have to work with 3rd party libraries that don't use these promises. Wrapping existing code into a new promise.

First, let's look at same code again. This code replaces the last then of the previous sample.

    return new WinJS.Promise(function(complete, error){

The constructor of the promise on line 2 takes a function with 2 parameters. The promise uses these functions to keep the chain going. Both parameters are functions that you can call from your code. In this example I use call magic function of some random library. This function takes an object which has a callback and an error function. When magic call its callback function, I call the complete function that was given to me by the promise. This will trigger the next step in the chain of promises and call the then or done function if it is specified. The value passed to the complete function will be passed to the then or done functions. In case of an error occurring magic calls what I specified on line 8. I just call the error function that was provided to me, passing it the error. This way it can be handled somewhere else.

Wrap up

I hope I shed some light on these promises. Keep in mind that code like this can be refactored pretty easily into multiple methods, because promises can be passed around in variables and parameters.

A complete version of source is available on GitHub.

Windows Store app with TypeScript and Knockout

Demo application

In this tutorial we’re going to make a very simple Windows Store app that uses TypeScript. The app is going to use Knockout to handle user input to search patterns on I assume you have read my previous tutorial on how to set up TypeScript compilation in a Windows Store app. We’ll start with an empty project after adding TypeScript compilation.


First we’ll start by adding our dependencies through NuGet. We have a dependency on KnockoutJS, because this is what we need for our bindings. To make the request to colourlovers we are going to use jQuery. First install both by searching them in the NuGet explorer, or type the following two commands in the NuGet console.

Install-Package knockoutjs
Install-Package jQuery

To make our lives a lot easier we are also going to install a couple of type definitions. There’s an awesome project going on over at GitHub, DefinitelyTyped. This collection contains definitions for many JavaScript frameworks and libraries. If you are using any third party library in your project you should definitely have a look at that.

For our convenience these definitions are available through NuGet also.

Install-Package jquery.TypeScript.DefinitelyTyped
Install-Package knockout.TypeScript.DefinitelyTyped

There are two definitions which we need also. There’s are for the WinRT and WinJS libraries used in the project. Although a version of these files come with TypeScript, the version on DefinitelyTyped are far more up to date. If you install the definition for WinJS, WinRT is also installed.

Install-Package winjs.TypeScript.DefinitelyTyped

That’s all for the packages. A small last trick. You can search by tag when looking for NuGet packages in the Package Manager, by starting your search with “tag:”. To search for anything on TypeScript, just search for “tag:typescript”.


Packages alone won’t bring us very far. Start by deleting the old default.js file and adding a new default.ts file. Add the code below to the file:

/// <reference path="../scripts/typings/winjs/winjs.d.ts" />
/// <reference path="../scripts/typings/knockout/knockout.d.ts" />

module Default {
    "use strict";

    WinJS.Application.onactivated = (args: any) => {
        if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                    (rootElement) => {
                        // apply knockout binding …


The first two lines, in comments tell TypeScript to use these definitions as references. We create a module named Default. This code is pretty much the same as its JavaScript counterpart, except for the then on line 10. The function inside is called when the processing of the UI is done. This will be the place where we’re going to apply the knockout binding and create a new instance of our view model.

Knockout ViewModel

In this example we only need one view model. To create this, start by adding a new TypeScript file to the scripts folder. Add the following code to the new file.

/// <reference path="../scripts/typings/knockout/knockout.d.ts" />

module ColourLovers {

    export class PatternsViewModel {

        constructor() {


This code will be the basic outline of the view model. It starts by adding a reference to knockout, it than defines the module with the PatternsViewModel.

The class needs a property to store the query to use when calling the ColourLovers api. Add this piece of code to line 6:

query: KnockoutObservable<string> = ko.observable<string>();

This will add the query variable to the class and uses the generic type KnockoutObservable of type string. It’s that initialized immediately using the generic function observable on ko from Knockout. The use of this generic give you a great advantage over the JavaScript version. In JavaScript there’s no one stopping you for putting a number in there. This might cause problems on some occasions. TypeScript will give you an error, and in Visual Studio you’ll get a compiler error preventing you from running the broken code.

We also need a function to call whenever this value changes. At the following code between lines 9 and 10:

private search = function (value?){          


This function will only be used inside the class, thus it can be made private. Note that the private indication is only enforced by TypeScript. Because this function will also be called from the constructor, but without the parameter, it is nullable.

Speaking of which… Let’s implement the constructor and have it call the search function. The code on line 3 comes with Knockout. Whenever an observable changes its value, the subscribe function is call and the new value is passed to as a parameter. In this case it’s the value to search for on ColourLovers. We’ll just pass it on the search function.

constructor() {
    this.query.subscribe((value) => {;

The last thing to do in the view model is making the call to ColourLovers. This will be done in the search function.

private search = function (value?) {
    $.getJSON("" + value).then(
        (result) => {

The code for the search function is pretty straight forward. All it does is making an Ajax call and then it uses a promise (the jQuery version in this case) to handle the result. I’m using the lambda version of a function in this case. You could write the search function on line 1 as a lambda also, but I prefer “regular” function to be written as such and callback as lambdas as this keeps the code a bit more readable.

The result is placed in the result variable. We’ll have to define this also. It’s just one single line to add right below the definition of the query variable we defined earlier. For now, we make de observable array of type any so we can add anything to that.

result: KnockoutObservableArray<any> = ko.observableArray<any>();

To kick off the databinding with knockout you’ll have to call its applyBindings function. To do that, place the line below in default.ts inside the lambda.

ko.applyBindings(new ColourLovers.PatternsViewModel(), rootElement);

You should be able to run the code now, although nothing will be shown on screen. But, if you place a breakpoint inside the result of the search function you should be able to hit that and see the result.

The View

The view is build using two parts. The header, which contains a title and the searchbox. And the contents that contains a list. The connection between the HTML and Knockout is made though the data-bind attributes.

<div class="header">
    <h1>TypeScript HTML App</h1>
        <input placeholder="search" data-bind="value:query" />

<div class="patternsOuter">
    <ul class="patternsList" data-bind="foreach:result">
        <li class="patternsListItems">
                <img data-bind="attr:{src:imageUrl, alt:title}" />
            <div data-bind="text:title"></div>


To get a little formatting use the following CSS:

body {
    display: -ms-grid;
    -ms-grid-rows: 150px 1fr;
    -ms-grid-columns: 1fr;   
.patternsListItems {
    list-style-type: none;
    padding-bottom: 24px;
    padding-right: 24px;
.patternsList {
    display: -ms-flexbox;
    flex-flow: wrap; 
.patternsOuter {    
     overflow-y: scroll;    
     -ms-grid-row: 2;
.header {
    margin-left: 40px;
    -ms-grid-column: 1;

The data-bind on line 4 of the html binds the query property to the value of the textbox. Because it is two-way whenever the value changes the code is updated and the subscribe method is called on the view model.

The second data-bind is a foreach on the result property which is filled with the results of the query when the ajax call to ColourLovers is done. Everything inside the HTML-tag the foreach handler is on will be repeated for every item. This creates a list of <li/> with an image and a title.

Try running the code again. The application should work as expected now.

WinJS through helper

What happens if you would like to use a WinJS control in combination with Knockout? For example, a rating control. The patterns returned by ColourLovers contain a numHearts property. This is a floating point value between 0 and 5, which is perfect to show in a rating control. The HTML for the control looks as follows:

<div class="ratingControl" data-win-control="WinJS.UI.Rating"
     data-win-options="{ maxRating: 5 }"

On line 3 you can find the Knockout databinding. But, the average handler is not defined by Knockout. Because Knockout knows nothing about WinJS and its controls you’ll have to help it a little. I’ve added a TypeScript file to the solution, KoHandlers.ts and added following code to that:

ko.bindingHandlers["average"] =
    init: (element, valueAccessor, allBindings, viewModel, bindingContext) => {
    update: (element, valueAccessor) => {
        var value = valueAccessor() || {};

        if (element.winControl) {
            element.winControl.averageRating = value;

Make sure you add the .js file the .html file.

When Knockout initializes the binding the init function is called. To make sure the control is processed this is where we call WinJS.UI.process passing it the control.

When the value in the view model changes the update function is called. All we do is grabbing the value from the accessor, checking if the control is still there.

This handler does not update the view model when the user selects another rating. To implement something like that you’ll have to add an event handler to the init function and monitor the changes yourself.


I hope I’ve showed a bit how you could use Knockout in your TypeScript store apps. Now we’ve got the basics out of the way we can dive in a little deeper into using TypeScript in your Store apps next time. If you have any question or suggestions please leave them in the comments or send me tweet or email.

Demo application

Enabling TypeScript Compilation in Windows Store apps


TypeScript compiles to JavaScript, thus it can be used in Windows Store apps. Other than with Web applications, where you can configure the way typescript compiles on the project’s property page, with Windows Store apps you’ll have to edit the project file by hand. Which is not that hard.

Edit the project file

To do this, unload your Windows Store JavaScript application project by right clicking and selecting unload.

Right click the project again and select edit.

What we need to do is tell MSBuild what it has to do when it encounters a TypeScript file. The whole XML file in front of you basically is nothing more than a configuration for MSBuild. It uses various “targets” that tell what to do in all kinds of situations and how properties are specified. If you want to dive deep into MSBuild, project files and everything around that you definitely should start reading here, at MSDN.

When TypeScript was installed on your computer, assuming you have, it added everything it needs to the MSBuild folder on your system. You can find this folder at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\TypeScript.

First we’re going to define a property inside the project file to this path. The whole file is divided in PropertyGroups. You’ll have to search for a PropertyGroup that has a label named “Global”. It probably only contains a GUID at the moment and is probably around line 37. At the following to that group:


This line defines a property “TypeScriptPath” we’re going to need later on. The path uses 2 properties defined elsewhere, but they make up the path to the TypeScript folder I talked about earlier.

Next we’re going to add the default properties for the TypeScript compiler. A few lines below the “Global” PropertyGroup you’ll find 2 imports. Place the following line right below these:

<Import Project="$(TypeScriptPath)\Microsoft.TypeScript.Default.props" />

The last part we’re going to add to the project file are the configurations for the Debug and Release builds and the targets for TypeScript. These files contain the tasks that need to be executed to compile typescript. Add the following code at almost the end of the file, right before the last import.

<PropertyGroup Condition="'$(Configuration)' == 'Debug'">

<PropertyGroup Condition="'$(Configuration)' == 'Release'">

<Import Project="$(TypeScriptPath)\Microsoft.TypeScript.targets" />
<Import Project="$(TypeScriptPath)\Microsoft.TypeScript.jsproj.targets" />

The code is pretty straight forward. It tells TypeScript to compile to EcmeScript 5. When building using the Debug configuration it should leave comments intact, where it should remove these when building in Release. TypeScript uses Source maps for being able to set breakpoints in your TypeScript while debugging. You won’t need these files when running in Release. The last property that is defined tells the TypeScript compiler it should use AMD modules when needed, you could change this to CommonJS if you prefer.

And that’s it. Close the file and reload the project.

You should be able to add TypeScript files to the project now. The TypeScript files get a TypeScriptCompile Package Action.

One last note. Other than with web project you’ll have to include the .js and files in your project. Otherwise they won’t get deployed and your app won’t work.

To make things a little easier for everyone, I contributed the project template to the SideWaffle project.

Using Grunt to compile .less in Windows Store apps

I was playing with Grunt. Grunt is a JavaScript task runner. It automates a lot of repetitive tasks like minification, unittesting, linting and more. I’ve used it to compile templates and compile .less files to .css. In this tutorial I’ll show you how to do the latter.

Before we dive into Grunt you need Node.js. Just go to and install it. NodeJS can serve websites, but can also run tools. Like Grunt. Node.js uses a package manager (a bit like NuGet), npm. You’ll be using npm a lot when using Node.js.

Getting started

First let’s create a new project in Visual Studio, a Windows Store app with JavaScript of course. (Although everything in this tutorial can be used in Windows Phone apps and universal apps too, as long as you use JavaScript). I named mine GruntLessApp.

After creating the project start the Node.js command prompt. This should be somewhere in your start menu. And navigate to the project folder of the project you just created.

Now before we can use Grunt we need to install it. In order to get started first install the command line interface, grunt-cli.

Type the following in the command prompt: npm install grunt-cli -g

This tells the node.js package manager, npm, to install grunt-cli globally so it can be accessed from every location.

Grunt uses 2 configuration files. Packages.json contains all packages your project is dependent on. The other one is gruntfile.js. Creating packages.json can be done by typing: npm init

And follow the instructions.

So, now it’s finally time to install Grunt itself…


Just type: npm install grunt –save-dev

This will install Grunt and save the dependency to the packages.json file. If you save this file in your source control others can use this to install the same dependencies (by typing npm install). I personally just include these files in my project in Visual Studio and set the Package Action to none. This way I can easily edit the files in Visual Studio and store in under source control.

To get Grunt to compile your .less files you’ll have to install a task for it.

Type: npm install grunt-contrib-less –save-dev

Your packages.json file will look something like this now:

  "name": "GruntLessApp",
  "version": "0.0.0",
  "description": "demo application for grunt and less",
  "main": "js\\default.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-contrib-less": "~0.11.0"


Last thing we’ll need to do is setting up the gruntfile.js file. If you like some samples of this file, have a look at the Grunt site. This file is not created automatically in this case, but you’ll can just add a .js file in visual studio in the root of your project. Be sure to set the package action to none so the file doesn’t get included in the package when you publish the app.

The gruntfile.js file is build using a few parts. The first line is the definition of a functions. This part is the same for every gruntfile.js.

module.exports = function(grunt) {
  // Do grunt-related things in here


Inside this function you’ll have to tell Grunt the configuration for the tasks to execute. This is done by passing an object to grunt.initConfig(); like so:

        less: {
            development: {
                options: {
                    paths: ["css"]
                files: {
                    "css/default.css": ["css/*.less"]


Let’s go over this. The less object in line to tells Grunt we’re talking about the configuration for the less tasks. Next, on line 3, we’ve named this configuration. You can have multiple configurations for various situations. On line 4 the actual the options of the less task are specified. In this case we’ll tell the task it should use the “css” folder as a base for the @import less function. The files section on line 7 tells the task to combine the *.less files into ‘default.css’.

grunt.registerTask('default', ['less:development']);


The last two lines tell Grunt to load the less contrib package and register the ‘less’ task as the default. If your gruntfile.js grows over time with more and more tasks you’ll have more of these. Probably in various forms, for development and publishing for example.

To try this out, rename your default.css to default.less and change the contents to something like:

@bgColor: #333333;
@fgColor: red;

body {
    background-color: @bgColor;

    border: 1px solid darken(@fgColor, 20%);



Now go back to your command prompt and type: grunt

To get you project to use the “new” css file, include it in your project. Set the package action of the .less file to none to exclude it from being packaged.


There are a few ways to get this process a bit more automated. Grunt is all about removing repetitive tasks and typing a command in a prompt after every change is pretty repetitive.

One way is to use the grunt-contrib-watch package. Using this package will enable you to have the command running continuously and monitor folders and files for changes. When a change happens a series of tasks can be run. Added the task is pretty straight forward. It’s basically the same as described above with the less-task.

In the case of .less files I prefer another method. Because the installation of Node.js has added the path of the npm packages to the “PATH” environment variable, the packages installed with the –g flag can be used everywhere. So let’s add it as a prebuild task to our project.

For this we have to edit the project file. By unloading the project you can edit this inside Visual Studio. Right click the project file in the solution folder and select Unload Project.

Right click the project again, and select Edit GrunLessApp.jsproj.

At the very bottom of the xml, but right before the closing </project> tag, add the following:

<Target Name="BeforeBuild">
    <Exec Command="grunt" />

This will do exactly as it says, before the build, execute the command grunt.

To try it out we’ll have to reload the project. To do this, close the file, right click the project in the solution explorer and hit Reload Project.

From now on, on every build, grunt will be executed and help you compile your .less files to .css.


And that’s it.

A few links to read more about what was discussed in the tutorial:

Windows Phone Sketchflow 2013

In the past I used SketchFlow to prototype my Windows Phone apps. Unfortunately the development of the windows phone SketchFlow templates stopped back in 2011. These templates don’t work in Blend for Visual Studio 2013. Today I had enough of not being able to use that template and just upgraded it to Blend for VS2013.

To use the template you’ll need Silverlight and SketchFlow (which comes with Blend on VS premium and ultimate).

You can download the Windows Phone SketchFlow templates here:

Once downloaded, extract the zip file into: %userprofile%\documents\Visual Studio 2013\Blend

This folder was probably empty and now it should have to folders in it, ProjectTemplates and ItemTemplates.

To see if it works, just start Blend and select new project on the welcome dialog. On the new project dialog go to Windows Phone. The SketchFlow template should be in the list.

The basics on how to use the template are still available on the codeplex project of the first version and are still pretty much valid. I might do an updated version of the documentation in Visual Studio 2013 in the future.



Combining WinJS, TypeScript, jQuery and KnockOut

Windows Store app using TypeScript, KnockOut and jQuery

In this tutorial we’re going to build a very simple Windows Store application that uses jQuery and Knockout to get some data from the internet and show this in a GridView. I’ll show you how you create a new project, get all the the TypeScript definitions you need, get data from a web service and bind that to the GridView control. I’m assuming you have at least a little TypeScript knowledge. If you don’t you should have a look at the tutorials on first.

File – New

Start by creating a new project using the template Store apps with TypeScript project template I wrote about recently. After this is installed you can go to the Windows Store section in the TypeScript category in the New Project dialog. Select the Blank App template and give the app a name. I named mine ColourLovers. Hit OK to create the project.


This will give us an application similar to a blank application created using the JavaScript template, only with TypeScript in place.

Because this application is going to need jQuery and Knockout we’ll have to get that into the solution. I always use NuGet to get libraries like this into my projects. The easiest way to do this is to open the Package Manager Console from Tools –> Library Package Manager in the menu. In this console window type:

Install-Package jQuery

to get jQuery. And

Install-Package knockoutjs

to install Knockout.

While we’re here, let’s install the TypeScript definition for Knockout too. The definition for jQuery is already included in the project template. Just type

Install-Package knockout.TypeScript.DefinitelyTyped

In the package manager console window to get the definition. Note that you can use the Tab key to get completion of the words.

DefinitelyTyped is a huge open source library of TypeScript definitions of JavaScript frameworks. If you would like to use a JavaScript framework in your TypeScript website or application you should check DefinitelyTyped to see if it contains the TypeScript definition. It would make your life developing you app a lot easier.

Getting Data

To get some data into the app we’re going to make an ajax call to the API of Colourlovers. This API gives us some simple data to work with. To get the data I would like to use what I always use to make ajax calls, jQuery.

To get some code completion and syntax checking on jQuery you’ll have to add a reference to the jQuery.d.ts file that’s in your project. Adding this is easy, just drag the .d.ts file from your solution window to the top of the default.ts file. This will result in a comment like this:

/// <reference path="../Scripts/typings/jquery.d.ts" />

To get the data using jQuery we are goingto use its getJSON function. This function call to the specified url and when it’s done it calls the success function you provided. The result of the ajax call is passed to the success function.

Inside the then function after the processAll we are going to place the getJSON function to get the data from ColourLovers.

args.setPromise(WinJS.UI.processAll().then(() => {
        (result) => {


This piece of code looks pretty much the same as it would when writing it in plain old JavaScript. Except for the lambdas, where function used to be.

Let’s add a little code to the view, our HTML file.

<div id=”content”></div>

At this point we should be able to loop through the result and add some HTML with values from the result to the content div.

Since we are using TypeScript, it would be nice to have some actual type checking and even code completion. To do this we’ll make an interface describing the result from the ajax call. An interface in TypeScript contains the description of an object. In this case the returned object is not complex. The entire interface looks like this:

declare module ColourLovers {
    export interface Top {
        id: number;
        title: string;
        userName: string;
        numViews: number;
        numVotes: number;
        numComments: number;
        numHearts: number;
        rank: number;
        dateCreated: string;
        colors: string[];
        description: string;
        url: string;
        imageUrl: string;
        badgeUrl: string;
        apiUrl: string;

I personally hate write code like this. Why? Because it’s very easy to have code like this generated by a computer. So I decided to build a website that does exactly that. Converting a JSON object to a TypeScript interface. At you can paste a piece of JSON into the textbox and have it converted to TypeScript. You even can enter the URL to service that returns JSON and have that converted.

To have the result use the interface we just created, add it to the callback function. Now, when we just loop though the items returned from ColourLovers, we can build some UI.

(result: ColourLovers.Top[]) => {
    var content = $("#content");
    for (var r in result) {
        div.append("<h3>" + result[r].title + "<h3>");
        div.append("<img src="" + result[r].imageUrl + "" width="150">");

Note that when you type inside the callback, you get intellisense on the result.


When you run this app it should look something like below. Although this app is getting data and showing it on screen it isn’t exactly what you would expect from a Windows Store app. It would be nice to have some interaction too. You could use jQuery to get some interaction with your app, but there are other ways. Like KnockoutJS for example.


Binding to the UI

KnockoutJS uses a viewmodel that is bound to elements in the DOM. If you haven’t used it please have a look at The site has some very nice tutorials on getting started with using KnockOut in your web applications. It uses data-bind attributes on HTML elements to bind properties on the viewmodel to attributes or events in the DOM. It does all change and dependency tracking for you. KnockOut can also be used to render templates.

If you haven’t heard from Knockout before but have build Windows Store apps this should sound familiar.

Let’s start by creating the viewmodel. The viewmodel is basically just another TypeScript class. For sake of simplicity I added it to Default module that’s already in the project. I named the class ViewModel. I added a constructor too, because that’s where we’re going to move the ajax call we created earlier to.

class ViewModel {

    constructor() {


The viewmodel is going to need one property to use in the DOM. Well, an array to be more specific. This array needs to be an observableArray. KnockOut uses this function (and a couple more, like a regular observable) to track changes. Whenever you push something into an observableArray the UI is updated. The TypeScript version of the observableArray is generic and takes the type you want to store in the observableArray. In the case of this tutorial we’re going to use the interface we created earlier, Colourlover.Top.

Just add this line to the ViewModel class:

top = ko.observableArray<ColourLovers.Top>();

Filling this array is as simple as passing a value to a function. And that’s something you should always keep in mind when working with knockout. You don’t just assign a value to a variable, you pass it to the variable by calling it as a function and passing the new value.

To fill the observableArray I moved the ajax call from earlier to the constructor of the ViewModel and changed the success part as follows:

    (result: ColourLovers.Top[]) => {;

Last small modification we’ll have to make to the TypeScript code before we can move to the HTML part of this chapter. We have to create a new instance of the ViewModel class and the knockout to do its magic with it by passing it to the applyBindings function.

At the place where we just removed the ajax call we’re going to change to code to this:

args.setPromise(WinJS.UI.processAll().then(() => {
    ko.applyBindings(new ViewModel());

Now that the ViewModels set up it is time to have a look at the view, the HTML. In the last chapter we added some simple HTML to the DOM, but why not use a WinJS control this time, like a ListView. This way we get the Windows 8 grid we are used to see. The HTML for a ListView with GridLayout looks like this:

<div data-win-control="WinJS.UI.ListView"

At this point the grid doesn’t display any data. Normally you would add an option to the data-win-options to set the data source. But since we are using KnockOut I would like to use the KnockOut data-bind method to set the data source. Unfortunately this doesn’t work out of the box. There is no data source handler in KnockOut to set the data source of a Windows 8 control. So I’ve created them myself. You can find them over at GitHub. The project contains only two handlers at the moment, but will grow over time. Just add the two handlers to your project and you ready to go.

Now we can specify the data source with the data-bind attribute and set it to the top property of the ViewModel.

Which results in:

<div data-win-control="WinJS.UI.ListView"

Normally, when you use the ListView you would like to specify a template which describes the way your data should be rendered. KnockOut provides its own template engine. You could specify the default template using the data-win-options attribute, but you’ll loose the reference to KnockOut that way. On my GitHub project you’ll find the handler to use a KnockOut template. The template itself is specified as follows:

<script id="itemTemplate" type="text/html">
    <div >
        <div style="width:260px;height:190px"
             data-bind="style:{backgroundImage: 'url('+$data.imageUrl+')'}">
            <div data-bind="text:title"></div>

You have to add a script like this to the Head section of the HTML document. This will create a tile of 260px by 190px with its background image set to one from the data returned by the ColourLovers API. On top of that the title of the pattern is displayed. Nothing Store app or TypeScript specific about that, just regular KnockOut.

To tell the grid to use this template, change the HTML of the ListView control to:

<div data-win-control="WinJS.UI.ListView"
     data-bind="datasource:top, template:itemTemplate"

The last thing I want to address is that you can use some KnockOut functionality out of the box. Like handling events, even ListView specific events.

Lets say you would like to handle the clicking/tapping on an item of the grid. You would use the iteminvoked to do that. Just use the default KnockOut syntax to handle the event.

<div data-win-control="WinJS.UI.ListView"
     data-bind="datasource:top, template:itemTemplate, event:{iteminvoked:selectionChanged}"

Of course you have to add the handler for the event too. Which is nothing more that a function on the ViewModel.

selectionChanged = (eventArgs) => {
    // do something useful.


That’s it!

You probably thought that creating a Windows Store application that uses TypeScript, jQuery and Knockout would be far more complicated that this :) By using NuGet and the definitions found at DefinitelyTyped you get intellisense and type checking without much effort.

A few last tips to wrap things up: