Resolving WinJS webcomponents attributes

Now that you know how to use WinJS as webcomponents, and how to declare your controls, we will talk about the mecanism for resolving attribute values.

Lets work with an example :

<win-listview id="recentItemsList" member 

You could think of attribute resolution as

[what to do]:[where to look]:[string token]

If you look at the « itemdatasource » attribute, you could read it like this : get the « recentItemsPromise » property from parent control, and wrap it in a WinJS.Binding.List for the ListView.

In this example, « recentItemsPromise » is just a string, and « ctrl » and « list » are operators. The list operator is smart enougth to see that it received a promise, and await it to set value.

Operators are just functions referenced in the namespace WinJSContrib.Utils.ValueParsers. You could provide your own operators by adding them to this namespace.

When the attribute is resolved, you will endup with something equivalent to :

list(domelement, ctrl(domelement, "recentItemsPromise"));

As you can see, their is no complex parsing involved, it is very efficient, and enforce composition. You have no limit at the number of operators you can chain like this.

You could find the list and details about built-in operators in the API documentation.

registering your WinJS webcomponents

In the last episode, we had a glimpse of using WinJS controls with webcomponents syntax, thanks to WinJS Contrib. Let’s dig a little deeper and see how you could use your own controls with it.

On platforms with non native implementation of webcomponents, the WinJS Contrib module is attaching an observer on each page controls (and releasing it on when disposing the page). This observer uses MutationObserver to track changes in the DOM and automatically build the WinJS controls that you registered. It means that controls, not on a page (like controls in default.html) are not instantiated. In such case, you must call « WinJSContrib.UI.WebComponents.inspect(element) » just like you would have to call WinJS.UI.processAll with vanilla WinJS.

Registering a control is just about providing the name of the DOM element, and how to map DOM attributes to your control implementation. If you don’t want to use DOM element attribute, you could still use data-win-options, or use both.

Declaring a control is quite easy. If you look in « winjscontrib.ui.webcomponents.js », you will find the declarations for WinJS controls. Lets look at the declaration for the DatePicker :

	WinJSContrib.UI.WebComponents.register('win-datepicker', WinJS.UI.DatePicker, {
		properties: ['calendar', 'datePattern', 'disabled', 'maxYear', 'minYear', 
				'monthPattern', 'yearPattern', 'onchange', 'current'],
		events : ['change']

You must call WinJSContrib.UI.WebComponents.register to wrap your control. You must at least provide the name of the DOM element, and the constructor for your control. The third argument is an object containing the mapping for your control. Within this object, the items in « properties » indicate the name of the properties that you want to map as attribute on the element, and « events » indicate the name of the events you want to map.

« properties » and « events » are shortcuts to build a mapping. You could provide a raw map if you have to do fancy stuf. Lets imagine that the calendar attribute used on DOM element must map to something like _calendarBuilder.calendar in your control. In such case you could use :

	WinJSContrib.UI.WebComponents.register('win-datepicker', WinJS.UI.DatePicker, {
		properties: ['datePattern', 'disabled', 'maxYear', 'minYear', 
				'monthPattern', 'yearPattern', 'onchange', 'current'],
		events : ['change'],
		map: {
			"CALENDAR" : {
				attribute : "calendar",
				property : "_calendarBuilder.calendar",
				type : "property",
				resolve : true
			"CHANGE" : {
				attribute : "change",
				property : "_calendarBuilder.changeevent",
				type : "event",
				resolve : true

This syntax is more verbose but you have total control over the mapping. Note that the mapping key should be uppercase.

Another scenario that may come in mind is how do I map a fragment/page to a webcomponent ?

This is a lesser known feature of WinJS but WinJS.UI.Pages.define actually returns the constructor for the page, with the exact constructor signature of common WinJS controls (first parameters provides containing DOM element, and second parameter for control options).

To map a page/fragment to a component, you just have to pass the constructor. If you look at the searchbar control in the sample application, you will find an example that looks like this :

var SearchBarCtor = WinJS.UI.Pages.define("/controls/searchbar/searchbar.html", {
	//control implementation not mentionned here for brievity

//for use as standard control with data-win-control
WinJS.Namespace.define('Flickity.UI', { SearchBar: SearchBarCtor });

if (WinJSContrib.UI.WebComponents) {
   	WinJSContrib.UI.WebComponents.register('flickity-searchbar', SearchBarCtor);

The last use case we will cover now is for controls containing controls. Sometimes you write a control that wraps one or more other controls. You can map those controls directly to DOM attributes by using their own registration. WinJS Contrib has a control that wrap a SemanticZoom and the two associated ListView for managing list with groupings. The declaration for this control use that pattern :

WinJSContrib.UI.WebComponents.register('mcn-semanticlistviews', WinJSContrib.UI.SemanticListViews, {
	properties: [],
	controls: {
		"listview": WinJS.UI.ListView,
		"zoomedOutListview": WinJS.UI.ListView,
		"semanticZoom": WinJS.UI.SemanticZoom
	map: {
		"DEFAULTGROUPLIMIT": { attribute: 'defaultGroupLimit', property: '_dataManager.defaultGroupLimit', resolve: true },
		"GROUPKIND": { attribute: 'groupKind', property: '_dataManager.groupKind', resolve: true },
		"FIELD": { attribute: 'field', property: '_dataManager.field', resolve: true },
		"ITEMS": { attribute: 'items', property: '_dataManager.items', resolve: true },

The mapping can also have a « controls » section, which is used as a map. The key is the prefix for the control, and the value is the constructor for the control. When you register a control, the webcomponents module is creating a mapping and attach it to the constructor. That’s why you have nothing more to pass to map child control. However, the controls you are using as child map should have been declared before declaring this one.

The control can then be declared like this :

<mcn-semanticlistviews id="semanticzoom"

Next time we will have a look at the resolution of properties and detail the various options you have.

Using WinJS controls as webcomponents

WinJS Contrib goal is to makes WinJS development faster, and simplify common tasks. Last time we saw that WinJS contrib enables using JavaScript classes to define your pages, enabling ECMAScript 6 or Typescript in your applications.

This time we will talk about something that could radically change the way you write your pages. As stated previously, WinJS Contrib override core page control. This new control has the benefit of providing an extensible page lifecycle.

The code snippets in this post are coming from the sample applications we built to illustrate WinJS Contrib features. The first is from a vanilla WinJS application, and the other is from the exact same application with WinJS Contrib and webcomponents.

With vanilla WinJS, you declare controls like this:

<div id="recentItemsList" 
        itemTemplate : select('#pictureItem') 

The control model in WinJS is very effective but this syntax for declaring controls is a bit ugly. It’s verbose, and the parsing of options does not allow extensions. In all WinJS samples, the list is bound to data in the options using a static variable. Believe me, it is really a bad practice. In some templates, you will find the data bound with syntax like this « select(‘.pagecontrol’).winControl.myData ». Despite the fact that this syntax is also ugly, in any real world application, you have to link some of your controls property to something coming from a promise. It can be http call, data stored in files, local database, etc. You end up writing code for wiring data and controls.

enter webcomponents !

WebComponents is a new paradigm, currently under discussion by W3C, to declare components as custom DOM elements. You can get details on this by looking at As the time of this writing, Webcomponents have native implementation in Blink (engine used in Chrome and Opera) and partial support in Firefox. No support in IE or Spartan yet.

Webcomponents is really a very promising spec, and almost all modern front-end framework uses this syntax. Unfortunately, WinJS does not…

WinJS Contrib has a new module, that enables using controls with a webcomponents syntax like this :

<win-listview id="recentItemsList" member 

Using this also allow many improvements on the syntax. As you can see, some of the code that resides in the controller with vanilla WinJS now moved to the declaration of the control. The resolution of control properties can be extended and use the same mecanism we described previously for providing arguments to other WinJS Contrib helpers.

We will deep dive into this mecanism in another post, but to give you a sneek peak, this mecanism use operators to resolve the property. If we look at the « itemdatasource », the string « list:ctrl:recentItemsPromise » could be read as : get the recentItemsPromise property from the containing control, and wrap the result in a WinJS.Binding.List datasource. WinJS Contrib has several operators and you could add your own.

To use webcomponents in your application, you just have to include « winjscontrib.core.js » and « winjscontrib.ui.webcomponents.js ». The module is defining the components for most WinJS controls. It maps control’s properties as attributes on the DOM element. We haven’t tested them all with this new syntax. We would be pleased to get any feedback from you if you encounter troubles with it, or if we missed some properties.

This module use core webcomponents on platform supporting it, and a polyfill for the others. The polyfill uses « MutationObserver ». It means it will work on IE11 and above, so you can use it in your Windows 8.1 and Windows Phone 8.1 applications, and obviously on Windows 10. We haven’t fully tested on Android and iOS yet but it’s the next step, because we use WinJS in many cross platform applications.

In the next posts, we will detail the resolution of properties, and the way you could declare your controls to use webcomponents syntax. In the meantime, go check the sample application, and feel free to send us feedback.

WinJS and ES6

It’s time for a new episode about WinJS and WinJS Contrib ! this time we will talk about using ECMAScript 6 with WinJS and more specifically about using JavaScript classes.

With WinJS pages, you use object literal to define your pages, something like :

WinJS.UI.Pages.define('/pages/home/home.html', {    
    processed: function(element, option){ 
    ready : function(element, options){

WinJS will build a constructor for the page and add the content of the object literal as a mixin on that constructor. When the page is invoked, the constructor is used to produce a new object that hold those methods on its prototype. What is great is that you could call WinJS.UI.Pages.define multiple time on the same page, using some external mixin. This model is very interesting because you could work in the best possible way for a developper : composition.

This programming model has no limit in terms of what you can do, however it has some drawbacks. First, a lot of developpers are not JavaScript gurus. Using OO languages along with JavaScript, they are not familiar or comfortable with the concept of mixins and this syntax looks like some esotheric thing. It’s also a different programming model than the business logic where you may enforce something more « object oriented ». I know « object oriented » is not in the « pure » JavaScript paradigm, but that’s where JavaScript is going with things like ES6 classes.

The other problem with this syntax is about the tooling. More often than not, intellisense goes nuts and does not provide you any help about a variable you created in another function, 5 lines of code above.

Last but not least, the object literal makes things like ECMAScript 6 classes, or Typescript a hell to work with WinJS. This is really odd because : 1 – Typescript is from Microsoft and it does not fit well with their own UI/front-end framework, and 2 – if you play with Windows 10 preview and dev tools, you may have noticed that, if you create an universal app in JavaScript, you can use ES6 in your application. It has not been officially announced yet but it looks like Windows 10 UAP in HTML and JavaScript uses some form of EdgeHTML (the Spartan engine). It means that you can use all the ES6/HTML/CSS goodness that comes along with it, as well as the performance benefits.

So, how could you use JavaScript / ES6 / Typescript classes with WinJS ? in fact it is quite simple. Last time we looked at the basic features of WinJS Contrib, and more specifically the fact that WinJS Contrib override WinJS page control. Once you put WinJS Contrib, you could call WinJS.UI.Pages.define with a constructor instead of an object literal.

class HomePage{
    ready(element, options){
WinJS.UI.Pages.define('/pages/home/home.html', HomePage);

If you start playing with ES6 or Typescript, you may also use some of the other ES6 features. One that could help you improve readability and reduce code is arrow functions. Arrow functions are anonymous function with a syntax identical to lambdas in C#. In addition to syntactic sugar, the arrow functions does not change scope. If you use arrow function instead of functions, the « this » scope is preserved, and you avoid writing tons of ugly code like « that = this ».

To demonstrate those features, we made an ES6 version of the demo application using JavaScript classes. This version is still a Windows 8 version transpiled using Babel, but if you want to have a lot a fun, you could bring it to a Windows 10 UAP (it’s just copying files) and drop Babel, it will work just fine and it is a wonderful playground to experiment with new features of HTML/Javascript in the new rendering engine in Windows 10.

If you want a more direct look, you could check the « searchbar » control that we used to illustrate WinJS Contrib basics on the previous post.

WinJS Contrib Basics

Now that we set the stage for WinJS and WinJS Contrib, it’s time to dig into some code goodness.
In this episode, we will look at the fundamental of WinJS Contrib.

interactive elements

You have interactive elements in all apps. Weither it is with mouse or touch, it is good practice to provide visual feedback on interactions, otherwise the user feel trust in your application. WinJS Contrib has an abstraction over interactive element. Using it will provide an appropriate cursor with mouse, and a visual feedback with touch. It is as simple as :

WinJSContrib.UI.tap(domElement, callback, options);

the third argument is optional and allow you to specify such thing as « disableAnimation » to avoid the « pressed » effect with touch, or « lock » to add interactivity on elements in a scrollable are (like adding a button inside an item in a listview). The beauty is that « tap » is cross platform and will act as « fastclick » on Android and iOS.

When using it, a css class « tap » will be added on the element, and when element is pressed a « tapped » will be set as long as the element is pressed. You can use this to override the default animation.

In previous post, we explained that WinJS Contrib replaces the page implementation of WinJS. Our page control allow you to declare taps in your markup. You must simply add a « tap » attribute on an element, and as a value, you pass the name of the function on your page, like this :

<div class="button" tap="someFunctionOnMyPage"></div>

When called, your function will be bound to the page, it means that when the function is called, « this » refer to your page.

You could specify arguments to tap by adding a « tap-args » attribute. The value will be passed in the argument to the function on your page. The value could be a simple string, or use the resolution pipeline from WinJS Contrib. We will expand on this pipeline in another post, for now, just note that you can inject argument from a property or a function of your page.

<div class="button" tap="someFunctionOnMyPage" tap-args="ctrl:somePropertyOrFunctionOnMyPage"></div>

Another thing that is really common in all applications is to navigate after clicking a button. You can implement this as easily as tap with a « linkto » attribute. As a value, you will specify the url of the target page.

<div class="button" linkto="/pages/home/home.html"></div>

In case you want more, linkto can have arguments, just like tap. The arguments will be passed to the navigation

<div class="button" linkto="/pages/home/home.html" linktoargs="obj:{ index: 3}"></div>

interacting with DOM

When writing a WinJS page, you end up writing tons of DOM selector to get instances of the controls, or DOM element that you will interact with. Your page end up looking a bit ugly with things like this all around the place :

var listView = page.element.querySelector('#myListView').winControl;

If you are wandering why scoping selector to page, go have a look at some WinJS best practices.

WinJS Contrib page introduce a mecanism to map elements and controls as properties on your page by adding a « member » attribute on the node. You could leave it blank, and the name of the property will be the « id » on the node, or you could specify the name of the property.

<div class="button" member="btnClose"></div>

If the element has a control attached on it, the property will hold the control, otherwise it will be the DOM element :

<div member="listview" data-win-control="WinJS.UI.ListView"></div>

then you will use it magically in your page :

page.listview.itemDataSource = new WinJS.Binding.List().dataSource;

If you prefer having the declarations in your page, we still have some goodness for you. The page control has « q » and « qAll » functions for running querySelector and querySelectorAll from your page element, which is at least shorter than the full syntax. The « qAll » function is also kind enougth to map the result as an array, so you can use forEach on the result.

    //do something

preventing leaks

The first cause of memory leaks is unreleased event listeners having a closure on some global variable. To ensure releasing your listener without adding some (ugly) extra code to your page, WinJS Contrib provide an event tracker object. The page control holds an instance of it that you can use. You use this object to attach functions to event listeners, and when you dispose the tracker, it will dispose all attached events automatically. If you use the page instance, the page will take care of releasing the tracker.

instead of

ctrl.showBinded =;    		 
ctrl.searchInput.addEventListener('focus', ctrl.showBinded);
ctrl.searchInput.removeEventListener('focus', ctrl.showBinded);

you have :

ctrl.eventTracker.addEvent(ctrl.searchInput, 'focus',;    

does all this really help ?

Well, see for yourself by looking at the small sample application that we made. You have one version with WinJS only, and another with WinJS Contrib.

This application is for searching Flickr. If you look at the code for the search bar control and compare the pure WinJS and the WinJS Contrib version, you will see a real difference (it removed 45 lines of code on 154…)

Next time we will see other features enabled by the WinJS Contrib page

Introducing WinJS Contrib

Last time we tried to explain why and when WinJS can be a good fit for your HTML application. As an application framework, WinJS is very lean. It’s a great strength, but if you have worked a little with it, you may have found that you write a lot of boilerplate code.

After many applications using WinJS, we decided to share the various helpers that we use as a contrib project, available on Github. If you want to get a glimpse of what WinJS Contrib can do for you, you could have a look at the source, or install the showcase app from the Windows Store. The showcase app illustrate many of the features and allow you to watch the code and the API documentation. The source code for the showcase app is also available on Github.

In this series we will look at the different pieces of WinJS Contrib. But for now, we will provide a general overview.

WinJS Contrib is not delivered as a big library. Instead, we choose to provide several small pieces with dedicated purpose. You will find helpers for communicating with webworkers or iframes, a tiny search engine, helpers to ease the implementation of WinRT features (background transfert, multiscreen, contact API, …), and a bunch of UI controls.

Each of those pieces have been developped and used in one or many applications. Some of those applications can be found in the Windows Store like XBMC Commander, or I’m hungry, and several others apps for our customers.

The heart of WinJS Contrib is in the « core » library. It contains all the helpers for improving syntax and productivity. It’s required by many of the other parts. In addition to the helpers, the core library is also replacing the page control from WinJS. We tried many ways to improve WinJS syntax but unfortunately, WinJS is not built with extensibility in mind, and we find it to be the least invasive way.

The custom page control does not remove anything from core page but it adds a lot. Our page control extend the lifecycle provided in WinJS pages, and provide extension points to unlock many features (enhance the page object, productivity and memory management, using ES6 classes, providing a way to use webcomponent syntax, …).

One package we use in all our projects is the « bindings ». It contains a mecanism for having arguments with your bindings, and a whole lot of basic bindings. For example, bindings for show/hide, enable/disable, binding for images, or for adding ellipsis on text.

Another usefull package is the « animations ». WinJS animations are visually appealing, but one thing that makes them useless in many cases is the fact that you cannot set the duration of the animation, or the item delay. WinJS Contrib animations are all configurable.

To illustrate the various features over this series, we decided to provide a specific Github repository with a small application. You will find a version built only with WinJS, and other versions leveraging features of WinJS Contrib.

In the following episodes, we will go into more details on the various improvements that you will be able to leverage with WinJS & WinJS Contrib, using this application for code demonstrations.

Why WinJS can be a good front-end framework…

We are still early in 2015 and the JavaScript front-end ecosystem is still hot.

There are many popular frameworks out there, Angular 1.x, Angular 2 in alpha, React, Ember, Backbone, Aurelia, Polymer, …

This post is the first on a series about WinJS. In this first episode, we will see what is WinJS, and what it is good for.

Web vs Native

All those framework have their own personnality, strengths and weaknesses. But they all have one thing in common : they are built for the web. To my point of view, none of those frameworks are built for making embedded applications like native HTML Windows apps, Cordova apps, Firefox OS apps, …

Designing and optimizing a mobile application for web, or for an embedded applications is different. When building for the mobile web, your worse ennemy is network latency. Every image, stylesheet or script is slowing your site down, and every bytes count. You try to bundle your files as much as possible to avoid those pitfalls.

When you are building for an embedded application, you don’t care about those network latencies. Every file resides on the device, and loading them is as fast as the SSD is on the device. In fact, on most modern hard drives, it can be faster to load several small files than loading a big one. In addition, in those applications, you will favor loading your application incrementally. It helps your app start fast, and saves memory and battery on the device.

Users don’t care…

With an embedded application, users expectations are different. The user does not know, or care, that your application is built using web technologies. He click on your app icon and assumes that it will perform as any other app on his device. The rendering engines are getting faster and faster but it is still not as performant as native.

To achieve a native look and feel, you must have a fine grained control over the DOM, and you sometimes have to orchestrate how and when your views are built and rendered. Common frameworks tends to abstract DOM away and relies on data binding to build UI. It could lead to a lot of frictions when it comes to optimizing your views. Some frameworks, especially Ionic are built with that performance constraint in mind, but unfortunately, they does not work well on all platforms.


WinJS is a JavaScript front-end framework that was publicly announced in september 2011, at the first Microsoft //Build conference. At that time, it was designed to make native Windows applications using HTML and javascript. Since then, it has been open-sources (go have a look at it on Github) and the latest version are designed to work well on all recent mobile devices. WinJS has basics for the different peaces needed by an application framework (templates, binding, messaging, …) and a rich set of UI widgets.

WinJS has been designed for making fast, native looking applications, and it’s great for that. Whether it is on Android, iOS, or Windows, you can take the most of what your device can do with web technologies. You can use it for web (it is still HTML/CSS/Javascript) but it’s really not designed for it.

What is great with it is that the framework rely on componentization of your UI. You are building your UI by composing controls. Controls can be simple JavaScript classes, or they can rely on « Fragments ». A fragment is loaded from an HTML file, and all dependencies defined in the HTML are loaded along with the fragment. You could modularize your UI and logic, and load it incrementally in a very natural way.

As you can see, the mindset when building an application with WinJS is very much like what you have with WebComponents approaches (except for the Shadow DOM aspects). The main difference is about the syntax you use for declaring your controls (instead of defining custom elements, you use attributes).

So, WinJS is wonderful ?

Well… considering what you can do with it, yes. But it is far from perfect. Sometimes, it’s really not developper friendly.

WinJS is very unopiniated about how to do things. It’s great because you stay in control but it means you have to do a lot of things by hand. What is really sad is that, in its almost 4 years, WinJS has not improved at all for that matter. Microsoft has focused their efforts on UI widgets (making them cross platform for example), but you are still writing a lot of unnecessary boilerplate code.

We have made dozens of applications with WinJS, for Windows, as well as Android or iOS. From time to time we gathered a lot of tools and helpers, and a while ago we decided to publish them to the community, as a « WinJS Contrib » project. In the other parts of this series, we will show you the different aspects that you could improve by using WinJS Contrib.

We will see how to reduce boilerplate code, use ES6/Typescript classes, use WinJS with webcomponents syntax in the markup… so stay tuned !

Best practices for WinJS applications

It’s a very exciting time for writing HTML5 native apps for Windows 8, and now for Windows Phone 8.1. WinJS is a very powerful framework but when you start using it, you may experience some trouble. This article will try to give you some advices on how to design your code, and how to avoid the most common pitfalls.

it’s HTML5 and javascript, but it’s not web

This is my first advice and you should take it very seriously ! You are using HTML5 to build native apps. It requires a different mindset, both in coding and user experience. If you are a web veteran, you might have some habits that you will have to lose. In such an application things are stateful, and you are composing screens based on fragments of html/javascript/CSS that should be independant. If you are familiar with single page applications, you are probably familiar with this mindset.
Another point to keep in mind is the security context. In a Windows application, you will not have to deal with CORS concerns, but you will have to be aware of other security or platform restrictions. Let’s name a few :

  • you are not able to use « alert » or « confirm », use system dialogs instead.
  • you are not allowed to inject anything through « innerHTML », HTML is fine, but adding scripts may trigger an error.

learn javascript

Many developpers, especially in the .NET world, tends to consider javascript as a 2nd rank language, something dirty. Others may think they know it because it ressemble C# or java (look, it has curly brackets…), and because they have used a jQuery plugin long ago.
The truth is that javascript is a very powerful language, and that it’s totally different from languages like C# or java (static, strongly typed, object oriented). Javascript is ascripting, functional, prototyped language.
There is beauty and horsepower in this language, but you also have some horrible things. A book like « javascript the good parts » from Douglas Crockford may help you understand which parts to use and why.

learn promises

If you enter Windows 8 and/or Windows Phone 8.1 application, you enter a world of asynchronous programming. In javascript asynchronous means callbacks and promises, at least until EXCMAScript 6 (which should introduce an equivalent of C# async/await). Many libraries uses promises to manage asynchronous calls, it is a very common pattern (jQuery, Angular, Node.js, …).

The principle is dead simple. When you call for an asynchronous operation, you don’t get a direct result like you would in an arythmetic operation :

var a = 12 + 42;

Instead, when calling an asynchronous operation you will get a promise that you will be notified for the result when it becomes available. To get notified, you will have to tell that promise what you want to do when the operation will succeed, or what to do if it fails. You will end up with something like this :

myFunkyAsynchronousCall().done(function successCallback(result){
  //what to do when successfull
}, function errorCallback(error){
  //what to do on error

In WinJS you can build promises with « done » or with « then ». Both functions has the same parameters (complete, error, and progress callbacks). The difference is that « then » is returning a promise, it’s a continuation operation, while « done » returns nothing and it’s the end of the asynchronous pipeline. The « then » is pipelining errors but not « done ». Be mindfull that pipelining errors make them hard to debug…

Generally speaking use « then » for chaining promises. Otherwise, use « done ». Just like this :

myFunkyAsynchronousCall().then(function successCallback(result){
  return anotherFunkyAsyncCall();
}).done(function secondSuccessCallback(2ndAsyncCallResult){
  //pipeline success
}, function pipelineErrorCallback(error){
  //what to do on error

benefit from HTML5, CSS3, and ECMAScript 5

You are in a place where you know which features you can use. Embrace it ! this is especially true for CSS3 layouts capabilities like flexbox, CSS grid, and properties like « box-sizing ». If all that does not sound familiar, go learn the benefits of CSS3. CSS grid alone can saves you hours of margin+padding nightmares.

you have fragments, use them to store your variables

If you look at what you get when you create a new WinJS project with Visual Studio, you will see a bunch of variables floating around. The Windows 8 samples are no better for that matter. Remember that those code portions are there to demonstrate Windows or WinJS capabilities, not javascript best practices.

You will compose your UI through independent peaces of HTML and javascript. With « WinJS.UI.Pages.define » or WinJS controls, you will define controllers attached to a fragment of HTML. If a variable belongs to a piece of UI, put it inside the code of this fragment.

For exemple, please, please, DON’T write code like this :

(function () {
    &quot;use strict&quot;;
    var myvariable;

    WinJS.UI.Pages.define(&quot;/pages/home/home.html&quot;, {
        ready: function(element, options){
        	myvariable = options.someNavigationParameter;

In the exemple above « myvariable » clearly belongs to the page itself but it is static. Using it like this is bad for several reasons. I will just detail two of them :

  • if you have closure relying on this variable, you may end up with memory leaks because the variable will retain the whole page in memory.
  • you may end up with strange behaviors when you will navigate back and forth to this page, because the variable will still exist with a previous value. Combined with a few asynchronous calls, you will have a very exciting time debugging this kind of issues.

Avoiding those troubles is as easy as this :

(function () {
    &quot;use strict&quot;;

    WinJS.UI.Pages.define(&quot;/pages/home/home.html&quot;, {
        ready: function(element, options){
        	this.myvariable = options.someNavigationParameter;

scope your DOM selectors

This one is also related to the fragment based approach. Imagine that you have a page called « detail ». From this « detail » page you navigate to the same « detail » page but with different parameters. If you are using DOM selectors based on document like « document.getElementById » you will end up with strange behaviors.
The reason is quite simple. When navigating to the second page, getElementById will return the first node with that Id. Depending on your code, the first instance of the page may still be in DOM at that point in time, so your selector will give you a soon to die DOM element. Another case when non-scoping DOM selectors can hurt you is when you are navigating fast in the application. For example opening a page and clicking as fast as possible on the back button. If your page use asynchronous call, and you leave the page before the asynchronous call returns, all your global selectors will return nothing.

Scoping your selector is very easy. First, the « init », « load » and « ready » functions are taking the fragment element as an argument. Secondly, the page object itself has a property called « element » that points to the DOM element of that specific page. Just call « page.element.querySelector(‘#myDomElement’) ». If you are using jQuery for your selectors, remember that jQuery allows you to use scope : « $(‘#myDomElement’, page.element).css(‘display’, ‘none’);

scope your CSS

For better maintainability, we tend to have a CSS document for each fragment. Those CSS are loaded on the fly when WinJS loads each fragment, but they are loaded only once. If you don’t scope your CSS selectors, you may end up with naming collisions. Let’s take an example : fragment A define a CSS class « .myButton » with color red, and fragment B define a CSS class « .myButton » with color green. You navigate to fragment A, the engine loads the associated CSS and the button is red. Now you navigate to fragment B. The engine loads the corresponding CSS and the button green. So far so good. Now if you return to fragment A, the button will stay green because the CSS for fragment A is already loaded and overriden with the one from fragment B. What is funny with this problems is that the resulting behavior will come after some time, and it will depends on the order in which you navigate. Fortunately, the DOM explorer in Visual Studio will help you to find out because you could see the file owning the styles applyed to an element.

As well as what we described for javascript selectors, the best thing to do is to scope your CSS. If you use something like « .fragmentA .myButton { background-color: red } », you lower considerably the risk for namespace collisions.
Using a CSS preprocessor like « .less » may help a lot because you will be able to nest elements instead of cloning selectors. For example, you will write :

.fragmentA {
  .myButton {
    background-color: red

The good news is that you could use less today within Visual Studio, and enforce it with Visual Studio extensions like « Web essentials »

use javascript’s bind

The « this » context in javascript is something that is not always fun. Fortunately there are helpers that could help a lot, and the « bind » function is among the most interesting. It’s a function of the function object, that returns a function bound to a specific « this » context.
Well… it’s probably better to take an example :

(function () {
    &quot;use strict&quot;;

    WinJS.UI.Pages.define(&quot;/pages/home/home.html&quot;, {
        ready: function(element, options){
        	var page = this;
        	page.myButton = element.querySelector('#myButton');
        	page.myButton.addEventListener('click', page.buttonClicked.bind(page));

        buttonClicked: function(arg){
        	var page = this;
        	//do something with your page

The « .bind(page) » used when registering the event forces the « this » context to the page object inside the « buttonClicked » function. Without it, the « this » variable Inside « buttonClicked » would correspond to the button itselt.

use libraries

A Windows or Windows Phone apps written with WinJS is not web but it is still HTML / CSS / javascript. There are tons of libraries and jQuery plugins out there that will help you make great apps. There are also some librairies dedicated to WinJS, like WinJS Contrib that could help you a lot.

have fun !

WinJS is not perfect but I have a lot of fun writing applications with it, I hope you will have too.

Retour sur la //Build 2014

Cette année les annonces se sont orientées autour de 5 grands axes, Windows Phone 8.1, Windows 8.1 Update 1, les Universal Apps, Microsoft Azure et .NET.


Windows Phone 8.1

La mise à jour prochaine de Windows Phone 8.1 sera disponible sur tous les téléphones Windows Phone 8 actuels et embarquera un grand nombre de nouveautés dont certaines ont été très remarquées.

« Hi, I’m Cortana »

Cortana est votre assistant personnel intégré à Windows Phone 8.1. Il se situe comme un concurrent à Siri présent sur iPhone enrichi de fonctionnalités supplémentaires.
Elle remplace la recherche Bing intégrée dans Windows Phone 8 et l’améliore en apprenant à vous connaître comme le ferait un assistant personnel humain. En effet, quel meilleur assistant que celui qui sait quelles informations vous êtes susceptibles de trouver intéressantes !
En plus de vous aider dans vos recherches Cortana peux prendre des rendez-vous, vous signaler d’éventuels conflits et de vous proposer comment les résoudre.
Ce ne sont bien entendu pas ses seules fonctionnalités alors n’oubliez pas de lire les prochains numéros pour plus d’informations sur le sujet !

Centre d’actions

Windows Phone se voit enfin doté d’un centre d’actions. En glissant à tout moment votre doigt vers le bas depuis le haut de l’écran vous pouvez le faire apparaître et gérer l’activation du Wifi, du Bluetooth, du mode avion ou de la rotation automatique de l’écran. Ces différents raccourcis sont ceux par défaut mais vous pouvez bien entendu configurer les actions qui vous intéressent parmi une liste d’actions possibles. Vous pouvez également accéder directement à la liste de tous les paramètres systèmes. Vous y trouverez la liste de toutes les notifications que vous auriez manquées ou la liste des mails non lus. Certains considéreront que cette fonctionnalité arrive relativement tard mais mieux vaut tard que jamais d’autant plus qu’elle s’intègre parfaitement bien à l’ergonomie Windows Phone.



L’intégration de votre Windows Phone dans votre entreprise s’est également fortement améliorée. Votre service informatique dispose désormais de la possibilité de gérer l’activation ou la désactivation de certaines applications, de supprimer à distance les fichiers liés à l’entreprise, de la connexion VPN ou encore de la lecture des mails cryptés S/MIME.


Internet Explorer 11

Internet Explorer 11 fait également son arrivée dans Windows Phone 8.1 proposant une meilleure et plus réactive navigation sur internet. Cette version d’Internet Explorer prend en charge un certain nombre de fonctionnalités liées à WebGL ouvrant ainsi la porte à la 3D dans le Web sur Windows Phone.
Cette arrivée bénéficie bien entendu à la navigation sur internet en particulier sur des sites de partages de vidéos tels que YouTube dont le rendu est maintenant parfaitement satisfaisant. En effet les vidéos se lisent directement dans la page web, supportent les différentes orientations du téléphones et peuvent se mettre en plein écran. Pour rappel, seule cette dernière fonctionnalité était disponible sur Windows Phone 8.


Windows gratuit !

Microsoft a décidé de rendre Windows gratuit pour les appareils dont la taille d’écran est inférieure à 9 pouces. Cela bénéficiera non seulement aux téléphones, aux appareils embarqués mais aussi aux petites tablettes. On peut s’attendre à voir des réductions de prix de l’ordre de 50 dollars sur chacun de ces appareils. Ceci est non négligeable et montre la volonté de Microsoft de concurrencer frontalement Android.

Autres nouveautés

Windows Phone est en plus enrichi d’un nouveau type de clavier, le clavier Wordflow. Il permet une frappe plus rapide et Windows Phone 8.1 a d’ailleurs été reconnu le clavier le plus rapide du marché par le Guinness des records !
Un certain nombre d’API supplémentaires font leurs apparitions dans Windows Phone pour gérer le Bluetooth LE, les nouvelles tâches de fond ou encore l’intégration avec Cortana.

Nouveaux téléphones

A l’occasion de l’annonce de Windows Phone 8.1 Nokia a dévoilé non pas 2 mais 3 nouveaux téléphones !
Les deux premiers sont en fait très similaires, il s’agit des Lumia 630 et 635. Dignes successeurs de l’actuel Lumia 620 ils en sont une version améliorée et remise au goût du jour. On notera tout particulièrement que le Lumia 630 est le premier Windows Phone disposant d’une version supportant deux cartes SIM !
Le dernier est le Lumia 930. Successeur du 920 il présente des caractéristiques techniques très haut-de-gammes.


Windows 8.1 Update 1

Cette mise à jour mineure de Windows 8.1 apporte une nette amélioration de l’expérience utilisateur pour les utilisateurs utilisant le clavier et la souris avec en autres l’apparition de la barre des tâches pour les applications Windows Store.
Il devient possible d’accéder à un menu contextuel lors du clic droit de la souris sur une tuile afin d’en modifier la taille, de l’épingler dans la barre des tâches ou encore de désactiver le côté dynamique de cette tuile.
Elle offre aussi maintenant aux développeurs d’applications Modern UI la possibilité d’interagir avec des composants développés en .NET standard. Cela signifie qu’il sera désormais possible de réutiliser votre code métier ou votre couche d’accès aux données historique dans une application Modern UI. L’option n’étant pas disponible pour les applications à destination du store ceci n’est possible que dans le cadre d’applications d’entreprises et qui ne seront donc pas déployées dans le Store.


Applications universelles (Universal Apps)

Probablement la principale annonce de cette //Build pour les développeurs d’applications Windows 8 et Windows Phone, les Universal Apps sont la dernière étape dans la direction prise par Microsoft pour la convergence entre les téléphones, les tablettes et les pc équipés de Windows.
Il existait auparavant de nombreuses techniques pour partager du code entre les différentes plateformes mais ce partage se limitait bien souvent au code métier de l’application et non aux vues. Avec les Universal Apps il est désormais possible de partager le code lié à votre interface graphique tout en pouvant personnaliser l’interface en fonction du facteur de forme sur lequel votre application fonctionnera.
Cette convergence entre plateforme s’applique aussi au niveau des langages de développement. Depuis Windows 8 il était devenu possible de développer des applications Modern UI en utilisant XAML et C# comme sur Windows Phone mais aussi XAML et C++ ou encore HTML et Javascript. Grâce aux Universal Apps ces différents langages sont désormais supportés dans Windows Phone et il devient donc possible de développer votre application Windows Phone en HTML et Javascript.
Une chose importante à noter est que pour l’instant les Universal Apps sur Windows Phone ne couvrent pas toutes les API disponibles en Silverlight pour Windows Phone. Ainsi il ne vous sera pas possible de vous intégrer complètement au système notamment dans l’écran de verrouillage du téléphone.


Microsoft Azure

De nouvelles fonctionnalités font leurs apparitions dans Azure dont certaines vont changer au quotidien la vie du développeur et de l’administrateur.


Il est désormais possible de créer, gérer, supprimer et même déboguer des machines virtuelles situées sur Azure directement depuis Visual Studio.
Il est aussi possible de prendre un Snapshot d’un ensemble de VM et de base Azure. Cela permet par exemple de faire des copies de votre infrastructure cloud pour effectuer de nombreux tests d’intégration ou de charge en parallèle. Cela permet aussi de déployer votre infrastructure vers un autre Datacenter Azure. Cette fonctionnalité est disponible sous forme de ligne de commande.

Mobile Services

Mobile Services a également le droit à sa mise à jour. Un des reproches fait à Mobile Services était que ces services devaient être développés en Javascript et qu’il était difficile de les intégrer à un contrôle de code source. Ceci est maintenant corrigé car vous avez dorénavant le choix entre .NET et Javascript.
Mobile Services supporte à présent l’authentification sur votre domaine Active Directory et cela fonctionne sur n’importe quel appareil grâce à l’utilisation de token OAuth.


SQL Azure

La taille maximales des bases de données Azure a été augmentée et est maintenant de 500 Go par rapport aux 150 Go précédent. Cette augmentation est assortie d’une promesse d’une disponibilité de 99.95%.
Une autre fonctionnalité annoncée est la sauvegarde automatique et journalière des bases de données et conservés durant un mois. Ceci parlera entre autres à tous ceux ayant par mégarde supprimé une table ou toute une base.
La réplication géographique des bases de données était aussi très attendue. Elle consiste à répliquer toutes les modifications fait depuis une instance dite primaire vers des instances secondaires situées dans des data center différents. Ceci est très utile afin de limiter la latence de vos applications en positionnant vos données aux plus près de vos utilisateurs ou encore d’éviter de perdre vos données en cas de catastrophe, naturelle ou non, dans un data center donné.

Portail Azure

Le portail Azure a été complètement repensé. Il ressemble plus à une application Windows 8 qu’à un dashboard standard. Le terme de « Blade » est utilisé pour définir les éléments graphiques assimilables à des pages qui s’empilent de gauche à droite.
La gestion de la facturation est maintenant bien plus précise. On voit plus facilement quel sont les coûts de chaque élément ce qui permet de mieux prévoir et affiner son budget.
AppInsights est dorénavant intégré dans le portail. Grâce à cela on peut éditer du code, l’archiver dans git ou TFS et même publier directement le site ainsi mis à jour. Les analyses de vos sites sont aussi intégrées. Temps de réponse moyens, disponibilité… Tout y est.




Auparavant, il existait un compilateur pour VB.NET et un autre pour C#. Cela n’est plus le cas avec Roslyn. Roslyn est le nouveau compilateur .NET et supporte ces deux langages. Mais en fait Roslyn est plus qu’un simple compilateur. C’est ce que l’on pourrait appeler « Compilateur as a Service ». Il est en effet désormais possible depuis son application .NET d’intéragir avec le compilateur pour lui faire analyser ou générer du code ! De plus Roslyn a été publié en open source sur Codeplex avec une licence Apache 2.0 ce qui permettra une meilleure intégration de .NET dans des projets libres tels que Mono.

En route vers le natif !

Une autre annonce intéressante est celle de .NET Native. Cet outil va compiler votre code .NET en code machine de façon à avoir des performances proches de celle de C++. Les premiers chiffres annoncés sont encourageants car il est fait état d’un démarrage 60% plus rapide et d’un gain de mémoire de l’ordre de 15% à 20% pour des applications Windows Store. .NET Native est actuellement disponible en version Developer Preview pour les applications Windows Store.

.NET Foundation

Comme pour affirmer ce regain clair d’intérêt pour l’Open Source, Microsoft a annoncé la création de la .NET Foundation. Elle a pour but de regrouper une grande partie des projets Open Source .NET populaires avec entre autre Roslyn, ASP.NET MVC, Entity Framework, Rx, SignalR et d’autres bibliothèques non issues de Microsoft comme les bibliothèques Mimekit et Mailkit de Xamarin.



Ne faisant pas partie des axes principaux il semble néanmoins intéressant de noter la présence remarquée de Xamarin lors de cette //Build. Miguel de Icaza, le créateur de Xamarin et de Mono sur lequel il est basé, a en effet participé à une des Keynotes et a eu une session très remplie où il a présenté son produit. Xamarin est un SDK permettant de développer en C# des applications à destination de iOS, MacOS et Android. Compatible avec les PCL (Portable Class Libraries) il permet de partage une très grande partie du code métier entre toutes les plateformes mobiles comme Windows Phone, Windows 8, iOS ou Android.



Riches en nouveautés surtout du point de vue des développeurs, cette Build aura marqué les esprits. L’unification amorcée des modèles de développement et de consommation des applications est amenée à se poursuivre dans le futur et chacun y trouvera de quoi faire.
L’orientation Cloud de Microsoft est confirmée avec un investissement non négligeable de la société dans le développement du nouveau portail Azure, l’ouverture continue à d’autres plateformes et langages.
Avec des outils tels que Xamarin vous pouvez désormais réutiliser vos compétences et votre code .NET pour cibler d’autres plateformes que celles de Microsoft.
Que vous soyez un développeur natif, .NET ou Web il n’y a maintenant plus aucunes excuses pour ne pas regarder ce que l’écosystème Microsoft peut apporter à votre succès et à ceux de vos projets !