Mini Gadgeteer Game Console on a Wii Controller

GadgeteerChuckyValentin Ivanov (aka Architect on the TinyCLR Forums) just posted one of the more awesome projects I’ve seen for .NET Gadgeteer. He’s built a mini game console using a repurposed Wii controller, plugged into his custom Chucky module, to control a ported version Pac-Man (he’s also working on a port of Space Invaders). This is just the kind of project that I think makes Gadgeteer so awesome.

Go read his blog post for all the details, including his hand-cut and drilled mounting board that connects the FEZ Spider mainboard and T35 LCD to the controller.

Oh, and if you’d like to see this awesome project in action, come to MADExpo next week. Valentin’s is just one of the many cool projects that will be on display in our demo room. I’ll also be bringing some Gadgeteer coolness, as will Pete Brown, and Sean Westcott (and Sean’s project involves electroluminescent wire…awesome!). And I hear the peeps from 757 Labs will be back as well. Should be great fun!

Register now!

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