Section 3.6 of the Store Certification Requirements say this:

Your app must neither programmatically close nor offer UI affordances to close it. Windows 8 Process Lifetime Management closes Windows Store apps automatically.

Obviously, then, your app should haven’t close buttons on its canvas or in the app bar. What’s a little tricky is that an app should also avoid closing itself into anything but the most catastrophic circumstances. That is, if an app has detected that it simply cannot run because of corrupt state or such, then perhaps it can close itself (using MSApp.terminateApp, by the way, not window.close, as the former will give you the opportunity to provide information that will surface in the Windows Store Dashboard).

However, situations like not having network connectivity, or really any external condition from which the app can recover, are not ground for closing the app programmatically. I’ve seen some apps do this that clearly weren’t caught by the certification process: I’ll be running along just fine, then I lose connectivity, and then the app informs me of that with a MessageDialog and then closes itself. Ouch! I just lost whatever state I’d built up in the app, so when I restart I have to get back to where I was. This is a big no-no. In such cases, the app should let me know that I don’t have connectivity, but then give me a way to retry whatever I was doing (that is, an app bar command), when I connectivity has been restored.

In other words, be nice to your users and never assume that you should just up and quit because of some external condition. Again, if you detect an internal condition that would make it impossible for the app to continue running, that’s one thing. But if it’s an external condition that the user can remedy, give them the chance to do that and continue using your app.

I, for one, promise to give poor ratings to apps that I find don’t behave well in this way! ūüôā


For some, the Windows Library for JavaScript, or WinJS, seems to take on an aura of mystique, as if it’s something really special or privileged, or something that is absolutely required by a Windows Store App.

The truth is that WinJS is actually just a JavaScript library, like other libraries you might employ. It does have one unique privilege in that it’s obtained automatically via the Windows Store when a dependent app is installed, and is also serviced through the Store.

But otherwise, it’s just a bunch of JavaScript code that makes writing a Windows Store app in JavaScript a whole lot easier, but isn’t absolutely required. For example, WinJS contains the HTML/CSS/JS implementation of those standard Windows 8 controls that aren’t already covered by HTML5. These include AppBar, DatePicker, FlipView, Flyout, ListView, Rating, SemanticZoom, TimePicker, ToggleSwitch, Tooltip, and ViewBox. You can roll your own versions of these if you want, but I’d think you’d want to spend time on those things that make your app really special.

Similarly, WinJS contains an animations library with the Windows 8 personality built right it…all this is implemented on CSS animations and transitions, so you can do it all manually, but what’s the point?

WinJS contains a bunch of utilities that simplify certain tasks in JavaScript–and many of these are pure JS and have nothing to do, really, with Windows itself. For example, WinJS.Namespace.define and WinJS.Class.define provide some built-in ways to deal with module and class patterns, which I find convenient. WinJS.Binding does the same for data binding, and WinJS.Navigation and WinJS.UI.Pages (along with WinJS.UI.Fragments) does the same for implementing a page navigation (that is, DOM-replacement) mechanism so you maintain the script context within an app.

Then there’s the WinJS.Application object that simplifies your interactions with the core Windows structures provided through WinRT–basically giving you an easier way to keep track of the details. All of this is stuff you can again write yourself, but the WinJS team decided that you’d probably like to have something written for you!

Consider something like promises as well. A promise is basically an object that has .then and .done methods on it. Even if you didn’t use WinJS, you’d get promise objects back from async WinRT¬†APIs thanks to the JavaScript language projection. What the code in WinJS.Promises does, then, is give you a set of utilities for doing more with these basic promises, like joining them or creating new ones from scratch. Again, all stuff you might end up writing on your own, just like the wrapper for XmlHttpRequests in WinJS.xhr that makes that async JS API look like a promise such that it can be easily integrated in with other async code using WinRT.

The short of it is that WinJS is a library full of all kinds of stuff for which people inside Microsoft figured a standard implementation would be really, really helpful.

Now along these lines, questions about the nature of WinJS sometimes arise in the context of whether it’s possible to write a Windows Store app using HTML, CSS, and JavaScript and have that app run within other browsers or other frameworks that also use these standards.

You can certainly write code that can be used in both an app and a site, and they can use common services, but an app written in HTML, CSS, and JavaScript has specific structures that are distinctly different from the structure of a web site/web app.

In particular, an app ties into various platform features such as the WinRT API, many parts of WinJS, and the fact that it’s running inside the WWAHost process instead of a browser. Apps are also generally written in an AJAX style (a single HTML page wherein parts of the DOM are swapped in and out) rather than using <a> navigation (which is again why WinJS provides many utilities here).

So again if you modularize your app code to separate pure app logic that can run in a browser (and doesn’t have any Windows-specific dependencies) from that which is platform-specific, then you can achieve some amount of code-sharing. But those apps won’t just run in a browser. They aren’t web apps: they are Windows Store apps that just so happen to be written with the same technologies as web apps.

Is it possible to use WinJS code in a web app, then? Originally, WinJS wasn’t licensed for this purpose, but as of April 2014, WinJS is an open source project so that you can use it anywhere. See http://try.buildwinjs.com/. It’s important to note that WinJS will take advantage of WinRT APIs when they’re available, but it was written to adapt when WinRT isn’t there.

In short, WinJS is¬†a very useful library with many different controls and other capabilities, and now that it’s open source it’s really helpful for creating a Windows-like experience in apps and on the web.


A somewhat frequent question from developers is how to keep some piece of data secret within an app, such as a secret app key provided by a service.

If this is something that an app acquires at runtime, then you want to use the Credential Locker API to securely store that bit of information. The Credential Locker API is found in the Windows.Security.Credentials.PasswordVault namespace.¬†Whatever is stored here is encrypted, of course, and can only be retrieved by the app that saved it in the first place. What’s also very¬†cool about this feature is that the contents of the Credential Locker is also roamed to the user’s other devices if they have PC Settings > Sync your settings > Password option turned on (and the PC is trusted). So if your app is installed on one device, obtains a secret key for a web service, stores it in the locker, and the user allows those credentials to be roamed, then that secret key will be available to your app when that same user installs it on another device. So you’d want to check for the existence of that secret key even on first run.

If you acquire such a key during app development and include it directly in the app package, then there is the possibility that the key can be discovered and extracted. In this case, the best approach is to store that key in a web service that you query on first run, after which you can save it in the credential locker and retrieve it from there during subsequent sessions.

In other words, assume that everything in your app package is public information and take appropriate steps.


HTML5 contains a geolocation API to find the user’s location, something that used to be accomplished by analyzing IP addresses. As shown in the specification, http://www.w3.org/TR/geolocation-API/, the API itself is fairly simple. For Windows Store apps written in HTML/CSS/JavaScript, then, there is an overlap with the Windows.Devices.Geolocation API in WinRT. So which one should you use?

Note: one key difference for any comparison with WinRT APIs is that HTML5 and native JavaScript APIs are available in the web context whereas WinRT is not. This comparison therefore only applies to pages running in the local context; in the web context you’ll want to use the HTML5/JS APIs.

It’s also helpful to note that overlaps such as these exist (a) because of the local and web contexts, and (b) to provide the capability to Windows Store apps written in other languages where an intrinsic API is not available.

With that, let’s look at both APIs in turn.

Geolocation in HTML5

HTML5’s geolocation is available through the navigator.gelocation object in JavaScript. With this you can obtain a single reading, which is useful to present location-relevant content for a visitor, and also watch the position for ongoing readings.

A single reading is retrieved through the navigator.geolocation.getCurrentPosition method, to which you pass a function that receives a position object:

navigator.geolocation.getCurrentPosition(function(position) {
     var lat = position.coords.latitude;
     var long = position.coords.longitude;
¬†¬†¬†¬† …
});

Additional parameters to getCurrentPosition include an error function and an object containing the options enableHighAccuracy (bool), maximumAge (maximum age of cached data in milliseconds), and timeout (in milliseconds).

Ongoing (asynchronous) readings are taken by passing a callback function to navigator.geolocation.watchPosition that takes the same parameters as getCurrentPosition. watchPosition returns an ID for the operation which can be passed to clearWatch to end the readings.

The timeout option value is important as it determines the maximum length of time that can elapse between a call to getCurrentPosition and watchPosition and a callback with a position value. If that timeout is exceeded, the error function is called with a TIMEOUT error. Other error conditions are PERMISSION_DENIED (see below) and POSITION_UNAVAILABLE (no geolocation capability is available, or there’s an error in determining the location). Note that a watch will remain in place when an error occurs.

The position object passed to the callback in both cases contains a timestamp member as well as a coords object. The latter contains latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, and speed (all doubles). Complete details are, of course, in the specification.

Privacy is a concern with geolocation. The W3C specification places the responsibility for insuring privacy on the agent that implements the API. Internet Explorer, for instance, pops up an alert to the user asking their permission on behalf of sites that use the API. This can be seen with the IE9 TestDrive site’s Geolocation page, http://ie.microsoft.com/testdrive/HTML5/Geolocation/Default.html.

If the user disallows geolocation, the error function given to getCurrentPosition or watchPosition is called with a PERMISSION_DENIED error.

Note that when using HTML5 geolocation in a Windows Store app (including any web content in iframes and pages within navigation domains), it is necessary to declare the Location capability in the app manifest. Without this declaration, the APIs will fail with PERMISSION_DENIED errors.

Note also that if a Windows Store app navigates to any additional websites (e.g. uses navigation domains or includes content in iframes) that utilize geolocation, it must also include the domain in the ApplicationContentUris list.

Geolocation in WinRT

In WinRT, geolocation is provided through the Windows.Devices.Geolocation API. In WinRT you create (with new) a Windows.Devices.Geolocation.Geolocator object, which you then configure with various properties if desired: desiredAccuracy (default or high), movementThreshold (double), and reportInterval (double).

Obtaining a one-time position reading is done through the getGeopositionAsync method that produces a Windows.Devices.Geolocation.Geoposition object. Its properties are civicAddress and coordinate, where the properties of the latter are accuracy, altitude, altitudeAccuracy, heading, latitude, longitude, speed, and timestamp.
var gl = new Windows.Devices.Geolocation.Geolocator();
gl.getGeopositionAsync().then(function (posOp) {
     var position = posOp.getResults();
     var lat = position.coordinate.latitude;
     var long = position.coordinate.longitude;
¬†¬†¬†¬† …
});

A variation of getPositionAsync lets you specify maximumAge and timeout parameters.

You can also assign functions to the positionChanged and statusChanged members of the Geolocator object for ongoing readings. positionChanged will be called within the reportInterval setting, and statusChanged is called when the device status changes between the following states:

  • ready: location data is available.
  • initializing: the location provider is initializing (e.g. a GPS receiver is still acquiring satellites).
  • noData: no location data is available from any location provider (like POSITION_UNAVAILABLE in HTML5).
  • disabled: the application doesn‚Äôt have permission to access location (like PERMISSION_DENIED in HTML5).
  • notInitialized: an operation to retrieve location has not yet been initialized (i.e. the app has not called getGeopositionAsync or registered for the positionChanged event).
  • notAvailable: the Windows Sensor and Location Platform is not available on this version of Windows.

Where privacy is concerned, this API will fail unless the app has declared the Location capability in its manifest. At runtime, Windows will also prompt the user for consent.

API Differences and Distinctions

As with other overlapping parts of WinRT and HTML5/JavaScript, the Geolocation APIs in WinRT are primarily there for apps written in C++ and .NET languages, where no other option is available. For written in HTML/CSS/JS, the two alternatives are more or less equal, with a few distinctions:

  • Geolocation options: The movementThreshold option is unique to WinRT, which is used for system power management and which allows an app to only receive readings there has been enough of a change. This is helpful for geo-fencing apps that only want to update themselves when the user has moved far enough away from a given point. To do the same with the HTML5 API requires more frequent location polling and calculating distance to filter out events.
  • Position information: When address information is supported by a location provider, WinRT provides for surfacing that data through the civicAddress property (and its individual sub-propeities).

Thus, developers with existing HTML5 geolocation code, or those who want to maintain as much platform-neutral code in their apps as possible, will likely use the HTML5 API. On the other hand, the convenience of movementThreshold and its positive effect on power management is a significant benefit of the WinRT API.


This isn’t so much a tip for certification, as for improving the chances that your app might be highlighted in the Store. To put it simply, if you don’t include great promotional graphics with your app submission, then the Store doesn’t have what it needs to put your app in the spotlight. Here’s the quote from the documentation, from What to include in your app’s description:

Promotional images

The Windows Store editorial team uses promotional images when they feature¬† apps in the Windows Store. Providing promotional images for your app doesn’t guarantee your app will be featured. But not providing them almost guarantees that it won’t be.

For more info about creating and uploading promotional images for your app, see Promotional images.

That last link above will give you exact dimensions and other requirements for those image.


It occasionally comes up that you need to serially iterate over a synchronous collection, but doing so involves async APIs. For example, you have a vector of StorageFile objects and want to call copyAsync on each of them, one at a time, in the order of the vector.

This can be accomplished with the following code (thanks to Adam Comella for this solution). Assuming that storageItems is the list over which you want to iterate and destination is the folder into which you want to copy those items, you can do this:

var storageItemsPromise = WinJS.Promise.as();
storageItems.forEach(function (item) {
     storageItemsPromise = storageItemsPromise.then(function () {
         return item.CopyAsync(destination);
     });
});
// Call done so that if CopyAsync throws an exception, it’ll cause the app to terminate
storageItemsPromise.done();


I installed the Win8 app called “Logo Quiz” the other day and noticed that the authors used a default splash screen image that simply contained an hourglass:

I found this definitely curious because a splash screen, while serving the same purpose of the hourglass–namely giving the user something to look at while an app is loading–is also an app’s first opportunity for promoting their brand and creating a sense of identity in the mind of the user. So having an app’s splash screen contain nothing but an hourglass works, for sure, but can be made so much better. I certainly hope that Logo Quiz improves upon this in their next version, because they do have a much more interesting tile image to serve as a basis.

At the same time, it’s clear that some of the blame for this misunderstanding lies with Microsoft’s early app templates in Visual Studio, where the default splash screen image from those templates showed a clock face:

This could easily have been interpreted to say that the purpose of the splash screen image is to show an hourglass representation of some sort, but indeed, that’s not the point at all. This is one reason why the current templates now just have a box with a big X through it as if to say “please don’t use this image!” (though some apps still do!).

In the end, always remember that the splash screen image is the first thing a user sees when they tap your app tile, so you want to make it as engaging and inspiring as you can–make the user happy that they tapped your tile! Help them to look forward to spending time in your app! As one example, I offer the splash screen of Pinball Fx2, an app with which I spent far too much time over the Christmas holidays:

I would almost venture to say that a great splash screen image is one that makes your users wish the app would load faster–and then, of course, you’re in great shape to use an extended splash screen….


Apps written in JavaScript occasionally need to obtain a UUID/GUID for one reason or another, so the question comes up: how to generate one?

One method is to just fabricate thestructureof a GUID with random numbers:

‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’.replace(/[xy]/g, function (c) {
var r = Math.random()*16|0, v = c == < ‘x’ ? r : (r&0x3|0x8);
return v.toString(16);
});

The problem here is that uniqueness is not guaranteed. If you’re just using the identifier for some internal purpose, this method could work, but if you’re taking that GUID anywhere outside of your app, you run a possibility of collision with a properly-generated GUID.

The robust method is to use the Win32 CoGreateGuid() API that creates a GUID that is guaranteed to be unique. For this you need to write a small WinRT component¬†as a wrapper,¬†which, as I showed in Chapter 16 of my book, is actually quite easy and the resulting component (DLL/WinMD) is quite small. So while some have considered this a “heavyweight” solution, it’s actually not that heavy.¬†Do note that CoCreateGuid, as a COM API, takes a little work to translate its result into a WinRT string (see this thread¬†and this thread).

The same can be done through a C#/VB component with its NewGuid method, where the component would look like this:

public sealed class GuidProvider
{
public static String GetGuid()
{

Guid g = Guid.NewGuid();
return g.ToString();
}
}

The caveat with this, as I describe here, is that for even such a simple C# component, you’ll be pulling in the .NET runtime into your process, which significantly increases the memory overhead at runtime. So in the end, it’s better to use C++ for this purpose.

 


At the recent Facebook/Windows 8 Hackathon hosted at Facebook headquarters, I was helping one group who was bringing a bunch of JavaScript code from a website into their project. They brought all this in with <script> tags at the top of default.html, where default.html contained just a <div data-win-control=”Application.PageControlNavigator” …> as some of the Visual Studio templates provide.

The PageControlNavigator was pointed to the app’s home page in its options, and that page control contained various <canvas> elements that the various JavaScript code attempted to initialize.

Almost everything worked. However, the code that attempted to obtain a canvas element and perform some initialization was failing. More specifically, document.getElementById calls with the canvas IDs were returning null, clearly indicating that those elements did not yet exist in the DOM.

The cause for this was that the code pulled at the top of default.html was all being executed before the PageControlNavigator was able to load the home page contents and attach it to the DOM, thus that page’s elements were not yet available. To correct this, we only needed to move the one bit of code from all those files that started the initialization process into the page control’s ready method, and all was well.

In short, when using page controls, the ready method is where you can be assured that the page’s contents have been loaded and are available for manipulation. The exact timing of how all those elements get into the DOM is different from the direct contents of default.html (and different from what you might know from your browser experience), and so initialization calls need to be in the ready method and not just executed automatically on loading default.html.


For all the time you’ve been working on your app, everything’s ran beautifully. But then you submit the app to the Windows Store for certification and it comes back with a failure on requirement 3.2, “Your app must not stop responding, end unexpectedly, or contain programming errors” (see Store certification requirements). You’re utterly confused by this, because so far as you’ve seen, the app has never, in fact, crashed or failed to respond. What can you do about it?

First of all, the person who tested the app has hopefully given you some indication of what they were doing when the crash or hang happened. But what if they didn’t? Or what if you have trouble reproducing the problem?

What this really boils down to is how you test your own apps prior to onboarding them to the Store. I point this out because the developers I’ve worked with during the developer previews of Windows 8 had widely varying testing methodologies–or a complete lack of them! The ones who had a culture of testing within their organizations generally didn’t run into this certification failure–it was much more common with partners who didn’t have a good sense of what testing meant for their app.

Let me make it clear as I did in Chapter 17 of my book: testing an app is orders of magnitude more important than testing a website! Testing a site is often done one page at a time, and changes to one page typically don’t affect the rest of the experience. Therefore, if there’s a bug on that page, its impact is isolated. Furthermore, once you identify and fix the problem, you can release an update (by uploading the new page) in¬†a matter of minutes.

In contrast, a problem in an app has a much greater impact, because the app is a single package as opposed to multiple hosted pages. Issuing an update to the app (assuming it’s already in the Store), also takes at least a week. Therefore it behooves us to spend much more time really testing apps.

Basic testing–and this is all I really want to go into here–primarily means exercising every code path you can identify in your app: leave no feature untouched! To check this, set breakpoints in your code at the start of every feature-related function, and make a checklist. Run and exercise the app, and check off those functions that have been hit and for which you’re walked through the code. Take off the breakpoint and continue testing. At the end of the process, if you haven’t hit certain functions, figure out how to create the conditions where they will be.

Once you’ve identified all the code paths, you need to exercise them under a variety of real-world conditions that the app might encounter. These conditions include, but are not limited to:

  • First time the app runs after installation, meaning an entirely clean installation and that there are no existing caches, no existing app data, no saved state, etc. For this purpose, try to have a separate device where you only install the .appx for your app and not run it in Visual Studio.
  • First time an app is run on one device where the same user has installed it on another device, meaning that there may be roaming state present on first run.
  • Subsequent runs with previously saved app data and new roaming state from another device.
  • Running after being terminated by the user, both within 10 seconds of closing (during which time the app is just suspended), and after 10 seconds (when the app has been fully unloaded).
  • Running after being terminated by the system, where the app needs to rehydrate itself from saved state.¬†(Visual Studio helps to simulate this.)
  • Variations in network connectivity: network, no network, airplane mode, a slow connection (requests go through but might be timing out on occasion), metered networks (which affect background transfers and should affect your own data transfers).
  • Variations in screen sizes and pixel densities. (The Visual Studio simulator helps with this.) This can include plugging in external monitors or projectors.
  • Exercising all the view states: snapped, filled, fullscreen-landscape, and fullscreen-portrait. These exercise your resize methods and media queries.
  • Exercising the app with all input methods: mouse, touch, and keyboard, both independently and simultaneously.
  • Exercising the app on a variety of different hardware with different performance characteristics, e.g. from a slow ARM machine to a fast multi-core gaming box. This can help uncover race conditions and latency issues that might occur on some devices but not on others (like the machine you’re working with). That is, some problems can arise when code executes too slowly, or when it runs too quickly. Remember for this purpose that Microsoft has set up Windows App Labs where you can go test with lots of real-world devices.
  • Purposely abuse the app in ways that you don’t think it should be used. Try invoking different command when they should be (especially via the keyboard). Open all your charms (search, share, settings) and play with them on every page of the app.
  • Navigate between all your pages slowly and quickly.
  • Pan/scroll around within your app slowly and quickly, especially in list views and other layout that has lots of rendering involved.
  • Simulate failures with any web services you employ. You might have great connectivity, but what if the service itself is down? What if it returns bad data? What if you’re hitting a server in another country that you didn’t realize? I speak of the latter because the manual testers for the Store are located in different places around the world, so while you might be hitting a server near your home, the tester might be hitting one in Eastern Europe.
  • Ask yourself also if your code is robust to handle bad data coming back from a service.

There are probably more things you can try, for which I refer you to other resources on software testing. The point is, testing is a real art that needs your attention with apps. With some focus on testing–hopefully a strong focus–you should avoid certification failures for crashes and hangs. And even if you still get such a failure, doing testing along the lines I’ve described here will likely uncover the problem.