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.


While I was preparing for my Alive with Activity talk at the //Build 2012 conference last October, I was thinking more deeply about the design of the Windows Start screen, live tiles, and why, exactly, the API for live tiles (as well as toast notifications), limits you to using a predefined ‘template’ for a tile’s XML update payload. Put another way, why didn’t Microsoft just allow apps to create whatever kind of tile updates they want to? Why shouldn’t an app developer have complete control over the appearance of their tiles?

The clearest reason, to me, is that the Start screen is the central piece of shared real estate in the whole system. As such, it really begs for a sense of unity across the whole experience, and works best when there is consistency between the tile updates that are happening for all the apps involved.

With this in mind, I’ve been reflecting on the Start screen experience as it relates to the three ‘qualities’ of energy, known in the Bhagavad-Gita and other Vedic teachings of ancient India as the ‘gunas.’ These qualities are something that one of the best-known modern masters, Paramhansa Yogananda, drew from extensively in his teachings. For example, one of his early writings, Psychological Chart (1925), identified many different psychological qualities as expressing one or more of the gunas.

The three qualities or gunas, as explained in Yogananda’s Autobiography of a Yogi, are tamas (obstruction, inertia, ignorance), rajas (activity), and sattva (elevating or expansive, sometimes written sattwa). These provide a way of understanding the predominant nature of human beings, and is, in fact, at the core of the Living Wisdom School attended by my son (a system that is explained in the book Education for Life, written by J. Donald Walters, himself a direct disciple of Yogananda).

Human psychology aside, my point in this post is to think about the ways that the start screen of an operating system can be designed, and how they related to these qualities.

One design is something we all know very well: a screen full of static icons, perhaps with a pretty picture in the background. Yes, this design has been around for 20 years or so now (can you say Windows 95), and while it works and can look beautiful, it’s actually quite lifeless. In many ways, then, this design can represent some elevating qualities (sattva) but by its static nature—if not its age!—represents inertia (tamas).

Another design would be to give apps a space on a start screen in which they can do anything they want—any kind of text and image content, perhaps video and audio, whatever kinds of animations they might choose, and so on. Certainly this is a step above the static, tamasic kind of experience, but the result is un-unified, undirected, and chaotic. This is rajas at its best, like when you’re busy and active just for the sake of being busy and active. Such activity helps remind you that you’re not dead, but isn’t particularly elevating in the sense that you derive any true joy or happiness from it. Indeed, what lies at the end of this road is exhaustion and a collapse back to the tamasic state. Put another way, if you designed a start screen like this and (hopefully) allowed users to turn off the noise, it’s likely that they’ll turn it off rather quickly, especially if multiple apps wanted to play audio and video simultaneously!

A third design is to allow for some activity, but in such a way that there is that sense of unification, coherency, and beauty without letting things get out of hand. This is both rajas and sattva working together—an activating+elevating experience.

And this is exactly what I think the Windows Start screen, through the tile update templates, achieves. There is activity, certainly (and still something that users can control), but that activity is coordinated such that tile animations and the update cycle happen in a way that’s actually enjoyable to look at, rather than an eyesore.

If you haven’t been on your Start screen for a bit, assuming you’ve been reading this post, hit the Windows key and watch what happens. When you first land on the Start screen, there’s a moment of rest where everything is quiet. Then a number of tiles will update more-or-less together (but a bit in a sequence too), and then everything gets quiet again. After a time, a few tiles will again update or animate, and then a period of rest.

It’s this coordination between the app tiles, combined with the period of quiet and rest, that makes the Start screen alive with activity, but not busy with activity. And as apps draw their tile updates from a choice of available templates, every update has a relationship with the others that also reinforces this sense of unity.

Personally, I think it’s a brilliant solution.


Recently I was scribbling out some for a ListView control and wrote out a WinJS.Binding.Template in default.html. I misspelled data-win-control, leaving off the ‘l’ at the end:

<div id=”entryTemplate” data-win-contro=”WinJS.Binding.Template”>

The result of this was a curious exception way down in WinJS: (for the benefit of search engines, the error text is “Exception is about to be caught by JavaScript library code at line 20074, column 9 in ms-appx://microsoft.winjs.1.0/js/ui.js … 0x800a138f – JavaScript runtime error: Object expected”)

Spelling data-win-control correctly fixed the problem, but I wanted to make a note of what caused this error with a WinJS.Binding.Template. Basically because I’d misspelled the attribute name, a template control never got created, thus the non-existent object.


If you have occasion to do a live demonstration that’s being projected onto a larger monitor or screen, you can change a setting in the desktop Control Panel to make your touch points show visual feedback. This allows your audience to better follow exactly what you’re doing.

That setting is in Control panel > Hardware and Sound > Pen and Touch > Change touch input settings, then check the “Show visual feedback when touching the screen” box (see below). You might also want to check the “Optimize visual feedback for projection to an external monitor” box as well. Note that this setting appears only on systems that are touch-enabled.


Thanks to my teammate Kyle Marsh for this one:

var freeSpaceProperty = "System.FreeSpace";
var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;

localFolder.getBasicPropertiesAsync().then(function (basicProperties) {
    // Get extra properties
    return basicProperties.retrievePropertiesAsync([freeSpaceProperty]);
}).done(function (extraProperties) {
    var propValue = extraProperties[freeSpaceProperty];
    if (propValue !== null) {
        outputDiv.innerText = "Free Space: " + propValue;
}
}, function (error) {
    // Handle errors encountered while retrieving properties
});

Mozilla has introduced two simple methods to the DOM API for encrypting and decrypting base64 values. These are btoa, which converts binary (or string) data to a base64 ASCII-encoded string, and atob, which will do the opposite.  These APIs are being adopted by Internet Explorer 10 and are thus also available to Metro style apps written in JavaScript.

The basic functionality of these methods overlaps with the WinRT APIs found in the Windows.Security.Cryptography.CryptographicBuffer class, with the results being entirely interchangeable as you would expect. This means that base64-encrypted data created in one app using the DOM APIs can be passed to and successfully decrypted by an app using the WinRT APIs, and vice versa. This is shown in the code example below.

The difference between the two APIs thus rests in their structure and scope. As seen in the code example below, the btoa and atob methods are the simplest and most concise, but they work only with binary or basic string data, and cannot handle raw Unicode. As Mozilla’s btoa docs point out, Unicode strings will cause an exception in both methods and must be worked around with additional code. These methods are also focused solely on base64.

The WinRT APIs, on the other hand, are a little more complicated for basic usage but are much more flexible overall. For one, they handle Unicode strings just fine, with support for UTF-8, UTF-16LE, and UTF-16BE. Second, these APIs work with an intermediary buffer that can be created from a string, a byte array, or filled with random data. Finally, such buffers can then be encoded to base64 or hexadecimal, or copied to a separate byte array.

In short, the two can be used interchangeably for basic base64 operations, but developers might find it more consistent to use WinRT for other kinds of encoding.

Code example

This example simply shows the equivalence of the APIs and their cross compatibility. Create a new JavaScript project using the Blank template and drop in the code below. When you run the app and press the Run Test button, you’ll see the original string, the base64 encryption, and the decrypted values, using WinRT exclusively, using HTML APIs exclusively, then intermixing the two. As you’ll see, the results are entirely as expected.

HTML (body of default.html)

<body>
     <h1>Encryption Comparison</h1>
     <button<span >id="btnRun">Run Test</button>
     <p>Input Text: <spanid="txtInput">A text string for encyption</span></p>
     <p>Encrypted String (WinRT): <spanid="txtEncryptedWinRT"></span></p>
     <p>Decrypted String (WinRT): <spanid="txtDecryptedWinRT"></span></p>
     <p>Encrypted String (btoa): <spanid="txtEncryptedJS"></span></p>
     <p>Decrypted String (atob): <spanid="txtDecryptedJS"></span></p>
     <p>Decrypted String (WinRT using btoa output): <spanid="txtDecryptedCross1"></span></p>
     <p>Decrypted String (atob using WinRT output): <spanid="txtDecryptedCross2"></span></p>
</body>

 

JavaScript (entire contents of default.js)

(function () {
    "use strict";
    var app = WinJS.Application;
    app.onactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            WinJS.UI.processAll();
            var btn = btnRun;
            btnRun.addEventListener("click", runTest);
        }
    }


    function runTest() {
        var wsc = Windows.Security.Cryptography;
        var input = document.getElementById("txtInput").innerText;
        var buffer1a = wsc.CryptographicBuffer.convertStringToBinary(input,
        wsc.BinaryStringEncoding.utf8);
        var encrypt1 = wsc.CryptographicBuffer.encodeToBase64String(buffer1a);
        document.getElementById("txtEncryptedWinRT").innerText = encrypt1;
        var buffer1b = wsc.CryptographicBuffer.decodeFromBase64String(encrypt1);
        document.getElementById("txtDecryptedWinRT").innerText =
        wsc.CryptographicBuffer.convertBinaryToString(wsc.BinaryStringEncoding.utf8, buffer1b);
        var encrypt2 = btoa(input);
        document.getElementById("txtEncryptedJS").innerText = encrypt2.toString();
        document.getElementById("txtDecryptedJS").innerText = atob(encrypt2);
        document.getElementById("txtDecryptedCross1").innerText = wsc.CryptographicBuffer.convertBinaryToString(wsc.BinaryStringEncoding.utf8,
        wsc.CryptographicBuffer.decodeFromBase64String(encrypt2));
        document.getElementById("txtDecryptedCross2").innerText = atob(encrypt1);
    }


    app.start();
})();

 


New projects created from Visual Studio templates contain default tile, splash screen, and store logo images that just contain an X in a box. These are designed to be so ugly that you feel utterly compelled to replace them.

Unfortunately, some developers forget to do this. Until recently, these weren’t actually checked by the Store certification process, thus we see some apps in the Windows Store that still contain the default Store logo:

The particular challenge with the Store logo (that’s referenced on the manifest editor’s Packaging tab and not the Application UI tab) is that you never see that graphic in the running app. It appears only in the Store after you’re onboarded the app, which is why we see some of them make it into the Store.

Fortunately, the Store certification process (and a version of the Windows App Certification Kit from November 2012 or later), will fail you if you’re still using the default images.

Save yourself the trouble, then, by making sure to double-check your square tile, wide tile, splash screen, and store logo graphics before uploading to the Store.

While you’re at it, be sure to give your app a more interesting background color than the default gray. Such things are so simple to change and make a huge difference in your Store presence.


A while back one of my associates asked for an “ideal spec” for a Windows 8 developer on behalf of a partner who was looking to hire such a person. I won’t presume to have the ‘ideal,’ but here is a list that you might find helpful in your own recruiting efforts:

It would be best, of course, to find a developer with experience in one or more of the language/presentation layer choices for building apps: HTML/CSS/JS, C#(VB)/XAML, C++/XAML, and C++/DirectX. Experience in more than one is a big plus because of the platform’s support for writing mixed-language apps via WinRT components. And of these, DirectX experience is more specific to doing graphics apps vs. those with layout and data.

Other attractive qualifications:

  • Understands how to work with web services and web-based databases.
  • Strong testing skills and understanding of testing methodology. This will make a huge difference in delivering a top-quality app; those apps produced by developers who’ve never had to test much at all (e.g. many web-only developers) tend to have more bugs and fail Store certification more often.
  • Experience with Visual Studio a plus, as this reduces learning curve and helps productivity, though the tools can be learned, of course.
  • Experience in measuring and improving performance a plus, as again this will help produce a top-quality app, especially with web services.
  • Ability to learn and understand a platform, not just an app’s internals, which helps in understanding how to integrate all the platform features of Windows 8 into an app
  • Understands caching strategies for producing a mobile app that can operate with or without connectivity.
  • Respects the role of designers and enjoys working with them and maintaining a strong relationship–this will happen!
  • Experience with Windows Azure, Azure Mobile Services, and/or Windows Notification Service (WNS) a plus, especially for working with live tiles and notifications.
  • Familiarity with authentication, e.g. OAuth.
  • Mobile dev experience in general is a good thing.