Tải bản đầy đủ (.pdf) (750 trang)

Programming Windows Store Apps with HTML CSS and JavaScript

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (16.45 MB, 750 trang )






























Programming/Windows
ISBN: 978-0-7356-7176-8


About the Author
Charles Petzold has been writing
about Windows programming
for 25 years. A Windows Pioneer
Award winner, Petzold is author
of the classic Programming Windows, the
widely acclaimed Code: The Hidden
Language of Computer Hardware and
Software, Programming Windows Phone 7,
and more than a dozen other books.
Writing Windows 8 Apps with C# and XAML
Like Windows itself, this classic book has been reimagined for
a new world of programming and user experiences. Guided
by developer legend Charles Petzold, Programming Windows,
Sixth Edition teaches how to use your existing C# skills with
XAML and the Windows Runtime to create full-screen, touch
apps for Windows 8.
Master the elementals
• Create and initialize objects with code or XAML
• Handle user-input events such as taps
• Manage and experiment with dynamic layout
• Visually redene a control’s appearance
• Create Windows Runtime libraries
• Use MVVM for data binding and commanding
• Work with asynchronous methods; write your own
• Animate transitions and create 2D and 3D effects
• Manage resolution, scaling, and navigation
Extend your skills and apps
• Handle pointer, manipulation, tap, and hold events
• Manipulate bitmaps and rich text

• Work with GPS and orientation sensors
• Call Win32
®
and DirectX
®
functions
• Enable share, search, and print
microsoft.com/mspress
U.S.A. $59.99
Canada $62.99
[Recommended]






























Get C# and C++ code samples
Ready to download at:
/>
About the Sixth Edition

Completely rewritten for Windows 8

Focuses on creating apps using C#,
XAML, and the Windows Runtime

Expertly teaches essential skills in Part 1:
Elementals

Rounds out your Windows 8 education
in Part 2: Specialties

Provides code samples in both C#
and C++
edition
Petzold

Programming
Windows
Writing Windows 8 Apps with C# and XAML
Sixth Edition
Programming Windows
Kraig Brockschmidt
Programming
Windows Store
Apps with HTML,
CSS, and JavaScript
Second Edition
Professional
SECOND
PREVIEW
spine = 2.07”




SECOND PREVIEW
This excerpt provides early content from a book currently in
development and is still in preview format. (See additional
notices below.)

PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399


Copyright © 2013 Microsoft Corporation

All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
without the written permission of the publisher.

This document is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in
this document. Information in this document, including URL and other Internet website references, is subject to change
without notice. The entire risk of the use or the results from the use of this document remains with the user.

Unless otherwise noted, the companies, organizations, products, domain names, e-mail addresses, logos, people, places, and
events depicted in examples herein are fictitious. No association with any real company, organization, product, domain name,
e-mail address, logo, person, place, or event is intended or should be inferred.

Microsoft and the trademarks listed at /Trademarks/EN-
US.aspx are trademarks of the Microsoft group of companies. All other marks are property of their respective owners.

This book expresses the author’s views and opinions. The information contained in this book is provided without any express,
statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers or distributors will be held liable
for any damages caused or alleged to be caused either directly or indirectly by this book.

Acquisitions, Developmental, and Project Editor: Devon Musgrave
Cover: Twist Creative • Seattle and Joel Panchot


1

Contents
Introduction 12
Who This Book Is For 14
What You'll Need (Can You Say “Samples”?) 15

Some Formatting Notes 16
We Want to Hear from You 17
Stay in Touch 17
Chapter 1 The Life Story of a Windows Store App: Characteristics of the Windows Platform 18
Leaving Home: Onboarding to the Windows Store 20
Discovery, Acquisition, and Installation 22
Playing in Your Own Room: The App Container 26
Different Views of Life: Views and Resolution Scaling 30
Those Capabilities Again: Getting to Data and Devices 33
Taking a Break, Getting Some Rest: Process Lifecycle Management 36
Remembering Yourself: App State and Roaming 38
Coming Back Home: Updates and New Opportunities 42
And, Oh Yes, Then There’s Design 43
Chapter 2 Quickstart 45
A Really Quick Quickstart: The Blank App Template 45
Blank App Project Structure 48
QuickStart #1: Here My Am! and an Introduction to Blend for Visual Studio 52
Design Wireframes 53
Create the Markup 56
Styling in Blend 58
Adding the Code 63
Extra Credit: Improving the App 77
Receiving Messages from the iframe 78
Improving the Placeholder Image with a Canvas Element 79
Handling Variable Image Sizes 80
Moving the Captured Image to AppData (or the Pictures Library) 83
2

Using a Thumbnail Instead of the Full Image 85
The Other Templates: Projects and Items 86

Navigation App Template 86
Grid App Template 87
Hub App Template 87
Split Template 87
Item Templates 88
What We’ve Just Learned 88
Chapter 3 App Anatomy and Performance Fundamentals 90
App Activation 91
Branding Your App 101: The Splash Screen and Other Visuals 92
Activation Event Sequence 96
Activation Code Paths 98
WinJS.Application Events 100
Optimizing Startup Time 103
WinRT Events and removeEventListener 105
App Lifecycle Transition Events and Session State 107
Suspend, Resume, and Terminate 108
Basic Session State in Here My Am! 112
Page Controls and Navigation 115
WinJS Tools for Pages and Page Navigation 115
The Navigation App Template, PageControl Structure, and PageControlNavigator 118
The Navigation Process and Navigation Styles 125
Optimizing Page Switching: Show-and-Hide 127
Page-Specific Styling 128
Async Operations: Be True to Your Promises 130
Using Promises 130
Joining Parallel Promises 132
Sequential Promises: Nesting and Chaining 133
Managing the UI Thread with the WinJS Scheduler 135
3


Scheduler Priorities 136
Scheduling and Managing Tasks 137
Setting Priority in Promise Chains 139
Inside a Task 141
Debugging and Profiling 143
Debug Output and Logging 143
Error Reports and the Event Viewer 144
Async Debugging 146
Performance and Memory Analysis 148
The Windows App Certification Toolkit 153
What We’ve Just Learned 154
Chapter 4 Web Content and Services 155
Network Information and Connectivity 157
Network Types in the Manifest 158
Network Information (the Network Object Roster) 159
The ConnectionProfile Object 161
Connectivity Events 162
Cost Awareness 163
Running Offline 167
Hosting Content: the WebView and iframe Elements 169
Local and Web Contexts (and iframe Elements) 170
Dynamic Content 173
App Content URIs 175
The <x-ms-webview> Element 177
HTTP Requests 187
Using WinJS.xhr 188
Using Windows.Web.Http.HttpClient 189
Suspend and Resume with Online Content 194
Prefetching Content 196
Background Transfer 198

4

Basic Downloads 199
Basic Uploads 203
Completion and Error Notifications 204
Providing Headers and Credentials 205
Setting Cost Policy 205
Grouping Transfers 206
Suspend, Resume, and Restart with Background Transfers 207
Authentication, the Microsoft Account, and the User Profile 208
The Credential Locker 209
The Web Authentication Broker 211
Single Sign-On 215
Using the Microsoft Account 216
The User Profile (and the Lock Screen Image) 222
What We’ve Just Learned 224
Chapter 5 Controls and Control Styling 226
The Control Model for HTML, CSS, and JavaScript 227
HTML Controls 229
Extensions to HTML Elements 232
WinJS Controls 234
Syntax for data-win-options 237
WinJS Control Instantiation 239
Strict Processing and processAll Functions 240
Example: WinJS.UI.HtmlControl 241
Example: WinJS.UI.Rating (and Other Simple Controls) 242
Example: WinJS.UI.Tooltip 243
Example: WinJS.UI.ItemContainer 244
Working with Controls in Blend 247
Control Styling 250

Styling Gallery: HTML Controls 252
Styling Gallery: WinJS Controls 254
5

Some Tips and Tricks 262
Custom Controls 263
Implementing the Dispose Pattern 266
Custom Control Examples 267
Custom Controls in Blend 271
What We’ve Just Learned 275
Chapter 6 Data Binding, Templates, and Collections 277
Data Binseding 278
Data Binding Basics 278
Data Binding in WinJS 280
Under the Covers: Binding mixins 290
Programmatic Binding and WinJS.Binding.bind 292
Binding Initializers 294
Binding Templates 298
Template Options, Properties, and Compilation 301
Collection Data Types 304
Windows.Foundation.Collection Types 304
WinJS Binding Lists 310
What We’ve Just Learned 321
Chapter 7 Collection Controls 323
Collection Control Basics 324
Quickstart #1: The WinJS Repeater Control with HTML controls 324
Quickstart #2: The FlipView Control Sample 328
Quickstart #3: The ListView Essentials Sample 330
Quickstart #4: The ListView Grouping Sample 332
ListView in the Grid App Project Template 336

The Semantic Zoom Control 340
How Templates Work with Collection Controls 343
Referring to Templates 343
Template Functions (Part 1): The Basics 344
6

Creating Templates from Data Sources in Blend 347
Repeater Features and Styling 351
FlipView Features and Styling 356
Collection Control Data Sources 359
The Structure of Data Sources (Interfaces Aplenty!) 360
A FlipView Using the Pictures Library 364
Custom Data Sources and WinJS.UI.VirtualizedDataSource 366
ListView Features and Styling 372
When Is ListView the Right Choice? 373
Options, Selections, and Item Methods 375
Styling 378
Loading State Transitions 380
Drag and Drop 382
Layouts 385
Template Functions (Part 2): Optimizing Item Rendering 394
What We’ve Just Learned 399
Chapter 8 Layout and Views 401
Principles of Page Layout 403
Sizing, Scaling, and Views: The Many Faces of Your App 406
Variable View Sizing and Orientations 406
Screen Resolution, Pixel Density, and Scaling 417
Multiple Views 422
Pannable Sections and Styles 426
Laying Out the Hub 427

Laying Out the Sections 428
Panning Styles and Railing 429
Panning Snap Points and Limits 431
Zooming Snap Points and Limits 432
The Hub Control and Hub App Template 433
Hub Control Styling 440
7

Using the CSS Grid 441
Overflowing a Grid Cell 443
Centering Content Vertically 443
Scaling Font Size 445
Item Layout 445
CSS 2D and 3D Transforms 446
Flexbox 446
Nested and Inline Grids 447
Fonts and Text Overflow 449
Multicolumn Elements and Regions 450
What We’ve Just Learned 453
Chapter 9 Commanding UI 454
Where to Place Commands 455
The App Bar and Nav Bar 460
App Bar Basics and Standard Commands 461
App Bar Styling 470
Command Menus 474
Custom App Bars 476
Nav Bar Features 477
Nav Bar Styling 486
Flyouts and Menus 488
WinJS.UI.Flyout Properties, Methods, and Events 490

Flyout Examples 491
Menus and Menu Commands 494
Message Dialogs 499
Improving Error Handling in Here My Am! 500
What We’ve Just Learned 506
Chapter 10 The Story of State, Part 1: App Data and Settings 508
The Story of State 510
App Data Locations 513
8

App Data APIs (WinRT and WinJS) 514
Settings Containers 515
State Versioning 517
Folders, Files, and Streams 518
FileIO, PathIO, and WinJS Helpers (plus FileReader) 524
Encryption and Compression 525
Q&A on Files, Streams, Buffers, and Blobs 525
Using App Data APIs for State Management 533
Transient Session State 533
Local and Temporary State 534
IndexedDB, SQLite, and Other Database Options 536
Roaming State 538
Settings Pane and UI 540
Design Guidelines for Settings 543
Populating Commands 545
Implementing Commands: Links and Settings Flyouts 547
Programmatically Invoking Settings Flyouts 549
Here My Am! Update 551
What We’ve Just Learned 552
Chapter 11 The Story of State, Part 2: User Data, Files, and SkyDrive 554

The Big Picture of User Data 555
Using the File Picker and Access Cache 560
The File Picker UI 561
The File Picker API 566
Access Cache 570
StorageFile Properties and Metadata 573
Availability 574
Thumbnails 575
File Properties 579
Media-Specific Properties 582
9

Folders and Folder Queries 588
KnownFolders and the StorageLibrary Object 589
Removable Storage 592
Simple Enumeration and Common Queries 593
Custom Queries 598
Metadata Prefetching with Queries 603
Creating Gallery Experiences 604
File Activation and Association 606
What We’ve Just Learned 611
Chapter 12 Input and Sensors 613
Touch, Mouse, and Stylus Input 614
The Touch Language, Its Translations, and Mouse/Keyboard Equivalents 616
What Input Capabilities Are Present? 622
Unified Pointer Events 624
Gesture Events 628
The Gesture Recognizer 636
Keyboard Input and the Soft Keyboard 638
Soft Keyboard Appearance and Configuration 639

Adjusting Layout for the Soft Keyboard 642
Standard Keystrokes 645
Inking 646
Geolocation 648
Geofencing 651
Sensors 655
What We’ve Just Learned 658
Appendix A Demystifying Promises 660
What Is a Promise, Exactly? The Promise Relationships 660
The Promise Construct (Core Relationship) 663
Example #1: An Empty Promise! 665
Example #2: An Empty Async Promise 667
10

Example #3: Retrieving Data from a URI 668
Benefits of Promises 669
The Full Promise Construct 670
Nesting Promises 674
Chaining Promises 677
Promises in WinJS (Thank You, Microsoft!) 682
The WinJS.Promise Class 683
Originating Errors with WinJS.Promise.WrapError 685
Some Interesting Promise Code 686
Delivering a Value in the Future: WinJS.Promise.timeout 687
Internals of WinJS.Promise.timeout 687
Parallel Requests to a List of URIs 688
Parallel Promises with Sequential Results 688
Constructing a Sequential Promise Chain from an Array 690
PageControlNavigator._navigating (Page Control Rendering) 690
Bonus: Deconstructing the ListView Batching Renderer 692

Appendix B WinJS Extras 696
Exploring WinJS.Class Patterns 696
WinJS.Class.define 696
WinJS.Class.derive 698
Mixins 699
Obscure WinJS Features 701
Wrappers for Common DOM Operations 701
WinJS.Utilities.data, convertToPixels, and Other Positional Methods 702
WinJS.Utilities.empty, eventWithinElement, and getMember 704
WinJS.UI.scopedSelect and getItemsFromRanges 704
Extended Splash Screens 705
Adjustments for View Sizes 711
Custom Layouts for the ListView Control 712
Minimal Vertical Layout 714
11

Minimal Horizontal Layout 717
Two-Dimensional and Nonlinear Layouts 721
Virtualization 723
Grouping 725
The Other Stuff 726
Appendix C Additional Networking Topics 731
XMLHttpRequest and WinJS.xhr 731
Tips and Tricks for WinJS.xhr 732
Breaking Up Large Files (Background Transfer API) 733
Multipart Uploads (Background Transfer API) 734
Notes on Encryption, Decryption, Data Protection, and Certificates 737
Syndication: RSS, AtomPub, and XML APIs in WinRT 737
Reading RSS Feeds 738
Using AtomPub 741

The Credential Picker UI 742
Other Networking SDK Samples 747
About the Author 748


12

Introduction
In celebration of the one-year anniversary of this book’s first edition, I’m delighted to offer you this
second preview of Programming Windows Store Apps in HTML, CSS, and JavaScript (Second Edition).
It’s been a huge year for both the book and the platform that it supports. With the general
availability of Windows 8.1 earlier this month (October 2013), the capabilities of the Windows platform
have grown dramatically, which is clearly in evidence by the expanded size of this second edition! Even
in this preview (12 chapters and three appendices), the book is not far from the length of the first
edition, and there are still eight chapters (and one appendix) to go. Nevertheless, it’s my pleasure to
provide you with a comprehensive volume on Microsoft’s latest operating system.
This second preview takes us through nearly all of the Windows Library for JavaScript, which
includes new controls like the Hub and Nav Bar. It also delves quite a bit into core WinRT APIs, such as
those for working with HTTP requests, app state, and files. The bulk of WinRT coverage is yet to come
in the final edition, as the remaining chapters include media, animations, contracts, live tiles,
notifications, background tasks, device access, WinRT components, accessibility, localization, and the
Windows Store. Fortunately, much is still the same as it was in Windows 8, and you can refer to the first
edition of this book as a basis. Then check out the session videos from //build 2013 that you can find
through . The Windows Developer Center, , also has
updated documentation that covers Windows 8.1, so you can find much more there. I can specifically
recommend Windows 8.1: New APIs and features for developers.
As I mentioned in the first preview, this second edition is intended to stand alone for developers
who are starting with Windows 8.1. It represents the state of Windows 8.1 rather than trying to
document the delta from Windows 8. For this reason I don’t explain how to migrate apps from
Windows 8 nor do I highlight many changes to APIs and behaviors (I do occasionally in specific cases).

Check the Developer Center for such information.
That said, here’s what you’ll find in this second preview:
 Chapter 1, “The Life Story of a Windows Store App,” covers the core characteristics of the
Windows platform. This is much the same as in Windows 8, with the biggest exception being
the view model for apps where we now have a variable sizing model.
 Chapter 2, “Quickstart,” builds a first complete app, Here My Am!, that is gradually improved
throughout the book. One significant change in this second preview is the use of thumbnails for
loading and displaying images, which is a key performance consideration that you should
always keep in mind. It’s very seldom that you need to load full image data.
 Chapter 3, “App Anatomy and Performance Fundamentals,” is much expanded from the first
edition, especially including coverage of the WinJS Scheduler API for managing work on the UI
thread, and a new section on debugging and profiling. I’ve also changed the title to reflect the
13

importance of performance considerations from the earliest stages of your app building.
 Chapter 4, “Web Content and Services,” is a mixture of new content and networking topics from
the first edition’s Chapter 14. I moved these topics earlier in the book because using web
content is increasingly important for apps, if not essential. This chapter covers network
connectivity, hosting content (especially with the new x-ms-webview control), making HTTP
requests (especially through the new Windows.Web.Http.HttpClient API), background
transfers (which have been improved), authentication, and a little on Live Services.
 Chapter 5, “Controls and Control Styling,” is updated from the first edition’s Chapter 4 and
includes the new WinJS.UI.ItemContainer control and discussed how to work with the WinJS
dispose pattern.
 Chapter 6, “Data Binding, Templates, and Collections,” combines material from the first edition’s
chapters on controls and collection controls. It’s helpful to look at templates by themselves,
especially given optimizations that are introduced with WinJS 2.0. This chapter also looks at
collection data types both in WinRT (types like the vector) and the WinJS.Binding.List,
setting us up well for Chapter 7.
 Chapter 7, “Collection Controls,” focuses completely on the WinJS controls that provide UI for

collections. These are the FlipView, ListView, Semantic Zoom, and Repeater controls. The
ListView especially has many updates in WinJS 2.0, such as drag and drop support and better
layouts (including custom layouts, see Appendix B).
 Chapter 8, “Layout and Views,” is much rewritten from the first edition’s chapter on layout,
especially given the change from the distinct view states of Windows 8 to the variable sizing
model of Windows 8.1. In addition, Windows 8.1 enables apps to have multiple views, which is a
fun topic, and WinJS adds a new Hub control to support great home page experiences.
 Chapter 9, “Commanding UI,” is much the same as the first edition’s Chapter 7 and now
includes the Nav Bar control that’s new in WinJS 2.0. The App Bar control also have
improvements for easier customization.
 Chapter 10, “The Story of State, Part 1: App Data and Settings,” shares much of the first edition’s
content from Chapter 8 but tells the story of app data much more clearly. I have to admit that I
wasn’t wholly satisfied with the first edition’s treatment of the subject, and after giving several
//build talks that helped me organize the material, it was clear that I needed to cleanly separate
app data (Chapter 10) and user data (Chapter 11). That opened up space in Chapter 10 here to
also cover file I/O basics, as well as the matter of streams, buffers, and blobs.
 Chapter 11, “The Story of State, Part 2: User Data, Files, and SkyDrive,” completes the discussion
of working with files and folders, including the deep integration of SkyDrive that we have in
Windows 8.1. This is another place we see the importance of using thumbnails when working
with images, as it greatly helps to boost performance and reduce memory overhead, especially
with collection controls.
14

 Chapter 12, “Input and Sensors,” was one of the easier chapters to update, as there aren’t many
changes in these areas for Windows 8.1. The two main exceptions are the change from
MSPointer* events to now-standard pointer* events, and the addition of geofencing APIs.
 Appendix A, “Demystifying Promises,” completes the discussion of promises that are introduced
in Chapters 2 and 3. After writing the first edition, I wanted to spend more time with promises
for my own sake, but it’s just my nature to leave a paper trail of my learnings! So, in this
appendix we start from scratch about what promises are, see how promises are expressed in

WinJS, explore how to create and source promises, and then pick apart some specific promise-
heavy code.
 Appendix B, “WinJS Extras,” is a collection of WinJS material that didn’t fit cleanly into other
chapters, including WinJS.Namespace.define, WinJS.Class.define, obscure WinJS APIs, and
custom layouts for the ListView control (where we even do circular and spiral layouts!).
 Appendix C, “Additional Networking Topics,” contains material that is related to Chapter 4 but
didn’t fit into that flow or that is more peripheral in nature. Note that WinJS.xhr is covered
here because Chapter 4 emphasizes the preferred Windows.Web.Http.HttpClient API.
As you can see, in this second edition I’ll be using appendices to go deeper into certain topics that
would be too much of a distraction from the main flow of the chapters. Let me know what you think.
Some of this material I’ve already posted on my blog, where
I’ve been working on various topics since we published the first edition. I’ll continue to be posting
there, though a bit less frequently as I focus on completing this second edition.
Who This Book Is For
This book is about writing Windows Store apps using HTML5, CSS3, and JavaScript. Our primary focus
will be on applying these web technologies within the Windows 8.1 platform, where there are unique
considerations, and not on exploring the details of those web technologies themselves. For the most
part, then, I'm assuming that you're already at least somewhat conversant with these standards. We will
cover some of the more salient areas like the CSS grid, which is central to app layout, but otherwise I
trust that you're capable of finding appropriate references for most everything else.
That said, much of this book is not specific to HTML, CSS, or JavaScript at all, because it’s focused on
the Windows platform and the Windows Runtime (WinRT) APIs. As such, at least half of this book will
be useful to developers working in other languages (like C# or C++) who want to understand the
system better. Much of Chapter 4 and Appendix C in this second preview, for example, is specific to
WinRT. The subjects of app anatomy and promises in Chapter 3 and Appendix A, on the other hand,
are very specific to the JavaScript option. In any case, this is a free ebook, so there’s no risk, regardless
of your choice of language and presentation technology!

15


In this book I'm assuming that your interest in Windows has at least two basic motivations. One, you
probably want to come up to speed as quickly as you can, perhaps to carve out a foothold in the
Windows Store sooner rather than later. Toward that end, I've front-loaded the early chapters with the
most important aspects of app development that also give you experience with the tools, the API, and
some core platform features. On the other hand, you probably also want to make the best app you can,
one that performs really well and that takes advantage of the full extent of the platform. Toward this
end, I've also endeavored to make this book comprehensive, helping you at least be aware of what's
possible and where optimizations can be made.
Many insights have come to me from working directly with real-world developers on their real-
world apps. As part of the Windows Ecosystem team, myself and my teammates have been on the front
lines bringing those first apps to the Windows Store. This has involved writing bits of code for those
apps and investigating bugs, along with conducting design, code, and performance reviews with
members of the Windows engineering team. As such, one of my goals with this book is to make that
deep understanding available to many more developers, including you!
What You'll Need (Can You Say “Samples”?)
To work through this book, you should have Windows 8.1 installed on your development machine,
along with the Windows SDK for Windows 8.1 and the associated tools. All the tools, along with a
number of other resources, are listed on the Windows 8.1 Downloads page. You’ll specifically need
Microsoft Visual Studio Express 2013 for Windows. We’ll also acquire other tools along the way as we
need them in this ebook. (Note that for all the screen shots in this book, I switched Visual Studio from
its default “dark” color theme to the “light” theme, as the latter works better against a white page.)
Also be sure to download the whole set of Windows app samples for JavaScript. We'll be drawing
from many—if not most—of these samples in the chapters ahead, pulling in bits of their source code to
illustrate how many different tasks are accomplished.
I’ve seen some reviews of programming books that criticize authors for just pulling code samples
from documentation rather than writing all their own code samples from scratch. Although I do
provide a number of additional examples in this second preview’s companion content, it’s been one of
my secondary goals to help you understand where and when to use the tremendous resources in what
is clearly the best set of samples I’ve ever seen for any release of Windows. You’ll often be able to find a
piece of code in one of the samples that does exactly what you need in your app or that is easily

modified to suit your purpose. In most cases these samples are the same ones I would have written
myself, and I’m very glad that wasn’t necessary! In a few cases I felt the samples lacked certain
scenarios, so you’ll see some modified and extended samples in the companion content.
I’ve also made it a point to personally look through every one of the JavaScript samples, understand
what they demonstrate, and then refer to them in their proper context. This, I hope, will save you the
trouble of having to do that level of research yourself and thus make you more productive in your
development efforts.
16

A big part of the companion content are the many revisions of the app I call “Here My Am!” (a
variant of “Hello World.” We start building this in Chapter 2 and refine it throughout the course of the
book. This includes localizing it into a number of different languages by the time we reach the end.
Something else I’ve done with this second preview is expand the use of video content. (All of the
videos are also available in a folder with this preview’s companion content). As in the first edition, I’ve
made a few longer videos to demonstrate use of the Visual Studio and Blend tools. In a number of
other cases, it’s far easier to show dynamic effects in video than to explain them in text and
screenshots. I’d also love to hear what you think about these.
Beyond all this, you’ll find that the Windows samples gallery as well as the Visual Studio sample
gallery also lets you search and browse additional projects that have been contributed by other
developers—perhaps also you! (On the Visual Studio site, by the way, be sure to filter on Windows
Store apps because the gallery covers all Microsoft platforms.) And, of course, there will be many more
developers who share projects on their own.
In this book I occasionally refer to posts on the Windows App Builder Blog, which is a great resource
to follow. And if you’re interested in the Windows 8 backstory—that is, how Microsoft approached this
whole process of reimagining the operating system—check out the Building Windows 8 blog.
Some Formatting Notes
Throughout this book, identifiers that appear in code—such as variable names, property names, and
API functions and namespaces—are formatted with a color and a fixed-point font. Here’s an example:
Windows.Storage.ApplicationData.current. At times, a fully qualified name like this—those that
include the entire namespace—can become quite long and don’t readily break across lines. In this

second preview you’ll see that these are occasionally hyphenated, as with Windows.Security
Cryptography.CryptographicBuffer.convertStringToBinary. Generally speaking, the hyphen is
not part of the identifier, though there are exceptions especially with CSS styles like win-container. In
any case, Visual Studio’s IntelliSense will help you, well, make sense of these!
For simplicity’s sake (and because such hyphens produced some headaches in the first edition of this
book), I’ve often omitted the namespace from identifiers because I trust you’ll see it from the context.
Plus, it’s easy enough to search on the last piece of the identifier on and find
its reference page—or just click on the links I’ve included.
Occasionally, you’ll also see an event name in a different color, as in datarequested. These
specifically point out events that originate from Windows Runtime objects, for which there are a few
special considerations for adding and removing event listeners in JavaScript to prevent memory leaks,
as discussed in Chapter 3. I make a few reminders about this point throughout the chapters, but the
purpose of this special color is to give you a quick reminder that doesn’t break the flow of the
discussion otherwise.
17

We Want to Hear from You
At Microsoft Press, your satisfaction is our top priority, and your feedback our most valuable asset.
Please tell us what you think of this book at

The survey is short, and we read every one of your comments and ideas. Thanks in advance for your
input!
Stay in Touch
Let’s keep the conversation going! We’re on Twitter: And you can
keep up with Kraig here:



18


Chapter 1
The Life Story of a Windows Store
App: Characteristics of the
Windows Platform
Paper or plastic? Fish or cut bait? To be or not to be? Standards-based or native? These are the
questions of our time….
Well, OK, maybe most of these aren’t the grist for university-level philosophy courses, but certainly
the last one has been increasingly important for app developers. Standards-based apps are great
because they run on multiple platforms; your knowledge and experience with standards like HTML5
and CSS3 are likewise portable. Unfortunately, because standards generally take a long time to
produce, they always lag behind the capabilities of the platforms themselves. After all, competing
platform vendors will, by definition, always be trying to differentiate! For example, while HTML5 now
has a standard for geolocation/GPS sensors and has started on working drafts for other forms of sensor
input (like accelerometers, compasses, near-field proximity, and so on), native platforms already make
these available. And by the time HTML’s standards are in place and widely supported, the native
platforms will certainly have added another set of new capabilities.
As a result, developers wanting to build apps around cutting-edge features—to differentiate from
their own competitors!—must adopt the programming language and presentation technology
imposed by each native platform or take a dependency on a third-party framework that tries to bridge
the differences.
Bottom line: it’s a hard choice.
Fortunately, Windows 8 and Windows 8.1 provide what I personally think is a brilliant solution for
apps. Early on, the Windows team set out to solve the problem of making native capabilities—the
system API, in other words—directly available to any number of programming languages, including
JavaScript. This is what’s known as the Windows Runtime API, or just WinRT for short (an API that’s
making its way onto the Windows Phone platform as well).
WinRT APIs are implemented according to a certain low-level structure and then “projected” into
different languages—namely C++, C#, Visual Basic, and JavaScript—in a way that looks and feels
natural to developers familiar with those languages. This includes how objects are created, configured,
and managed; how events, errors, and exceptions are handled; how asynchronous operations work (to

keep the user experience fast and fluid); and even the casing of method, property, and event names.
19

The Windows team also made it possible to write native apps that employ a variety of presentation
technologies, including DirectX, XAML, and, in the case of apps written in JavaScript, HTML5 and CSS3.
This means that Windows gives you—a developer already versed in HTML, CSS, and JavaScript
standards—the ability to use what you know to write fully native Windows Store apps using the WinRT
API and still utilize web content! And I do mean fully native apps that both offer great content in
themselves and integrate deeply with the surrounding system and other apps (unlike “hybrids” where
one simply hosts web content within a thin, nearly featureless native shell). These apps will, of course,
be specific to the Windows platform, but the fact that you don’t have to learn a completely new
programming paradigm is worthy of taking a week off to celebrate—especially because you won’t have
to spend that week (or more) learning a complete new programming paradigm!
It also means that you’ll be able to leverage existing investments in JavaScript libraries and CSS
template repositories: writing a native app doesn’t force you to switch frameworks or engage in
expensive porting work. That said, it is also possible to use multiple languages to write an app,
leveraging the dynamic nature of JavaScript for app logic while leveraging languages like C# and C++
for more computationally intensive tasks. (See “Sidebar: Mixed Language Apps” later in this chapter,
and if you’re curious about language choice for apps more generally, see My take on HTML/JS vs.
C/XAML vs. C++/DirectX on my blog.)
A third benefit is that as new web standards develop and provide APIs for features of the native
platform, the fact that your app is written in the same language as the web will make it easier to port
features from your native app to cross-platform web applications, if so desired.
Throughout this book we’ll explore how to leverage what you know of standards-based web
technologies—HTML, CSS, and JavaScript—to build great Windows Store apps for Windows 8.1. In the
next chapter we’ll focus on the basics of a working app and the tools used to build it. Then we’ll look at
fundamentals like the fuller anatomy of an app, incorporating web content, using controls and
collections, layout, commanding, state management, and input (including sensors), followed by
chapters on media, animations, contracts through which apps work together, live tiles and toast
notifications, accessing peripheral devices, WinRT components (through which you can use other

programming languages and the additional APIs they can access), and the Windows Store (including
localization and accessibility). There is much to learn—it’s a rich platform!
For starters, let’s talk about the environment in which apps run and the characteristics of the
platform on which they are built—especially the terminology that we’ll depend on in the rest of the
book (highlighted in italics). We’ll do this by following an app’s journey from the point when it first
leaves your hands, through its various experiences with your customers, to where it comes back home
for renewal and rebirth (that is, updates). For in many ways your app is like a child: you nurture it
through all its formative stages, doing everything you can to prepare it for life in the great wide world.
So it helps to understand the nature of that world!


20

Terminology note What we refer to as Windows Store apps, or sometimes just Store apps, are those
that are acquired from the Windows Store and for which all the platform characteristics in this chapter
(and book) apply. These are distinctly different from traditional desktop applications that are acquired
through regular retail channels and installed through their own setup programs. Unless noted, then, an
“app” in this book refers to a Windows Store app.
Leaving Home: Onboarding to the Windows Store
For Windows Store apps, there’s really one port of entry into the world: customers always acquire,
install, and update apps through the Windows Store. Developers and enterprise users can side-load
apps, but for the vast majority of the people you care about, they go to the Windows Store and
nowhere else.
This obviously means that an app—the culmination of your development work—has to get into the
Store in the first place. This happens when you take your pride and joy, package it up, and upload it to
the Store by using the Store/Upload App Packages command in Visual Studio.
1
The package itself is an
appx file (.appx)—see Figure 1-1—that contains your app’s code, resources, libraries, and a manifest, up
to a combined limit of 8GB. The manifest describes the app (names, logos, etc.), the capabilities it wants

to access (such as media libraries or specific devices like cameras), and everything else that’s needed to
make the app work (such as file associations, declaration of background tasks, and so on). Trust me,
we’ll become great friends with the manifest!

FIGURE 1-1 An appx package is simply a zip file that contains the app’s files and assets, the app manifest, a
signature, and a sort of table-of-contents called the blockmap. When uploading an app, the initial signature is
provided by Visual Studio; the Windows Store will re-sign the app once it’s certified.


1
To do this you’ll need to create a developer account with the Store by using the Store > Open Developer Account command in
Visual Studio Express. Visual Studio Express and Expression Blend, which we’ll also be using, are free tools you can obtain from
. This also works in Visual Studio Ultimate, the fuller, paid version of Microsoft’s development environment.
21

Blockmaps make updates easy The blockmap is hugely important for the customer experience of app
updates, and, as a consequence, for your confidence in issuing updates. It describes how the app’s files
are broken up into 64K blocks. In addition to providing certain security functions (like detecting
whether a package has been tampered with) and performance optimization, the blockmap is used to
determine exactly what parts of an app have been updated between versions so that the Windows
Store need download only those specific blocks rather than the whole app anew. This greatly reduces
the time and overhead that a user experiences when acquiring and installing updates. That is, even if
your whole app package is 300MB, an update that affects a total of four blocks would mean your
customers are downloading only 256 kilobytes.
The upload process will walk you through setting your app’s name (which you do ahead of time
using the Store > Reserve App Name and Store > Associate App with the Store commands in Visual
Studio), choosing selling details (including price tier, in-app purchases, and trial periods), providing a
description and graphics, and also providing notes to manual testers. After that, your app goes through
a series of job interviews, if you will: background checks (malware scans and GeoTrust certification) and
manual testing by a human being who will read the notes you provide (so be courteous and kind!).

Along the way you can check your app’s progress through the Windows Store Dashboard.
2

The overarching goal with these job interviews (or maybe it’s more like getting through airport
security!) is to help users feel confident and secure in trying new apps, a level of confidence that isn’t
generally found with apps acquired from the open web. As all apps in the Store are certified, signed,
and subject to ratings and reviews, customers can trust all apps from the Store as they would trust
those recommended by a reliable friend. Truly, this is wonderful news for most developers, especially
those just getting started—it gives you the same access to the worldwide Windows market that has
been previously enjoyed only by those companies with an established brand or reputation.
It’s worth noting that because you set up pricing, trial versions, and in-app purchases during the on-
boarding process, you’ll have already thought about your app’s relationship to the Store quite a bit!
After all, the Store is where you’ll be doing business with your app, whether you’re in business for fame,
fortune, fun, or philanthropy.
Indeed, this relationship spans the entire lifecycle of an app—from planning and development to
distribution, support, and servicing. This is, in fact, why I’ve started this life story of an app with the
Windows Store, because you really want to understand that whole lifecycle from the very beginning of
planning and design. If, for example, you’re looking to turn a profit from a paid app or in-app
purchases, perhaps also offering a time-limited or feature-limited trial, you’ll want to engineer your app
accordingly. If you want to have a free, ad-supported app, or want to use a third-party commerce
solution for in-app purchases (bypassing revenue sharing with the Store), these choices also affect your
design from the get-go. And even if you’re just going to give the app away to promote a cause or to


2
All of the automated tests except the malware scans are incorporated into the Windows App Certification Kit, affectionately
known as the WACK. This is part of the Windows SDK that is itself included with the Visual Studio Express/Expression Blend
download. If you can successfully run the WACK during your development process, you shouldn’t have any problem passing the
first stage of onboarding.
22


just share your joy, understanding the relationship between the Store and your app is still important.
For all these reasons, you might want to skip ahead and read the “Your App, Your Business” section of
Chapter 20, "Apps for Everyone, Part 2," before you start writing your app in earnest. Also, take a look
at the Preparing your app for the Store topic on the Windows Developer Center.
Anyway, if your app hits any bumps along the road to certification, you’ll get a report back with all
the details, such as any violations of the Windows app certification requirements (part of the Windows
Store agreements section). Otherwise, congratulations—your app is ready for customers!

Sidebar: The Store API and Product Simulator
At run time, apps use the Windows.ApplicationModel.Store.CurrentApp class in WinRT to
retrieve their product information from the Store (including in-app purchase listings), check
license status, and prompt the user to make purchases (such as upgrading a trial or making an
in-app purchase).
This begs a question: how can an app test such features before it’s even in the Store? The
answer is that during development, you use these APIs through the CurrentAppSimulator class
instead. This is entirely identical to CurrentApp (and in the same namespace) except that it works
against local data in an XML file rather than live Store data in the cloud. This allows you to
simulate the various conditions that your app might encounter so that you can exercise all your
code paths appropriately. Just before packaging your app and sending it to the Store, just
change CurrentAppSimulator to CurrentApp and you’re good to go. (If you forget, the
simulator will simply fail on a non-developer machine, like those used by the Store testers,
meaning that you’ll fail certification.)
Discovery, Acquisition, and Installation
Now that your app is out in the world, its next job is to make itself known and attractive to potential
customers. What’s vital to understand here is what the Windows Store does and does not do for you. Its
primary purpose is to provide a secure and trustworthy marketplace for distributing apps, updating
apps, transparently handling financial transactions across global markets, and collecting customer
reviews and telemetry—which taken together is a fabulous service! That said, the mere act of
onboarding an app to the Windows Store does not guarantee anyone will find it. That’s one reality of

publishing software that certainly hasn’t changed. You still need to write great apps and you still need
to market them to your potential customers, using advertising, social media, and everything else you’d
do when trying to get a business off the ground.
That said, even when your app is found in the Store it needs to present itself well to its suitors. Each
app in the Store has a product description page where people see your app description, screen shots,
23

ratings and reviews, and the capabilities your app has declared in its manifest, as shown in Figure 1-2.
That last bit means you want to be judicious in declaring your capabilities. A music player app, for
instance, will obviously declare its intent to access the user’s music library but usually doesn’t need to
declare access to the pictures library unless it has a good justification. Similarly, a communications app
would generally ask for access to the camera and microphone, but a news reader app probably
wouldn’t. On the other hand, an ebook reader might declare access to the microphone if it had a
feature to attach audio notes to specific bookmarks.

FIGURE 1-2 A typical app page in the Windows Store; by tapping the Permissions link at the upper left, the page
pans to the Details section, which lists all the capabilities that are declared in the manifest (overlay). You can see
here that Skype declares five different capabilities, all of which are appropriate for the app’s functionality.
The point here is that what you declare needs to make sense to the user, and if there are any doubts
you should clearly indicate the features related to those declarations in your app’s description.
Otherwise the user might really wonder just what your news reader app is going to do with the
microphone and might opt for another app that seems less intrusive.
3

The user will also see your app pricing, of course, and whether you offer a trial period. Whatever the
case, if they choose to install the app (getting it for free, paying for it, or accepting a trial), your app
now becomes fully incarnate on a real user’s device. The appx package is downloaded to the device
and installed automatically along with any dependencies, such as the Windows Library for JavaScript
(see “Sidebar: What is the Windows Library for JavaScript?”). As shown in Figure 1-3, the Windows
deployment manager creates a folder for the app, extracts the package contents to that location,

creates appdata folders (local, roaming, and temp, which the app can freely access, along with settings


3
The user always has the ability to disallow access to sensitive resources at run time for those apps that have declared the intent.

×