New Windows 8 How-Do-I Videos Released

I’m pleased to announce that a new series of short videos, called “How Do I?” created by your local Microsoft Technical Evangelists has been posted to Channel 9. Contributors include Jeff Barnes, Jeremy Foster, David Isbitski, and of course yours truly. Running between 8 and 15 minutes, these videos are intended to give you solid technical information on a specific topic in Windows 8 development, with no fluff, plenty of code examples, and kept short enough that you can easily fit them into your busy schedule.

My first foray, covering how to implement the Settings contract in a Windows 8 app written with HTML5 and JavaScript, is embedded below (note: for best viewing of the code, click the button at the bottom right of the player to view the video full-screen):

Continue reading New Windows 8 How-Do-I Videos Released

Microsoft DevRadio: Developing a RockPaperAzure Windows 8 app

In today’s episode Developer Evangelists Andrew Duthie, Brian Hitney and Peter Laudati recap the “Rock, Paper, Azure” – (#BeatTheGu) challenge from this year’s TechEd as well as how they built a Windows 8 App for the competition. Tune in for this lessons learned session on what considerations and features Andrew took into the design of the app. Continue reading Microsoft DevRadio: Developing a RockPaperAzure Windows 8 app

W8WIL #3: Timers using setTimeout in a Windows 8 app

In this, the third, post in my series “Windows 8: What I’ve learned,” I’ll share how the behavior of script loading and unloading in some Windows 8 Metro app templates require a different approach to using setTimeout for timers.


RPAHome_2 I recently had the opportunity to spend some more quality time with the Visual Studio 2012 release candidate, building a Windows 8 app for some of my teammates who focus on Windows Azure, Brian Hitney, Peter Laudati, and Jim O’Neil. You can see a screenshot of the app to the left.

One of the really cool things that these guys have built on top of Windows Azure is the Rock Paper Azure Challenge, an contest to see who can code the most effective online bot to play the game Rock, Paper, Scissors in the cloud. Cool prizes are available, from Best Buy gift cards, to Windows Phones to XBOXes and Kinects.

For TechEd North America this week, they came up with a very special contest, called Beat The Gu. The idea is simple…Scott Guthrie (whom most of you probably know now runs the Azure team), has a RockPaperAzure bot, and TechEd attendees could compete to see who could beat his bot (with a top prize of a 60″ LCD TV).

One of the features that the Rock Paper Azure Challenge provides is a set of leaderboards for all of the various contests that are currently running, with the data accessible via the OData protocol. This makes it super-simple to grab the data in a Windows 8 Metro style app as either XML (ATOM-Pub format) or JSON. I chose to build the app using HTML and JavaScript, so JSON format was perfect.

I’ll be sharing more details on the app and what went into it in a future post, but for now I want to focus on one of the things that bit me during the development process, namely using setTimeout to create a timer.

What I Learned

For the Rock Paper Azure Leaderboard app, I used the Navigation app template, which consists of a default.html page containing a div that becomes an instance of the PageControlNavigator class, which is defined in a script file called navigation.js. Basically this control provides an easy way to dynamically load fragments of markup, CSS and script referred to as Page controls at runtime. And the way that script resources are loaded and unloaded is a little different when using this template, as we’ll see in a bit. You can read more about how single-page navigation works here.

One of the most important features was for the leaderboard information on the home page to be refreshed periodically, since the contest takes place in rounds and after each round, the position of the players will typically change. Since I was using HTML and JavaScript to build the app, the natural way of doing this was to use JavaScript’s setTimeout function to periodically refresh the data.

In earlier versions of the app, I had code in the home page’s ready function that would call a function in my data.js file (modeled after the pattern in the Grid app template) to retrieve a WinJS.Binding.List with the leaderboard data, then bind that data to a ListView on the page. Once all that was done, I would call setTimeout, passing it the name of the function to refresh the data, along with the timeout duration, something like this:

   1:  ready: function (element, options) {
   2:      var promise = Data.init();
   3:      promise.done(
   4:          function (leaderboardList) {
   5:              leaderListView.winControl.itemDataSource = leaderboardList.dataSource;
   6:              setTimeout(dataUpdateLoop, 30000);
   7:          }
   8:      );
   9:  }

Essentially, the code above will call a function named dataUpdateLoop after 30 seconds. This works great…as long as you stay on the home page.

RPA_scripts_2Although Windows 8 apps written in HTML and JavaScript use standards-based technologies, there are some subtle differences in how the JavaScript and CSS files are loaded (and unloaded, importantly) when using the Navigation app template. With a web site, when you switch to a different page, the DOM is unloaded, and any scripts that were running are no longer in scope. The new page is then loaded, along with any scripts it references.

In an app based on the Navigation template, script loading is a little different. When I run the app, all of the scripts and such required to display the homepage are loaded, as shown in the Solution Explorer screen capture to the left. The base.js and ui.js files are part of the WinJS library, and will always be loaded in a Metro style app (they’re referenced in default.html). default.js and navigator.js are loaded by default.html, and provide support functionality for the entire app, since default.html acts as a parent container for the whole app. settingsUtil.js and searchResults.js are also loaded by default.html, and support the Settings pane and Search contract, respectively.

The remaining JavaScript files, data.js, home.js, and converters.js, are loaded by home.html, which is a Page control that is loaded automatically when the app starts up. Now let’s take a look at what happens when we go to a different part of the application, for example, we can visit the player details page by tapping or clicking on one of the player tiles on the leaderboard:

RPA_playerDetails_4 When the details page loads, we see the screen to the right, which shows us the details for the selected player, including their current place, number of wins and losses and ties, total points, and the date and time of their last match. But of greater interest is what happens with our scripts. If we take another look at the Solution Explorer, we’ll see that another script has been loaded, playerDetails.js, as shown below:


In addition to the new JavaScript file being loaded, notice what didn’t happen…none of the previously loaded scripts were unloaded. BUT…the controls on the homepage (most critically the ListView control containing the leaderboard info) are no longer instantiated. The impact of this, as I discovered in testing the application, is that the timer I set in the code above continues executing, but because leaderListView is no longer instantiated, the dataUpdateLoop function will throw an exception.

Suffice it to say, this was not an acceptable result. I still needed to update the leaderboard on a regular basis, but having the app throw exceptions or crash if I tried to look at the details or use other functionality in the app was not OK.

The Solution

I’m sure there are probably any number of ways to work around a problem like this, but here’s what I came up with (I welcome suggestions for a more elegant or robust solution in the comments). The key is to clear the timer when you move to a different page, and restart the timer when you come back to the home page. Conveniently, JavaScript includes a function for just this purpose, called clearTimeout (there’s a corresponding version for setInterval as well if you’re doing timers that way). But you need to do a little more work in order to use it. clearTimeout requires you to provide it with the ID of the timer you want to clear, which conveniently is a return value of the setTimeout function when called (in my code above, I was simply ignoring this value).

To implement this, I refactored my code as follows:

   1:  ready: function (element, options) {
   2:      var promise = Data.init();
   3:      promise.done(
   4:          function (leaderboardList) {
   5:              leaderListView.winControl.itemDataSource = leaderboardList.dataSource;
   6:              if (appSettings.refreshData()) {
   7:                  appdata.current.localSettings.values["currentTimeoutId"] = 
   8:                      setTimeout(dataUpdateLoop, appSettings.refreshDataInterval());
   9:              }
  10:          }
  11:      );
  12:  }

In the bold section of the code above, I’m capturing the ID of the timer that I’m creating with setTimeout, and storing it as value named “currentTimeoutId” in my local settings. That allows me to access the ID later if I need to clear the timer. I’ve also modified the code to include a check of another setting, refreshData, which is defined in settingsUtil.js, and is a boolean value indicating whether or not to perform the refresh. I’ve also moved the refresh interval into a setting which is likewise exposed by settingsUtil.js. To cancel the timer when navigating to another page, I simply add the following code to the function that’s mapped to the ListView’s oniteminvoked event:

   1:  function itemInvoked(args) {
   2:      args.detail.itemPromise.done(
   3:          function (item) {
   4:              if (appdata.current.localSettings.values["currentTimeoutId"]) {
   5:                  clearTimeout(appdata.current.localSettings.values["currentTimeoutId"]);
   6:              }
   7:              WinJS.Navigation.navigate("/pages/details/playerDetails.html",;
   8:          }
   9:      );
  10:  }

In the bold section of the code above, I’m testing whether I’ve captured an ID from a call to setTimeout, and if so, I’m calling clearTimeout and passing in the relevant timer ID. That’s all there is to it!


When using JavaScript to write an application, whether for the web, or for a Windows 8 app, you need to be careful to understand the scope in which your code is executing, as well as when that code is loaded and unloaded. The Windows 8 Metro app development environment helps you by including best practices, such as wrapping your page code inside a self-executing anonymous function, to help you avoid problems with variable name collisions, etc. The Navigation template is a great place to start because it provides some key infrastructure (including a consistent back button users can use to go back to the previous page) to help you help your users find their way around your app. But you need to keep in mind that script loading in a Metro style app behaves somewhat differently when using the Navigation template to implement single-page navigation.

Note that this tip also applies to the Grid App and Split App templates, since they use the same single-page navigation pattern using navigator.js.

I hope you found this tip useful…if so, please share with your friends and colleagues!

W8WIL #2: Declaratively Specifying an ItemTemplate in a Fragment

I’ve been playing quite a bit over the last few days with the new Windows 8 Release Preview, as part of a special team project I’m working on with some of my fellow DEs. One of the areas I was working on is doing some simple databinding using a ListView control in a JavaScript Metro style app based on the Navigation App template. In this second installment of my Windows 8, What I’ve Learned series, I’ll give you a tip that may help save you some pain and troubleshooting time when declaratively associating an ItemTemplate for a ListView control inside a page fragment.

I was able to very easily create an array with a couple of objects, each with a couple of properties, and then bind those to the ListView by passing the array to the constructor of the WinJS.Binding.List object, which gave me a List object with a dataSource property that I could assign to the ListView’s itemDataSource property in the ready() function of home.js, like so:

listView.winControl.itemDataSource = myList.dataSource;

So far, so good…when I ran the project, the data showed up, in JavaScript object style, as expected. But since that’s not a very interesting way to display data, I of course needed to add an ItemTemplate, similar to the following:

   1:  <div id="myTemplate" data-win-control="WinJS.Binding.Template">
   2:     <div>
   3:        <div class="win-type-large myTitle" data-win-bind="textContent: title">
   4:     </div>
   5:  </div>

Once I had my template declared (note the data-win-control attribute that tells WinJS to instantiate this as a BindingTemplate), I had to tell my ListView about it, which I could do either programmatically or declaratively.

TIP: If you look at either the Grid App or Split App JavaScript templates, both show examples of assigning a template to a ListView programmatically.

I find declarative syntax a bit simpler, so I wanted to do it that way. In previous demos I’ve done, the syntax looked like this:

<div id="listView" data-win-control="WinJS.UI.ListView" 
   data-win-options="{itemTemplate : myTemplate}"></div>

I dutifully added the data-win-options attribute to my ListView markup, ran the project again, and…nothing. The underlying data was still being rendered as a JavaScript object.

I spent a couple of hours pulling my hair and making little changes to the code before it finally dawned on me to check the ListView quickstart documentation, and lo and behold, it turns out that the declarative syntax above doesn’t work when your markup is part of a page fragment, which is what you get as part of the Navigation App template. Instead, you need to use the following syntax:

<div id="listView" data-win-control="WinJS.UI.ListView" 
   data-win-options="{itemTemplate : select('#myTemplate')}"></div>

The “select” will walk the DOM to resolve the reference, while the direct id reference in the first example won’t work because the fragment markup hasn’t been added to the DOM by the time that the resolution takes place.

So if you’re working with ItemTemplates declaratively in page fragments, be sure to use the “select(‘#templateId’)” syntax to associate your template with your ListView.

(h/t Jeff Sanders – moderator in the Metro Style apps forums for more detail on the underlying issue)

Designing Metro style: Being the Best on Windows 8

The other day, I published a post that contended that every developer has at least some responsibility for the design of the apps they’re working on, particularly if they don’t have the luxury of working with full-time designer on their project. The post also looked at some of the history of the Metro design language, and how the work that Microsoft is doing with Metro style apps in Windows 8, and the guidance we provide, can help developers build great apps.

no1_sm_2As developers, too often we don’t feel like we’re getting anything done until we start writing code, but when it comes to designing a great application, just cracking open Visual Studio and going to town isn’t going to give you the results that you want. I’ve had the privilege of sitting in on some training provided by the UX Evangelists in my organization, which included a great recommendation for how to get started on the right foot, and that’s to figure out the answer to the question “What is my app best at?” And it’s important to be able to answer this question succinctly and simply. Once you have a “best at” statement, it will guide you in identifying and prioritizing the core scenarios and features that support that “best at” statement.

Without a “best at” statement, the temptation may be strong to throw in every feature you can think of in an effort to outdo your competitors in a contest of who can come up with the longest bulleted list of features. This is not a recipe for success in a Windows 8 Metro style app. Why? Because it’s virtually impossible for an app to be “best at” everything, so being selective about the features you focus on is more likely to lead you to success.

Continue reading Designing Metro style: Being the Best on Windows 8

Windows 8 Release Preview and Visual Studio 2012 RC

On the off chance that you’ve not heard already, I wanted to share the great news that the Windows 8 Release Preview and Visual Studio 2012 Release Candidate are both now available for download.

UPDATE: I noticed that the link above only gets you to the Visual Studio 2012 Express RC install. If you want to try a different version, head on over to the Visual Studio product site downloads page, and you can get the edition of your choice there. You can also read up on the “go live” license, and what’s supported under it.

Download Links:

Windows 8 Release Preview

Visual Studio 2012 Release Candidate

While you’re waiting for the bits to arrive over the ‘tubes, check out some of the following great posts about these releases:

Delivering the Windows 8 Release Preview

Visual Studio 2012 RC Available Now

Visual Studio Dark Theme

Announcing the Release Candidate (RC) of Visual Studio 2012 and .NET Framework 4.5

Visual Studio 2012 and .NET 4.5 Release Candidates available now!

New – Whitepaper: Migrating your Windows 8 Consumer Preview app to Windows 8 Release Preview

UPDATE – two more links:

What’s changed for app developers since the Consumer Preview

Windows Release Preview: The Sixth IE10 Platform Preview


Why Developers Should Care About Design, and How Metro Helps

Or…I was a Teenage Design Have-not

I’m going to avoid casting aspersions on my fellow developers and instead simply own up to my own failings…I’ve been developing software since I was 10 years old (my first program was written in BASIC on a Commodore PET), and professionally for well over a decade, and for most of that time, I believed that design was someone else’s job, and that it didn’t matter whether I could design my way out of a paper bag.


Design is everyone’s responsibility, at least to some degree. No, you don’t have to start wearing black turtlenecks or engaging in other clichés, but what you should do is start cultivating a basic knowledge of design, and training your eye for what is and isn’t good design, both in the world of pixels as well as in the real world. Have you ever found yourself marveling at how difficult it is to figure out how to use some basic device? Listen to that voice in your head…it’s telling you that you’re dealing with a bad design.

Continue reading Why Developers Should Care About Design, and How Metro Helps

Databinding in Windows 8 JavaScript Metro style Apps

[ NOTE: This post was written using the Visual Studio 11 beta and Windows 8 Consumer Preview…as with any pre-release software, the code and concepts are subject to change in future versions ]

One of the nice features of the new JavaScript Windows Metro style app templates in the Visual Studio 11 beta is that they provide built-in support for databinding, using sample data in a JSON array. Folks who have experience in the XAML world may not see this as a particularly big deal, since Silverlight and WPF have supported databinding for a long time.

For web applications, however, data binding is still a concept that’s evolving. While there are third-party libraries like Knockout.js that provide client-side databinding (and my fellow DE David Isbitski recently published a blog post detailing how you can use Knockout in a Metro style app, if that’s your cup of tea), but in general the web world is a little behind the curve compared to XAML-based databinding.

Continue reading Databinding in Windows 8 JavaScript Metro style Apps

Grantophone on Windows 8 in NYC

Had to share this…Grant Kot, a cello student at Juilliard who also dabbles in C++, is the author of the fun and popular Grantophone app for Windows Phone. Grant was a special guest at the keynote of our New York City Windows 8 Developer event last week, and showed off his Windows 8 version of Grantophone (which you can get from the Windows Store if you have installed the Windows 8 Consumer Preview). Here’s the video, with Grant performing the Imperial March from Star Wars:

Fun stuff…I can’t wait to see what he comes up with next!

CapArea.NET Follow-up: HTML5 Metro apps resources

caparealogoMy thanks to everyone who came out tonight for the Capital Area .NET User Group for my presentation on developing Windows 8 Metro style applications using HTML5 and JavaScript. Great questions and lots of great discussion. Thanks for keeping me on my toes!

As promised, I wanted to share pointers to some additional recorded sessions from BUILD that you may find useful, as well as a link to the sample Canvas Paint app that I used for my demos. If you’re interested in getting the additional tweaks I added to the sample to support persisting the brush color and size, etc. please drop me a note via my contact page, and I will be happy to share it.

Additional Related BUILD Sessions:

and the presentation on which my talk tonight was based:

UPDATE: Nevin House, who attended last night’s talk, got in touch with me via email, and recommended the following two talks on JavaScript, and I heartily agree…both are great talks and are highly recommended for anyone wishing to better understand JavaScript in the context of Metro style apps in Windows 8:

Both presentations feature some of the best presenters from BUILD. Enjoy!

Canvas Paint Sample App

canvasPaintLogo_2The Canvas Paint sample app, along with many other samples and demos, may be downloaded from the Samples area for Windows 8. The direct link to the Canvas Paint sample is:

Note that you can browse the code directly online, or download the sample and run it locally (if you have installed the Windows 8 developer preview).