February 2013

Volume 28 Number 02

Modern Apps - Create Windows Store Apps with HTML5 and JavaScript

By Rachel Appel | February 2013

Rachel AppelNot only has Bill Gates’ dream of a computer on every desk and in every home come to fruition, but the advent of devices such as the Surface tablet has taken his dream even further. In addition to the Surface, there has been an explosion of new consumer-­oriented devices in every form factor possible. In other words, computers are everywhere.

Consider that on those computers are more than 1 billion existing Windows installations worldwide, with 300 million Windows 7 licenses sold each year in the previous two years. Combine the current, upgradable Windows installation base with the rapidly growing market of Windows 8 devices such as the Surface and you have the formula for monetization success. This is Windows reimagined—the unparalleled opportunity for you to make money by publishing apps in the Windows Store.

The Platform, Language and Toolset for Creating Windows Store Apps

In order to create a Windows Store app, you need Windows 8, Visual Studio 2012 and any SDKs specific to the requirements of your app, such as the Windows Live SDK or Bing Maps SDK. This minimal system setup and configuration makes app development on Windows 8 easy, from installation to deployment.

Once you’ve installed the requisite software, it’s time to move onto choosing a language. If your development background lies in the Microsoft stack as a Microsoft .NET Framework developer writing Windows Forms, Windows Presentation Foundation (WPF) or Silverlight apps with C# or Visual Basic, then creating Windows Store apps with XAML and C# or Visual Basic is the path of least resistance. C++ developers can also use C++ as the compiled language with XAML as its GUI companion.

If you’re a Web developer—including ASP.NET—you can apply your existing knowledge of open standard HTML5, JavaScript and CSS3 directly to Windows Store app development. Web developers may continue to use many popular third-party JavaScript libraries such as jQuery or Knockout. For this article, I’ll use JavaScript as the language of choice.

No matter where your development background lies, the barrier to entry is low when developing native Windows 8 apps. This is because the Windows Runtime (WinRT) is a platform that contains APIs that sit on top of the Windows core services, as illustrated in Figure 1.

Architecture of Windows Store Apps
Figure 1 Architecture of Windows Store Apps

The WinRT APIs give you access to everything Windows 8 has to offer, including APIs for hardware such as built-in webcams, geolocation, light sensors and accelerometers. Of course, platform fundamentals such as memory management, authentication, globalization and asynchronous processing—as well as Windows Store app features such as search, share and communications—are also readily available. There are even APIs for manipulating audio and video; however, if you’re writing JavaScript apps, HTML5 <audio> and <video> elements work great. You can browse the complete API on the “API reference for Windows Store apps” page at bit.ly/ZCwcJE.

Tenets of a Windows Store App

Windows Store apps run as fully immersive, full-screen experiences that deliver streamlined content to the user, without the app or its commands getting in the way of the user. Windows Store apps offer a clean, straightforward visualization of data that draws the user’s attention to the content.

Windows Store apps do things traditional Windows or Web apps couldn’t do before, such as sharing, searching and communicating with each other in an easy and unified way, using elements of the Windows Runtime called contracts as liaisons between apps.

Great UX is a key facet of Windows Store app development, from presentation and layout to navigation and app performance. Users expect consistency between apps and between apps and the OS. Windows Store apps are all about UX, and employing design principles—such as using a consistent font, the Windows UI silhouette and a scalable grid system—enhance the user’s comfort level when using your app. This consistency is carried throughout both apps and Windows 8 itself.

Ensuring both touch and mouse input work reliably and consistently is important because users now have more ways to interact with their computing devices in the form of mice, pens, touch, cameras and sensors.

Because battery-powered devices with processors such as ARM are becoming a major part of the computing landscape, Windows 8 must manage the overall and per-app memory in a strict fashion to enable a fast and fluid experience even when resources are low. Windows 8 apps enjoy a straightforward and simple process lifecycle to ensure the best experience.

While many apps will work nicely as a Windows Store app, not every app is a good candidate. For example, while Visual Studio itself embraces many modern UI design principles, its purpose is to allow the user to execute commands (in other words, programming). That’s not a good fit for a Windows Store app.

Visual Studio 2012 Windows Store App Project Templates

Visual Studio 2012 introduced a set of new templates for Windows Store app development in C#, Visual Basic, C++ and JavaScript. Regardless of language, the following template styles are available:

  • Blank: A bare-bones template with the minimum files required to build a Windows Store app.
  • Grid: A template that displays a grid that uses the Windows 8 UI silhouette along with template code for several features, including navigation and snapped-view support (more on this later). 
  • Split: A template that displays a list of items and item details in a two-column view, making it easy for the user to switch quickly among the items.
  • Fixed: A Blank template that uses a ViewBox object in the default.html page. A ViewBox is a WinRT object used in games.
  • Navigation: A template with a Blank project structure plus navigation and a set of basic app assets (that is, home.html, home.js and home.css) under the /home directory.

Because the Grid template contains code that touts many great Windows 8 features such as support for snapped view, screen scaling and navigation, it’s the perfect way to get started writing Windows Store apps.

After you create a new JavaScript Grid project template, examining its structure reveals a project full of standard Web file types—such as .html, .css and .js files—organized in folders under the project’s root. You can then debug and run a Windows Store app by pressing F5 or selecting Start Debugging from the Debug menu.

In the Windows Store app templates, default.html is the starting page for a Windows Store app and has a companion script file, /js/default.js, which contains basic process lifecycle management code. As with any other HTML file, default.html has code you might expect, including script references and new HTML5 semantic markup that defines the page structure. The following code fragment lives inside the default.html <body> tag and uses WinJS controls for navigation and to load the groupedItems.html page:

<div id="contenthost"
  data-win-control="Application.PageControlNavigator"
  data-win-options=
  "{home: '/pages/groupedItems/groupedItems.html'}"></div>

The data-* attributes are the HTML5 way to apply custom code or behavior to an HTML element, and in Windows Store app development, data-win-* attributes usually refer to Windows JavaScript controls. Windows JavaScript controls are built-in WinRT components that you apply to HTML elements to enhance or modify their behavior or style. Data-win-* attributes are prevalent in Windows Store JavaScript apps, especially when data binding.

Data Access in Windows Store Apps

As part of the Grid template, a file named data.js in the /js folder contains code that builds a data set of arrays as well as functions for grouping and manipulating the data. The data.js file also contains sample data that you should replace with your own. In this article, I’ll use data for a countdown app that shows the number of days remaining until an event such as a holiday or vacation.

In the data.js file you can find the only // TODO comment near the beginning of the file. Replace the code under the comment with your own, so the code looks something like the following code snippet, which makes an XMLHttpRequest call to retrieve JSON data, then also creates the data set, including dynamic properties such as the daysToGo and message fields:

var list = new WinJS.Binding.List();
...
WinJS.xhr({ url: "data.json" }).then(function (xhr) {
  var items = JSON.parse(xhr.responseText);          
  items.forEach(function (item) {
    item.daysToGo = Math.floor(
      (Date.parse(item.eventDate) - new Date()) / 86400000);
    item.message = item.daysToGo + " days until " + item.title;
    if (item.daysToGo >= 0) {
      list.push(item);
    };
  })
})

In the beginning of data.js is a line of code that instantiates a WinJS.Binding.List object aptly named list, and the preceding code pushes individual items onto this List.

The List object enables binding between JSON data or JavaScript arrays and HTML elements. Once the list variable is populated with data, use binding expressions in HTML markup to bind the List members to HTML elements.

When you read JSON data with a call to JSON.parse, the names in name/value pairs match properties of JavaScript objects at run time. The following JSON data shows how the JSON structure maps to members of the items variable in the preceding code snippet. The key, title, eventDate, image, color and group fields all map to the item object’s properties:

[{"key":"1","group":{"key":"group1","title":"Important Dates"},
"title":"Rachel's Birthday","eventDate":"01/13/2013",
"image":"/images/birthday.png","color":"#6666FF"},
{"key":"2","group":{"key":"group1","title":"Important Dates"},
"title":"Ada Lovelace Day","eventDate":"10/16/2013",
"image":"/images/ada.jpg","color":"#fff"},
{"key":"3","group":{"key":"group2","title":"Holidays"},"title":"Christmas",
"eventDate":"12/25/2013","image":"/­images/­tree.png","color":"#ef0d0d"},
{"key":"4","group":{"key":"group3","title":"School"},"title":"School Ends","eventDate":"6/10/2013","image":"/images/schoolbus.png","color":"#fff"},
{"key":"5","group":{"key":"group2","title":"Holidays"},"title":"Thanksgiving",
"eventDate":"11/29/2012","image":"/­images/­thanksgiving.png","color":"#FFCC00"},
{"key":"6","group":{"key":"group2","title":"Holidays"},"title":"New Year's Day", "eventDate":"1/1/2013","image":"/images/celebrate.png","color":"#f8baba"}]

Now that you’ve loaded the data, you need to ensure the List object is bound to the correct HTML elements. Modifications to the /pages/groupedItems/groupedItems.html page in Figure 2 shows data binding in action.

Figure 2 Data Binding the List Object to HTML Elements with WinJS Controls

<!-- These templates are used to display each
  item in the ListView declared below. -->
<div class="headertemplate" data-win-control="WinJS.Binding.Template">
  <button class="group-header win-type-x-large win-type-interactive"
    data-win-bind="groupKey: key"
    onclick="Application.navigator.pageControl.navigateToGroup(
      event.srcElement.groupKey)"
      role="link" tabindex="-1" type="button">
    <span class="group-title win-type-ellipsis"
      data-win-bind="textContent: title"></span>
    <span class="group-chevron"></span>
  </button>
</div>
<div class="itemtemplate" data-win-control="WinJS.Binding.Template" >
  <div id="myitem" class="item"
    data-win-bind="style.background: color">
    <img class="item-image" src="#"
      data-win-bind="src: image; alt: title" />
    <div class="item-overlay">
    <h2 class="item-title" data-win-bind="innerText: message"></h2>
      <h6 class="item-subtitle"
        data-win-bind="textContent: eventDate"></h6>
    </div>
  </div>
</div>
<!-- The content that will be loaded and displayed. -->
<div class="fragment groupeditemspage">
  <header aria-label="Header content" role="banner">
    <button class="win-backbutton" aria-label="Back"
       disabled type="button"></button>
    <h1 class="titlearea win-type-ellipsis">
      <span class="pagetitle">How long until...</span>
    </h1>
  </header>
    <section aria-label="Main content" role="main">
      <div id="listView" class="groupeditemslist"
        aria-label="List of groups"
        data-win-control="WinJS.UI.ListView"
        data-win-options="{  selectionMode: 'multi',
        tapBehavior:'toggleSelect' }"></div>
    </section>
</div>

Each HTML element in Figure 2 that contains a data-win-bind attribute has a binding expression that matches a property name of the item variable from the preceding code snippet, so all you need to do is make sure that the binding expressions match the names of the fields. Don’t forget to ensure that you also modify the binding expressions in the groupedDetail.html and itemDetails.html pages so correct data will show when a user navigates to them.

Running the project in the Windows Simulator yields results similar to that in Figure 3. (You can learn more about using the simulator at bit.ly/M1nWOY.)

Replace the Sample Data to Make a Basic App
Figure 3 Replace the Sample Data to Make a Basic App

As you can see, you can simply replace the code from the Visual Studio template for quick data access. However, projects are often quite large or complex, making maintenance difficult. If this is the case, then use the Model-View-ViewModel (MVVM) pattern to make maintenance easier. This pattern is extremely well-documented on the Web.

While your app now works, it’s time take advantage of the many great Windows 8 features that can make your app stand out in the crowd.

Branding Your Windows Store App

Considering that the focal point of Windows 8 is the Start page, it makes sense to start branding there. The Start page is filled with live tiles, and they aren’t just a bunch of square icons, either. Instead, they’re the best way to show off and attract users to your app. Live tiles are called “live” for a reason, and that’s because you can dynamically display information and images in them, making your app even more attractive.

Windows Store apps require three separate tile images with the following pixel dimensions:

  • Logo: 150 x 150 (standard tile)
  • Wide Logo: 150 x 310 (wide tile)
  • Small Logo: 30 x 30 (this shows only in app lists in the store)

The images can be any popular image format, and those with transparent backgrounds work best. Opening the package.appxmanifest file from the project’s root reveals the configuration palette, where you can select the tile images and set the background colors. Figure 4 illustrates both a standard and wide tile.

Countdown App Standard and Wide Tiles
Figure 4 Countdown App Standard and Wide Tiles

When you’re setting up the tiles is a good time to configure the splash screen by selecting just an image and background color—no code is used. Although tiles and splash screens are important factors in branding your app, you can do many more things to brand and polish your app, which you can read about at bit.ly/M4HYmL.

Windows 8 ‘Must-Have’ Features for Your App

While your app might work at this point, there are many new features and APIs in the Windows 8 app ecosystem that you can tap into to really make your app stand out. I’ll briefly discuss each.

AppBar An essential feature for every app is the AppBar, which is a WinJS control found in default.html. Normally, the AppBar stays out of sight, but when users right-click or swipe from the top or bottom of the screen, the AppBar displays as a bar across the bottom of the screen. Figure 5 shows the markup for an AppBar containing three buttons as well as their corresponding event listeners.

Figure 5 An AppBar with Buttons for Adding, Deleting and Exporting Data

// AppBar markup in default.html
<div id="appbar" data-win-control="WinJS.UI.AppBar">
  <button data-win-control="WinJS.UI.AppBarCommand"
    data-win-options="{id:'addItem', label:'Add',
    icon:'add', section:'global'}" type="button"></button>
  <button data-win-control="WinJS.UI.AppBarCommand"
    data-win-options="{id:'exportData', label:'Save',
    icon:'save', section:'global'}" type="button"></button>
  <button data-win-control="WinJS.UI.AppBarCommand"
    data-win-options="{id:'deleteItem', label:'Delete',
    icon:'delete', section:'selection'}" type="button"></button>
</div>
// Script in groupedItems.js
document.getElementById("exportData").addEventListener("click", Data.exportData);
document.getElementById("addItem").addEventListener("click", this.addItem);
document.getElementById("deleteItem").addEventListener("click", this.deleteItem);

Global AppBar commands should be located on the right side of the AppBar, while contextual commands should go on the left. Style the AppBar with CSS, as it’s only a <div>.

Snapped View Windows Store apps can run in full screen or a mode called snapped view that happens when the user “sticks” the app to the left or right side of the screen. Because the app now has less screen real estate, your app should display only necessary data.

Because snapped-view support is built into the Grid template, you need to verify that the data displays nicely while snapped, showing pertinent and readable information. The AppBar also works while the app is snapped, so that also might need style adjustments.

Semantic Zoom This new touch-friendly feature of Windows 8 is a way to aggregate large amounts of data in a single, easy-to-digest view. Users invoke Semantic Zoom in the following ways:

  • Touch: Pinch gesture
  • Mouse: Ctrl+Scroll Wheel
  • Keyboard: Ctrl - and Ctrl +

Semantic Zoom is more about visualizing data in a meaningful way that assists with navigation than simply exposing a zoomed view of it. If there’s a lot of data, it’s better for the user to have a bird’s-eye view rather than having to scroll through an overload of information. Consider how to best present the data so it’s the most meaningful.

Search and Share Searching and sharing data between apps are core aspects of modern apps. Users can now search across multiple apps at one time and then share the data they find. Or your app can register itself as a share target and accept data that users share from other Windows Store apps. Never before has app-to-app communication been so straightforward and consistent.

Picker Controls These are traditional Windows controls that have been updated for a modern UI—such as the File Open Picker or File Save Picker—or print settings dialogs that have been staples of Windows apps for many versions.

Media Because Windows Store apps built with JavaScript fully support HTML5, the <audio> and <video> elements work the same way as they do in ordinary Web pages. 

Toast Notifications Toast notifications are a way to provide a momentary message to the user, regardless of whether the app is in use or not. The most popular forms of toast notifications are e-mail alert pop-ups and text messages on phones. Toast messages can contain text and images and can serve as another way to attract users to your app. You can post the same notifications to the Windows 8 lock screen for a quick glimpse of any waiting messages.

Generation App

To recap, Windows 8 is Windows reimagined, sporting some of the biggest changes in the OS since Windows 95, in an unprecedented market. The built-in Visual Studio project templates enable you to get started publishing moneymaking apps easier and faster than ever in the largest market for app creators.

There’s not enough space here to discuss all of the awesome features you could and should use in your Windows Store app, so I highly recommend that you check out the Generation App program (bit.ly/W8GenAppDev). It guides you through the process of building a Windows Store (or Windows Phone) app in 30 days, offering free technical and design consultations and assistance along with exclusive tips and resources.

Rachel Appel is a developer evangelist at Microsoft New York City. Reach her via her Web site at rachelappel.com or by e-mail at rachel.appel@microsoft.com. You can also follow her latest updates on Twitter at twitter.com/rachelappel.

Thanks to the following technical expert for reviewing this article: Ian LeGrow