While working on the Devices and Printing chapter of the second edition of Programming Windows Store Apps with HTML, CSS, and JavaScript, I’ve been bitten several times by a subtly confusing feature of the device enumeration API and it’s projection into JavaScript.

Device enumeration happens in a few different ways, but a common method is to ask a device object like HidDevice or Bluetooth.RfcommDeviceService (both under the Windows.Devices namespace) for a “selector” string through a static method called getDeviceSelector. You then pass this to the Windows.Devices.Enumeration.DeviceInformation.findAllAsync.

The gotcha is that findAllAsync has two overloads that take one argument: one that takes a selector string, and one that takes a DeviceClass object. Only one of these, however, is projected into JavaScript and it’s the DeviceClass variant. Unfortunately, if you happen to pass a selector string to this method, you’ll get no complaint anywhere along the way: the API will accept the string, see that it’s an invalid DeviceClass, and then ignore it.

As a result, this variant of findAllAsync just assumes then that you didn’t need the argument and does the equivalent of findAllAsync() with no arguments, which enumerates every device on your system (all 300+ of them, typically!). This is, like I said, very confusing if you were only expecting to see a single result.

When using a selector to enumerate devices in JavaScript, then, be sure to call the findAllAsync(<selector>, <properties>) variant, passing null for <properties>. This ensures that you use the findAllAsync that expects a selector string, and thus you’ll get the results you’re looking for.

 

 


As of last week I assumed management and content development for the Windows App Builder’s Blog, which I’m sure most of you follow already.

What I’d love to hear from you is this: what content would you like to see on the blog? What questions are you dying to have answered? What ‘inside stories’ from the Windows engineering team would you like to know? Let me know in the comments!


Question: What data type does one use to pass a JavaScript Error object to a WinRT component?

Answer: None, actually. You cannot directly pass an Error object to native code in a component, as that object type won’t be meaningful in C++. You could stringify the Error and pass it as JSON, but that’s something of a pain.

What you can do instead is to source an exception in C++ (or C#), where those exceptions have known HRESULTs, because then you’ll get the appropriate errors in JavaScript thanks to the projection layer. It does take a little extra time (very small) to marshal this exception across the layer boundaries, but would only matter if you end up throwing millions of exceptions per second. (I hope that’s not the case!)

Here’s a C++ example to generate an Access Denied (E_ACCESSDENIED) that’s usable across the component boundary:

class ErrorHelper
{
public:
static void ThrowAccessDenied();
}

ErrorHelper::ThrowAccessDenied()
{
throw ref new Platform::AccessDeniedException();
}

And clearly you can extend ErrorHelper to include other methods for additional errors you need to use.

Thanks to Rob Paveza for this solution.

 


When working with the Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList, it’s important to know that it has a 1000 file limit. This has presented a challenge to some developers working with libraries that contain many more files than that, when they try to save every file in the library in this list. Of course, the problem is solved easily by saving the parent StorageFolder in the list instead, which will then include all those files. Sometimes, however, you might want to save a handful of files directly for performance reasons–files that you know you’re going to want, so you don’t have to go through the folders each time.

I’ll mention in this context that I’ve seen discussions about this sort of thing where developers talk about file paths and so forth. When working with files and folders in WinRT, always remember that the StorageFile and StorageFolder objects (and their shared StorageItem base class) are abstractions for path names and should be what you use whenever you think about path names. The key reason for this is that file-like entities can be backed by non-local providers such that the concept of a “pathname’ doesn’t even exist. The StorageFile/Folder/Item abstractions let the provider worry about the mapping details. For the consuming app, then, you use the FutureAccessList to do the equivalent of saving pathname strings in some other local storage. (The same goes for the recently used list that exists alongside FutureAccessList.)

Equally interesting is the question of what happens if files are moved on the file system between when you save a StorageFile to the FutureAccessList and when you later retrieve it. Generally speaking, Windows does its best to track changes to the file system and update the FutureAccessList accordingly, so the bottom line is that you should not worry about it. Of course, if you attempt to open a file obtained from the FutureAccessList, it can fail for any number of reasons, including the file having been moved without the system being able to track it. You have to handle all such exceptions anyway, so an orphaned file is just one in the mix.

 


Question: Is it possible to change the length of time a toast is displayed different from the ~7 second default?

Answer: Not programmatically. Toast display time is user-controlled via PC Settings > Ease of Access > Other Options > “Show notifications for” (for Windows 8.1; leave out Other Options on Windows 8). It’s one place where the user is in control, because different users respond at widely different speeds. You cannot assume that 2 seconds, for example, is long enough. A user might have difficulty reading, for example, or might have difficulty placing a mouse cursor or touching the screen fast enough to respond to the toast (think of a paralyzed user who is tapping keys with a mouth rod).

The shortest it can be set is 5 seconds, the longest 5 minutes. If you have some UX requirement that requires a shorter time (e.g. you’re trying to display short transient messages within a running app), then you should think about a different mechanism such as one using in-app flyouts.


The question occasionally comes up about the exact specifications for the built-in Windows animations that express the Windows look and feel. Often this is because someone wants to replicate the effect outside of Windows, such as on a website, or within a webview element where WinJS isn’t accessible.

Fortunately, it’s quite simple to see the implementation of the animations directly in the WinJS source code. All the animations stuff is right near the top of the ui.js file, with the WinJS.UI.Animation namespace starting around like 530/540. You can also just search for the specific animation’s name, and you’ll find code like this (omitting comments):

fadeIn: function (shown) {
return thisWinUI.executeTransition(
shown,
{
property: “opacity”,
delay: 0,
duration: 250,
timing: “linear”,
from: 0,
to: 1
});
},

WinUI.executeTransition is a helper function that takes the property bag indicated here and creates the transition/animation. In this case it animates the opacity property from 0 to 1 with no delay over 250ms using linear timing. And this is exactly the “spec” for the system-wide Windows fade-in effect, which is also expressed in the XAML animations and so forth.

It’s worth mentioning too that an app can also retrieve these characteristics–called animation metrics–through the Windows.UI.Core.AnimationMetrics API in WinRT (refer also to the Animation metrics sample.) This API exists primarily for DirectX apps written in C++ that don’t have a built-in animation library to draw from and therefore must replicate the behaviors at runtime. But you can use the metrics from any language to do the same if needed.


The title of this post might make it sound fancier than it is. The question here is about loading up a custom image format without depending on some codec having been installed system-wide (which a Windows Store app can’t do anyway). It also answers the question about just getting to the bits of an image file generally.

The trick is to read the file contents into a buffer, and then read the bytes out of the buffer. For example, here’s a roundabout way to load a JPEG:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.fileTypeFilter.replaceAll([‘.jpg’, ‘.jpeg’]);

picker.pickSingleFileAsync().then(function (file) {
return Windows.Storage.FileIO.readBufferAsync(file);
}).done(function (buffer) {
var reader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
var bytes = new Uint8Array(buffer.length);
reader.readBytes(bytes);
var blob = new Blob([bytes], { type: ‘image/jpeg’ });

    var img = document.createElement(‘img’);
document.body.appendChild(img);
img.src = URL.createObjectURL(blob);
})

This is highly redundant for built-in formats, of course, because you can just take the StorageFile (in file) from pickSingleFileAsync and pass it direcly tro URL.createObjectURL at the last line of this snippet. (Better yet, if you don’t need the full image, use the StorageFile.getThumbnailAsync or getScaledImageAsThumbnailAsync to minimize overhead.)

For some other format that lacks built-in support, however, this snippet shows you how to load up the bits into the bytes variable, at which point you can do whatever you want with it. To display a custom image format, you’ll need to translate it into bits of a supported file type. If you converted bytes into an array of jpegBytes, then you could just pass the latter to new Blob and everything else is the same. (You could also write the jpegBytes to a new StorageFile and then display it like you would any other, if you want to preserve the conversion.)

Thanks to Luke Hoban for this snippet.


Question: Is there an easy way to detect when the Charms bar is opened (such as to pause a game at such times)?

Answer: Yes, you can use the HTML blur event for this purpose, as opening the Charms pane will take focus away from the app (and closing it will cause a focus event). What’s important here is that you listen to the window object’s blur event, rather than any other specific element. For example:

window.addEventListener(“blur”, handleEvent, false);

handleEvent gets called when you activate charms via touch (in the simulator at least) and keyboard. The one case that it doesn’t seem to work is when you pull the charms out with the mouse in the lower right. For this, listen for the body element’s mouseleave event and handle it the same way as blur (even using the same handler).

Note that blur is not fired when the app bar appears, as that’s still keeping focus on the same app window (it’s app UI, not system UI). For this you can use the app bar’s beforeshow/aftershowevent, or you can use the blur event on the body element.
Question: I want to automatically close the charms pane from within one of my settings flyouts. How can I do this?

Answer: It’s very simple, just call window.focus() to set the focus back to the app, which automatically dismisses the charms bar. Navigating to a page with WinJS.Navigation.navigate has the same effect (as it sets the focus in the process).


As a short follow-up to the previous series of posts, I wanted to share a bit on detecting where a view is on the screen. That is, a view can be placed anywhere on the screen, which could be on either edge or in the middle (which is demonstrated in the Getting Around tutorial video.) For any given view, the ApplicationView object for which you obtain with Windows.UI.ViewManagement.ApplicationView.getForCurrentView(), its adjacentToLeftDisplayEdge and adjacentToRightDisplayEdge properties tell you whether the view is placed along a screen edge. If, also, the view is full screen, the isFullScreen property will be true as will both adjacent* properties.

It follows, then, that !isFullScreen && !adjacentToLeftDisplayEdge && !adjacentToRightDisplayEdge means that a view is split and is centrally placed.

 

 


In Part 1 we learned about creating views, and in Part 2 saw the ProjectionManager API. Now we turn to the Windows.UI.ViewManagement.ApplicationViewSwitcher class, something that’s again demonstrated in the Multiple views sample in the SDK.

Those methods of that class—with some verbose names!—are:

  • switchAsync(id): (3 overloads) Switches to a given view in the same space as the calling one. If the target view is already visible elsewhere on the screen, however, this will simply change focus to that view. A value from ApplicationViewSwitchingOptions can be used to customize the transition: default (standard transition), skipAnimation (no transition), or consolidateViews (closes the calling view).
  • tryShowAsStandaloneAsync: (3 overloads) Shows the new view adjacent to the calling view, with options from ViewSizePreference to determine the desired state of the new and calling views: default, useLess, useHalf, useMore, useMinimum, useNone. You can experiment with these variations in scenario 1 of the sample.
  • disableShowingMainViewOnActivation: Prevents the primary view of the app from showing on subsequent activations, that is, when it’s appropriate to activate the app directly into a secondary view. Showing the primary view is always the default unless this method is called. This is shown in scenario 2 of the sample, with the actual call in js/default.js.
  • prepareForCustomAnimatedSwitchAsync: Tells the views whether to run default animations on a switch; by specifying the skipAnimation option, you can attach a completed handler to this promise to perform custom animations. See scenario 3 of the sample.

Because the details and variations of these APIs get rather complex, I’ll leave it to you to explore the sample directly. Note that in the main scenarios of the app you won’t find any calls to switchAsync—these are made in the secondary view (js/secondaryView.js) to switch back to the primary view. In each case the view closes itself as part of the switch, which isn’t a required behavior, of course.

To show the basic switching behavior, then, I’ve made a few small modifications to a copy of this sample in my second edition companion content. First, the button in the secondary view to switch back to the main view does not close the secondary one. Then I’ve added a button to scenario 1 of the main app to call switchAsync on the selected secondary view. You’ll see how it brings that view up in the same space as the original one, rather than alongside. If you switch back from the secondary view, the main view will appear in that space.

Things get interesting when you create an adjacent view first, then in the main app switch to a secondary view in the space. Then you’ll see two secondary views at once. If you switch to the main app in either, you’ll then find that the Switch to Main View button in the other secondary view just changes focus to the already-visible app. Otherwise you’d be seeing the main app view twice, which would be very confusing!

In summary, I hope that you’ll find some excellent scenarios in which to use multiple views. Given the newness of the feature, you have an opportunity right now for your app to really stand out if you’re an early adopter.