As I'll be off for the holidays and not blogging until January, I thought to wrap up this year with this quickstart guide. I put together it together earlier this year for some of the business development guys at Microsoft who were helping other devs get started.

Getting Started Developing for Windows 8.1

A Cheat Sheet for Ramping Up Quickly

Getting started developing for Windows very much depends on the type of app being developed and the choice of language/presentation layer. The following information provides developers and designers with a foundation for finding the right path to explore the rich library of content available from Microsoft, including the best places to start your research.

Documentation

1.       Begin with Start Here which is a presentation-style walkthrough with the most essential links you need.

a.       The first page, Start, gets you the tools.

b.      The second page, Explore, highlights the language options and gives essential links to those starting tutorials. The key here is that you need to choose a language, and the basic guidance is “use what you know”. If you know more than one option, then you probably have a good sense of what is better for the app you want to build. If there are questions, we recommend consult with your Microsoft contacts on specific details that might make a difference in the choice:

                                                              i.      JavaScript with HTML:Create your first Windows Store app using JavaScript

                                                             ii.      C# or Visual Basic with XAML: Create your first Windows Store app using C# or Visual Basic

                                                            iii.      C++ with XAML: Create your first Windows Store app using C++

                                                            iv.      C++ with DirectX: Create your first Windows Store app using DirectX

c.       The third page, Design, points to planning and design guidance.

                                                               i.      Defining Vision is a good topic to think about what you’re trying to accomplish with an app. It has a number of sub-topics that go deeper into various areas.

                                                             ii.      Designers in particular need to start withDesigning UX for Apps as that contains the guidance around that aspect.

d.      The fourth page, Develop, gives the key on-ramping links to feature-specific tutorials. Many of these are also linked from the Learn to build Windows Store apps, which is the top-level table of contents for many areas of detail. This page is something you really just look at to know what’s all there—takes only a minute.

e.      The fifth page, Sell your app, is about the Store.

2.       I also recommend Chapter 1 of Programming Windows Store Apps in HTML, CSS, and JavaScript (a free ebook from Microsoft Press). This is an introduction to the platform from the viewpoint of an app, most of which is language-neutral.

a.       Alongside this, the topics under Windows Store app fundamentals will go a little deeper into each key platform area, like capabilities, contracts, app lifecycle, packaging, and app data.

b.      Two videos called “Beyond Just Beautiful” (Part 1 and Part 2) help raise awareness of non-so-obvious fundamentals of apps. (I made these for Windows 8; they are mostly applicable for 8.1 except that the slide on view states applies now to variable view sizing.)

c.       Note also that the above eBook, though directed toward HTML/CSS/JavaScript apps, is also very helpful to developers working in other languages as approximately 50% of the book is focused on the Windows Runtime APIs and other language-neutral aspects of the platform.

3.       There is also another set of tutorial series based on language choice:

a.       Developing apps (JavaScript and HTML5)–for this we also suggest Chapter 2: QuickStart of Programming Windows Store Apps in HTML, CSS, and JavaScript.

b.      Developing apps (C#/VB/C++ and XAML)

c.       Developing apps (C++ and DirectX)

4.      For some specific scenarios, see the list on In-depth guidance, which includes topics on games, reader apps, banking apps, the Hilo app, getting started for iOS developers, and migrating web or phone apps.

 

Samples

Learning to utilize the extensive samples in the Windows SDK, which cover 95% of the Windows Runtime APIs, is one of the great secrets of rapid app development. We recommend spending a day or so just getting familiar with the samples. Developers who do so will realize a high return on that invested time, as many bits of code that one needs in an app is already written in these samples.

The samples start on http://code.msdn.microsoft.com/windowsapps. The best thing to do is to download the whole kit and caboodle in your chosen language from http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples. Download the “full” package with all the languages so you just have everything. With this you can then:

·         Search in the sample tree for any API you’re interested in (make sure you have Windows index them).

·         The tutorials listed earlier often make reference to these samples, so you’ll already have them when you work through that material.

·         It’s instructive to just spend about 15-30 minutes browsing the folder after you’ve downloaded and unzipped the samples package. The folder names for each sample are very descriptive and will give you a great sense of what’s available (better yet, spend a day doing this, as noted above).

·         The aforementioned ebook, Programming Windows Store Apps in HTML, CSS, and JavaScript, links to every one of the JavaScript samples, and in the process also provides contextual links to the C#/VB and C++ variants of those same samples. The WinRT-related sections of the book, in other words, serve as a contextual index into the samples.

 

When you’re on the samples page, doing a search with feature keywords does a very good job at picking up the right samples. For example, if you want secondary tiles, searching on that term will give you the exact sample you need at the top of the list.

Also, with any given sample, it’s worth spending 5-10 minutes running the sample in VS and trying out all the different scenarios. Almost every sample has a choice of specific scenarios that are demonstrated, and provide descriptive text of what’s going on. They are a fabulous resource.


Another migration issue that I ran into with Windows 8.1 came out when changing the Windows 8 snapped view for the Here My Am! app in my book to variable view sizing. In particular, when I sized the view down to a width below 500px, I noticed that the fonts for h1, h2, and h3 elements no longer adjusted automatically with Windows 8.1/WinJS 2.0.

The reason for this is that the following block of CSS that is present in the WinJS 1.0 ui-dark.css/ui-light.css stylesheets was removed for WinJS 2.0:

@media screen and (-ms-view-state: snapped) { 
    h1, .win-type-xx-large {
        font-size:2 0pt;
        font-weight: 200;
        line-height: 1.2;
    }

    h2, .win-type-x-large {
        font-size: 11pt;
        font-weight: 600;
        line-height: 1.3636;
    }

    h3, .win-type-x-large {
        font-size: 11pt;
        font-weight: 400;
        line-height: 1.3636;
    }

    h1.win-type-ellipsis, .win-type-xx-large.win-type-ellipsis {
        line-height: 1.5;
    }

    h2.win-type-ellipsis, .win-type-x-large.win-type-ellipsis {
        line-height: 1.3636;
    }
}

Technically speaking, the WinJS told me that this was not a breaking change, per se, because the media query for -ms-view-state: snapped no longer fires at all in Windows 8.1, so that chunk of CSS wasn't be used. This is why it was deemed dead code and removed altogether. Personally, I didn't understand why they didn't change the media query to detect a similar view, but it's easy enough to rectify manually. Just copy these styles into your own CSS and place them inside a media query for < 500px narrow views, if you support them. That is, replace the @media in the code above with this:

@media screen and (orientation: portrait) and (max-width: 499px)

 

 


When I migrated one of my apps to Windows 8.1, I found that some code I had attached to the body.onload event wasn’t getting called. Windows.UI.WebUI.WebUIApplication.onactivated is the last thing that gets fired from the app host on startup (barring WinJS.Application.onready which is just queued after that but not related to a DOM event).

It turns out that there was a breaking change between Windows 8/WinJS 1.0 and Windows 8.1/WinJS2.0, which changed the exact sequence of the Windows and WinJS events (a sequence which was never specified nor guaranteed in the first place).

Note first that document.body.onload generally won’t work—one should use window.onload instead.

In WinJS 1.0, window.onload fires after WinJS.Application.onactivated. In WinJS 2.0 it fires before all the WinJS.Application events (including loaded, activated, and ready). My Win8 code was adding a window.onload handler within WinJS.Application.onactivatedt seeing it any longer. So I simply needed to move the addEventListener call earlier in the code and everything worked, but it took me a while to figure it out the cause.

 


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.


In Windows 8 and WinJS 1.0 it was exceedingly difficult (though not impossible) to create a custom layout object for the WinJS ListView control. As such it was one area of WinJS that I never investigated!

What made it difficult was that the ListView worked entirely on absolute CSS positioning, which meant that the location of every item had to be individually calculated within the layout object’s code. This also caused various performance issues as well.

For WinJS 2.0 on Windows 8.1, the WinJS team rewrote the layout engine of the ListView to leverage relative positioning such that it could let the app host’s layout engine do most of the work. This both improved performance and made it orders of magnitude more easy to write a custom layout. In fact, the simplest layout object hardly needs to do anything at all, because the default behavior (via flexbox with block elements) produces a simple vertical layout just like you get when throwing a bunch of div’s into an HTML page.

From there you can start to build out other behaviors you want:

  • Non-vertical layouts
  • Virtualization support
  • Keyboard support
  • Drag and drop general visual indicators
  • Drag and drop reordering and positional indicators
  • Animations

To explore all the details, I have 17 pages in Appendix B, “WinJS Extras” in my free ebook’s second edition (preview), which includes a minimal vertical layout, a minimal horizontal layout, two dimensional layouts, and non-linear layouts. For the latter I borrowed some code from Mike Mastrangelo of the WinJS team that was used in a short demo at //build 2013. The appendix also includes a short video demonstration of this.

B-3 (circle layout)


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.

 

 


It came to our attention recently through this forum post that there is a small bug in the Repeater control of WinJS 2.0 (Windows 8.1). I wanted to summarize my response to that post here.

The bug occurs when you change either the template or data property of the repeater and results in an enigmatic “NotFoundError” deep down inside the ui.js file of WinJS. It specifically occurs when the repeater’s template is set to a separately-declared WinJS.Binding.Template control. What happens is that when you change either template or data property of the control, it disposes its prior contents before rendering the new, but ends up trying to remove the same child node twice (hence the error).

Fortunately there are three ways to work around the bug:

  1. Instead of using a separately-declared template, place the template directly inline as the child of the repeater element.
  2. For a separately-declared template, use data-win-options=”{ extractChild: ‘true’ }” on the same element as data-win-control=”WinJS.Binding.Template”.
  3. Recreate the Repeater control whenever you change the template or data source (which is a more expensive operation of course).

See the original forum post for applicable code snippets.

[Correction: #2 above originally had WinJS.UI.Repeater, which should be WinJS.Binding.Template as modified.]