Microsoft press e_book_programming_windows_8_apps_with_html_css_and_javascript_pdf

13,073

Published on

Published in: Education, Business, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
13,073
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Microsoft press e_book_programming_windows_8_apps_with_html_css_and_javascript_pdf

  1. 1. 991
  2. 2. PUBLISHED BYMicrosoft PressA Division of Microsoft CorporationOne Microsoft WayRedmond, Washington 98052-6399Copyright © 2012 Microsoft CorporationAll rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or byany means without the written permission of the publisher.ISBN: 978-0-7356-7261-1Microsoft Press books are available through booksellers and distributors worldwide. If you need supportrelated to this book, email Microsoft Press Book Support at mspinput@microsoft.com. Please tell us whatyou think of this book at http://aka.ms/tellpress.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 beinferred.Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rightsunder copyright, no part of this document may be reproduced, stored in or introduced into a retrievalsystem, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, orotherwise), or for any purpose, without the express written permission of Microsoft Corporation.Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other marks are property oftheir respective owners.This book expresses the author’s views and opinions. The information contained in this book is providedwithout any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor itsresellers, or distributors will be held liable for any damages caused or alleged to be caused either directly orindirectly by this book.Acquisitions, Developmental, and Project Editor: Devon MusgraveCover: Twist Creative • Seattle2
  3. 3. Table of ContentsIntroduction............................................................................................................................................ 19Who This Book Is For ...................................................................................................................................................................20What Youll Need (Can You Say “Samples”?) ......................................................................................................................21A Formatting Note........................................................................................................................................................................22Acknowledgements......................................................................................................................................................................23Errata & Book Support ................................................................................................................................................................24We Want to Hear from You.......................................................................................................................................................25Stay in Touch ..................................................................................................................................................................................25Chapter 1: The Life Story of a Windows Store App:Platform Characteristics of Windows 8................................................................................... 26Leaving Home: Onboarding to the Windows Store..........................................................................................................27Discovery, Acquisition, and Installation.................................................................................................................................30Playing in Your Own Room: The App Container................................................................................................................34Different Views of Life: View States and Resolution Scaling ..........................................................................................37Those Capabilities Again: Getting to Data and Devices ..................................................................................................40Taking a Break, Getting Some Rest: Process Lifecycle Management..........................................................................43Remembering Yourself: App State and Roaming ..............................................................................................................45Coming Back Home: Updates and New Opportunities...................................................................................................48And, Oh Yes, Then There’s Design ..........................................................................................................................................50Chapter 2: Quickstart ................................................................................................................ 52A Really Quick Quickstart: The Blank App Template........................................................................................................52Blank App Project Structure..................................................................................................................................................55QuickStart #1: Here My Am! and an Introduction to Blend for Visual Studio.........................................................59Design Wireframes...................................................................................................................................................................59Create the Markup...................................................................................................................................................................62Styling in Blend..........................................................................................................................................................................64Adding the Code ......................................................................................................................................................................68Creating a Map with the Current Location .....................................................................................................................69Oh Wait, the Manifest!...........................................................................................................................................................733
  4. 4. Capturing a Photo from the Camera ................................................................................................................................75Sharing the Fun! .......................................................................................................................................................................78Extra Credit: Receiving Messages from the iframe .......................................................................................................81The Other Templates ...................................................................................................................................................................82Fixed Layout Template............................................................................................................................................................82Navigation Template...............................................................................................................................................................83Grid Template............................................................................................................................................................................83Split Template............................................................................................................................................................................83What We’ve Just Learned...........................................................................................................................................................84Chapter 3: App Anatomy and Page Navigation.....................................................................85Local and Web Contexts within the App Host....................................................................................................................86Referencing Content from App Data: ms-appdata.......................................................................................................90Here My Am! with ms-appdata...........................................................................................................................................92Sequential Async Operations: Chaining Promises .............................................................................................................94Error Handling Within Promises: then vs. done.............................................................................................................96Debug Output, Error Reports, and the Event Viewer...................................................................................................96App Activation................................................................................................................................................................................99Branding Your App 101: The Splash Screen and Other Visuals................................................................................99Activation Event Sequence..................................................................................................................................................101Activation Code Paths...........................................................................................................................................................103WinJS.Application Events.....................................................................................................................................................105Extended Splash Screens......................................................................................................................................................106Activation Deferrals...............................................................................................................................................................108App Lifecycle Transition Events and Session State ..........................................................................................................109Suspend, Resume, and Terminate.....................................................................................................................................109Basic Session State in Here My Am!.................................................................................................................................114Data from Services and WinJS.xhr.........................................................................................................................................116Handling Network Connectivity (in Brief)......................................................................................................................119Tips and Tricks for WinJS.xhr..............................................................................................................................................120Page Controls and Navigation ...............................................................................................................................................1214
  5. 5. WinJS Tools for Pages and Page Navigation ................................................................................................................121The Navigation App Template, PageControl Structure, and PageControlNavigator.....................................123The Navigation Process and Navigation Styles............................................................................................................129Optimizing Page Switching: Show-and-Hide ...............................................................................................................130WinRT Events and removeEventListener.............................................................................................................................131Completing the Promises Story..............................................................................................................................................133What We’ve Just Learned.........................................................................................................................................................135Chapter 4: Controls, Control Styling, and Data Binding .....................................................136The Control Model for HTML, CSS, and JavaScript .........................................................................................................137HTML Controls .............................................................................................................................................................................138WinJS stylesheets: ui-light.css, ui-dark.css, and win-* styles....................................................................................141Extensions to HTML Elements............................................................................................................................................142WinJS Controls .............................................................................................................................................................................142WinJS Control Instantiation.................................................................................................................................................144Strict Processing and processAll Functions....................................................................................................................145Example: WinJS.UI.Rating Control.....................................................................................................................................146Example: WinJS.UI.Tooltip Control ...................................................................................................................................147Working with Controls in Blend.............................................................................................................................................149Control Styling .............................................................................................................................................................................151Styling Gallery: HTML Controls..........................................................................................................................................153Styling Gallery: WinJS Controls..........................................................................................................................................155Some Tips and Tricks.............................................................................................................................................................158Custom Controls..........................................................................................................................................................................159Custom Control Examples ...................................................................................................................................................161Custom Controls in Blend....................................................................................................................................................164Data Binding.................................................................................................................................................................................167Data Binding in WinJS...........................................................................................................................................................169One-Time Binding..................................................................................................................................................................170One-Way Binding...................................................................................................................................................................173Implementing Two-Way Binding .....................................................................................................................................1755
  6. 6. Additional Binding Features ...............................................................................................................................................175Binding Initializers..................................................................................................................................................................177Binding Templates and Lists...............................................................................................................................................178What We’ve Just Learned.........................................................................................................................................................178Chapter 5: Collections and Collection Controls....................................................................180Collection Control Basics..........................................................................................................................................................181Quickstart #1: The FlipView Control Sample.................................................................................................................181Quickstart #2a: The HTML ListView Essentials Sample..............................................................................................183Quickstart #2b: The ListView Grouping Sample ..........................................................................................................186ListView in the Grid App Project Template....................................................................................................................191The Semantic Zoom Control ...................................................................................................................................................195FlipView Features and Styling.................................................................................................................................................198Data Sources.................................................................................................................................................................................202A FlipView Using the Pictures Library..............................................................................................................................202Custom Data Sources............................................................................................................................................................204How Templates Really Work ...................................................................................................................................................205Referring to Templates .........................................................................................................................................................206Template Elements and Rendering ..................................................................................................................................206Template Functions (Part 1): The Basics..........................................................................................................................207ListView Features and Styling..................................................................................................................................................210When Is ListView the Wrong Choice?..............................................................................................................................210Options, Selections, and Item Methods..........................................................................................................................212Styling.........................................................................................................................................................................................215Backdrops..................................................................................................................................................................................216Layouts and Cell Spanning..................................................................................................................................................216Optimizing ListView Performance.........................................................................................................................................223Random Access........................................................................................................................................................................224Incremental Loading..............................................................................................................................................................225Template Functions (Part 2): Promises, Promises!.......................................................................................................225What We’ve Just Learned.........................................................................................................................................................2326
  7. 7. Chapter 6: Layout.....................................................................................................................233Principles of Windows Store App Layout............................................................................................................................234Quickstart: Pannable Sections and Snap Points ...............................................................................................................237Laying Out the Hub ...............................................................................................................................................................238Laying Out the Sections .......................................................................................................................................................239Snap Points ...............................................................................................................................................................................240The Many Faces of Your Display............................................................................................................................................241View States................................................................................................................................................................................242Handling View States............................................................................................................................................................245Screen Size, Pixel Density, and Scaling............................................................................................................................249Graphics That Scale Well .....................................................................................................................................................252Adaptive and Fixed Layouts for Display Size.....................................................................................................................253Fixed Layouts and the ViewBox Control.........................................................................................................................254Adaptive Layouts ....................................................................................................................................................................256Using the CSS Grid......................................................................................................................................................................258Overflowing a Grid Cell ........................................................................................................................................................260Centering Content Vertically ..............................................................................................................................................260Scaling Font Size.....................................................................................................................................................................261Item Layout ...................................................................................................................................................................................262CSS 2D and 3D Transforms .................................................................................................................................................263Flexbox .......................................................................................................................................................................................263Nested and Inline Grids........................................................................................................................................................264Fonts and Text Overflow......................................................................................................................................................266Multicolumn Elements and Regions ................................................................................................................................267What We’ve Just Learned.........................................................................................................................................................270Chapter 7: Commanding UI....................................................................................................271Where to Place Commands.....................................................................................................................................................272The App Bar ..................................................................................................................................................................................276App Bar Basics and Standard Commands......................................................................................................................278Command Events...................................................................................................................................................................2817
  8. 8. App Bar Events and Methods ............................................................................................................................................282Showing, Hiding, Enabling, and Updating Commands ............................................................................................284App Bar Styling........................................................................................................................................................................287Custom Icons...........................................................................................................................................................................288Command Menus...................................................................................................................................................................290Custom App Bars and Navigation Bars...........................................................................................................................291Flyouts and Menus......................................................................................................................................................................293WinJS.UI.Flyout Properties, Methods, and Events.......................................................................................................294Flyout Examples ......................................................................................................................................................................295Menus and Menu Commands............................................................................................................................................299Context Menus........................................................................................................................................................................301Message Dialogs..........................................................................................................................................................................303Improving Error Handling in Here My Am!........................................................................................................................305What We’ve Just Learned.........................................................................................................................................................309Chapter 8: State, Settings, Files, and Documents ................................................................311The Story of State........................................................................................................................................................................312Settings and State...................................................................................................................................................................314App Data Locations................................................................................................................................................................315AppData APIs (WinRT and WinJS) ....................................................................................................................................317Settings Containers................................................................................................................................................................318Versioning App State............................................................................................................................................................320Storage Folders and Storage Files....................................................................................................................................321The FileIO, PathIO, and WinJS helper classes (plus FileReader) .............................................................................325Encryption and Compression.............................................................................................................................................326Using App Data APIs for State Management................................................................................................................327Session State ............................................................................................................................................................................327Local and Temporary State.................................................................................................................................................328IndexedDB and Other Database Options ......................................................................................................................329Roaming State.........................................................................................................................................................................331Settings Pane and UI..................................................................................................................................................................3338
  9. 9. Design Guidelines for Settings...........................................................................................................................................334Populating Commands.........................................................................................................................................................336Implementing Commands: Links and Settings Flyouts..............................................................................................338Programmatically Invoking Settings Flyouts ................................................................................................................341User Data: Libraries, File Pickers, and File Queries...........................................................................................................343Using the File Picker ..............................................................................................................................................................344The File Picker UI....................................................................................................................................................................345The File Picker API (and a Few Friends)..........................................................................................................................348Media Libraries........................................................................................................................................................................352Documents and Removable Storage ...............................................................................................................................353Rich Enumeration with File Queries .................................................................................................................................354Here My Am! Update.................................................................................................................................................................360What We’ve Just Learned.........................................................................................................................................................361Chapter 9: Input and Sensors .................................................................................................363Touch, Mouse, and Stylus Input.............................................................................................................................................364The Touch Language, Its Translations, and Mouse/Keyboard Equivalents ........................................................366Edge Gestures..........................................................................................................................................................................370CSS Styles That Affect Input ...............................................................................................................................................371What Input Capabilities Are Present?..............................................................................................................................372Unified Pointer Events...........................................................................................................................................................374Pointer Capture.......................................................................................................................................................................377Gesture Events .........................................................................................................................................................................378Multipoint Gestures...............................................................................................................................................................383The Input Instantiable Gesture Sample ..........................................................................................................................384The Gesture Recognizer .......................................................................................................................................................386Keyboard Input and the Soft Keyboard ..............................................................................................................................388Soft Keyboard Appearance and Configuration............................................................................................................389Adjusting Layout for the Soft Keyboard.........................................................................................................................392Standard Keystrokes ..............................................................................................................................................................395Inking...............................................................................................................................................................................................3969
  10. 10. Geolocation...................................................................................................................................................................................398Sensors............................................................................................................................................................................................401What We’ve Just Learned.........................................................................................................................................................404Chapter 10: Media ...................................................................................................................405Creating Media Elements .........................................................................................................................................................406Graphics Elements: Img, Svg, and Canvas (and a Little CSS)........................................................................................408Additional Characteristics of Graphics Elements .........................................................................................................411Some Tips and Tricks.............................................................................................................................................................412Img Elements...........................................................................................................................................................................412Svg Elements............................................................................................................................................................................413Canvas Elements.....................................................................................................................................................................413Video Playback and Deferred Loading................................................................................................................................416Disabling Screen Savers and the Lock Screen During Playback.............................................................................418Video Element Extension APIs............................................................................................................................................419Applying a Video Effect........................................................................................................................................................420Browsing Media Servers .......................................................................................................................................................421Audio Playback and Mixing.....................................................................................................................................................421Audio Element Extension APIs ...........................................................................................................................................423Playback Manager and Background Audio...................................................................................................................424The Media Control UI............................................................................................................................................................428Playing Sequential Audio.....................................................................................................................................................429Playlists............................................................................................................................................................................................431Loading and Manipulating Media.........................................................................................................................................433Media File Metadata..............................................................................................................................................................434Thumbnails...............................................................................................................................................................................435Common File Properties......................................................................................................................................................435Media-Specific Properties ...................................................................................................................................................436Media Properties in the Samples......................................................................................................................................439Image Manipulation and Encoding..................................................................................................................................442Transcoding and Custom Image Formats......................................................................................................................44710
  11. 11. Manipulating Audio and Video.........................................................................................................................................448Transcoding..............................................................................................................................................................................448Custom Decoders/Encoders and Scheme Handlers...................................................................................................451Media Capture .............................................................................................................................................................................453Flexible Capture with the MediaCapture Object.........................................................................................................454Selecting a Media Capture Device....................................................................................................................................458Streaming Media and PlayTo..................................................................................................................................................460Streaming from a Server and Digital Rights Management (DRM)........................................................................461Streaming from App to Network......................................................................................................................................462PlayTo .........................................................................................................................................................................................463What We Have Learned............................................................................................................................................................466Chapter 11: Purposeful Animations ......................................................................................468Systemwide Enabling and Disabling of Animations........................................................................................................470The WinJS Animations Library................................................................................................................................................471Animations in Action.............................................................................................................................................................474CSS Animations and Transitions.............................................................................................................................................479The Independent Animations Sample.............................................................................................................................483Rolling Your Own: Tips and Tricks.........................................................................................................................................485What We’ve Just Learned.........................................................................................................................................................490Chapter 12: Contracts..............................................................................................................491Share................................................................................................................................................................................................493Source Apps..............................................................................................................................................................................495Sharing Multiple Data Formats .........................................................................................................................................499Custom Data Formats: schema.org..................................................................................................................................499Deferrals and Delayed Rendering ....................................................................................................................................500Target Apps ..............................................................................................................................................................................502Long-Running Operations ..................................................................................................................................................508Quicklinks..................................................................................................................................................................................510The Clipboard ..........................................................................................................................................................................512Search..............................................................................................................................................................................................51411
  12. 12. Search in the App Manifest and the Search Item Template....................................................................................516Basic Search and Search Activation..................................................................................................................................517Providing Query Suggestions.............................................................................................................................................520Providing Result Suggestions.............................................................................................................................................524Type to Search.........................................................................................................................................................................525Launching Apps: File Type and URI Scheme Associations............................................................................................525File Activation ..........................................................................................................................................................................527Protocol Activation.................................................................................................................................................................529File Picker Providers ...................................................................................................................................................................530Manifest Declarations............................................................................................................................................................531Activation of a File Picker Provider...................................................................................................................................533File Open Provider: Local File.............................................................................................................................................535File Open Provider: URI........................................................................................................................................................537File Save Provider: Save a File............................................................................................................................................538File Save Provider: Failure Case.........................................................................................................................................539Cached File Updater...................................................................................................................................................................539Updating a Local File: UI ......................................................................................................................................................542Updating a Remote File: UI.................................................................................................................................................544Update Events..........................................................................................................................................................................545Contacts..........................................................................................................................................................................................548Using the Contact Picker......................................................................................................................................................551Contact Picker Providers......................................................................................................................................................553What We’ve Just Learned.........................................................................................................................................................556Chapter 13: Tiles, Notifications, the Lock Screen, and Background Tasks .......................557Alive with Activity: A Visual Tour...........................................................................................................................................558The Four Sources of Updates and Notifications...............................................................................................................568Tiles, Secondary Tiles, and Badges ........................................................................................................................................570Secondary Tiles........................................................................................................................................................................571Creating Secondary Tiles .....................................................................................................................................................572App Activation From a Secondary Tile ...........................................................................................................................57412
  13. 13. Managing Secondary Tiles..................................................................................................................................................575Basic Tile Updates...................................................................................................................................................................576Choosing a Tile Template....................................................................................................................................................577Creating the Payload, Method 1: Populating Template Content..........................................................................580Creating the Payload, Method 2: XML Strings.............................................................................................................581Creating the Payload, Method 3: The Notifications Extensions Library..............................................................581Using Local and Web Images.............................................................................................................................................582Branding....................................................................................................................................................................................584Cycling, Scheduled, and Expiring Updates ....................................................................................................................585Badge Updates ........................................................................................................................................................................587Periodic Updates .........................................................................................................................................................................590Web Services for Updates....................................................................................................................................................592Using the Localhost................................................................................................................................................................595Windows Azure .......................................................................................................................................................................596Toast Notifications......................................................................................................................................................................599Creating Basic Toasts.............................................................................................................................................................600Butter and Jam: Options for Your Toast.........................................................................................................................602Tea Time: Scheduled Toasts................................................................................................................................................604Toast Events and Activation................................................................................................................................................606Push Notifications and the Windows Push Notification Service.................................................................................606Requesting and Caching a Channel URI (App).............................................................................................................608Managing Channel URIs (Service).....................................................................................................................................610Sending Updates and Notifications (Service)................................................................................................................610Raw Notifications (Service)..................................................................................................................................................612Receiving Notifications (App).............................................................................................................................................612Debugging Tips.......................................................................................................................................................................614Windows Azure Toolkit and Windows Azure Mobile Services................................................................................614Background Tasks and Lock Screen Apps...........................................................................................................................615Background Tasks in the Manifest....................................................................................................................................616Building and Registering Background Task...................................................................................................................61813
  14. 14. Conditions.................................................................................................................................................................................619Tasks for Maintenance Triggers.........................................................................................................................................620Tasks for System Triggers (Non-Lock Screen)...............................................................................................................622Lock Screen–Dependent Tasks and Triggers.................................................................................................................624Debugging Background Tasks...........................................................................................................................................627What We’ve Just Learned (Whew!) .......................................................................................................................................628Chapter 14: Networking..........................................................................................................630Network Information and Connectivity...............................................................................................................................631Network Types in the Manifest..........................................................................................................................................631Network Information (the Network Object Roster)....................................................................................................632The ConnectionProfile Object............................................................................................................................................634Connectivity Events................................................................................................................................................................634Cost Awareness........................................................................................................................................................................636Running Offline.......................................................................................................................................................................639XmlHttpRequest ..........................................................................................................................................................................642Background Transfer..................................................................................................................................................................643Basic Downloads .....................................................................................................................................................................644Basic Uploads...........................................................................................................................................................................647Breaking Up Large Files .......................................................................................................................................................648Multipart Uploads..................................................................................................................................................................649Providing Headers and Credentials..................................................................................................................................652Setting Cost Policy..................................................................................................................................................................652Grouping Transfers.................................................................................................................................................................653Suspend, Resume, and Restart with Background Transfers .....................................................................................653Authentication, Credentials, and the User Profile............................................................................................................655The Credential Picker UI.......................................................................................................................................................656The Credential Locker ...........................................................................................................................................................659The Web Authentication Broker........................................................................................................................................661Single Sign On .........................................................................................................................................................................665Single Sign On with Live Connect ....................................................................................................................................66714
  15. 15. The User Profile (and the Lock Screen Image) .............................................................................................................668Encryption, Decryption, Data Protection, and Certificates.......................................................................................670Syndication....................................................................................................................................................................................671Reading RSS Feeds .................................................................................................................................................................671Using AtomPub.......................................................................................................................................................................674Sockets............................................................................................................................................................................................675Datagram Sockets...................................................................................................................................................................676Stream Sockets ........................................................................................................................................................................680Web Sockets: MessageWebSocket and StreamWebSocket.....................................................................................683The ControlChannelTrigger Background Task .............................................................................................................687Loose Ends (or Some Samples To Go)..................................................................................................................................688What We’ve Just Learned.........................................................................................................................................................689Chapter 15: Devices and Printing ..........................................................................................690Using Devices................................................................................................................................................................................691The XInput API and Game Controllers............................................................................................................................692Enumerating Devices in a Class .........................................................................................................................................696Windows Portable Devices and Bluetooth Capabilities ............................................................................................698Near Field Communication and the Proximity API .........................................................................................................700Finding Your Peers (No Pressure!)....................................................................................................................................702Advertising a Connection....................................................................................................................................................703Making a Connection ...........................................................................................................................................................704Tap to Connect and Tap to Activate ...............................................................................................................................705Sending One-Shot Payloads: Tap to Share....................................................................................................................706Printing Made Easy.....................................................................................................................................................................707The Printing User Experience..............................................................................................................................................708Print Document Sources.......................................................................................................................................................711Providing Print Content and Configuring Options.....................................................................................................712What We’ve Just Learned.........................................................................................................................................................71515
  16. 16. Chapter 16: WinRT Components: An Introduction..............................................................716Choosing a Mixed Language Approach (and Web Workers)......................................................................................718Quickstarts: Creating and Debugging Components.......................................................................................................720Quickstart #1: Creating a Component in C#.................................................................................................................721Quickstart #2: Creating a Component in C++.............................................................................................................726Comparing the Results..........................................................................................................................................................729Key Concepts for WinRT Components ................................................................................................................................731Implementing Asynchronous Methods...........................................................................................................................733JavaScript Workers.................................................................................................................................................................734Async Basics in WinRT Components................................................................................................................................737Arrays, Vectors, and Other Alternatives..........................................................................................................................742Projections into JavaScript...................................................................................................................................................746Scenarios for WinRT Components.........................................................................................................................................748Higher Performance ..............................................................................................................................................................748Access to Additional APIs.....................................................................................................................................................750Obfuscating Code and Protecting Intellectual Property...........................................................................................752Library Components ..............................................................................................................................................................753Concurrency .............................................................................................................................................................................753What We’ve Just Learned.........................................................................................................................................................754Chapter 17: Apps for Everyone: Accessibility, World-Readiness,and the Windows Store...........................................................................................................755Your App, Your Business...........................................................................................................................................................757Side Loading.............................................................................................................................................................................758Planning: Can the App Be a Windows Store App?......................................................................................................760Planning for Monetization (or Not) .................................................................................................................................761Free Apps..................................................................................................................................................................................762Ad-Supported Apps ..............................................................................................................................................................763Paid Apps and Trial Versions..............................................................................................................................................764In-App Purchases ...................................................................................................................................................................766Revenue Sharing and Custom Commerce for In-App Purchases..........................................................................76716
  17. 17. The Windows Store APIs...........................................................................................................................................................768The CurrentAppSimulator Object .....................................................................................................................................770Trial Versions and App Purchase.......................................................................................................................................774Listing and Purchasing In-App Products........................................................................................................................776Receipts......................................................................................................................................................................................780Accessibility ...................................................................................................................................................................................781Screen Readers and Aria Attributes..................................................................................................................................784The ARIA Sample....................................................................................................................................................................785Handling Contrast Variations .............................................................................................................................................788CSS Styling for High Contrast ............................................................................................................................................790High Contrast Resources .....................................................................................................................................................793Scale + Contrast = Resource Qualifiers..........................................................................................................................794High Contrast Tile and Toast Images..............................................................................................................................795World Readiness and Localization.........................................................................................................................................795Globalization ............................................................................................................................................................................797User Language and Other Settings..................................................................................................................................798Formatting Culture-Specific Data and Calendar Math .............................................................................................801Sorting and Grouping...........................................................................................................................................................803Fonts and Text Layout ..........................................................................................................................................................803Preparing for Localization ...................................................................................................................................................805Part 1: Separating String Resources.................................................................................................................................805Part 2: Structuring Resources for the Default Language..........................................................................................813Creating Localized Resources: The Multilingual App Toolkit..................................................................................816Testing with the Pseudo Language..................................................................................................................................821Localization Wrap-Up ...........................................................................................................................................................823Releasing Your App to the World..........................................................................................................................................824Promotional Screenshots, Store Graphics, and Text Copy .......................................................................................824Testing and Pre-Certification Tools..................................................................................................................................825Onboarding and Working through Rejection ..............................................................................................................827App Updates.............................................................................................................................................................................82717
  18. 18. Getting Known: Marketing, Discoverability, and the Web.......................................................................................828Connecting Your Website ...................................................................................................................................................829Final Thoughts: Qualities of a Rock Star App...............................................................................................................829What We’ve Just Learned.........................................................................................................................................................831About the Author ....................................................................................................................833Survey Page..............................................................................................................................83418
  19. 19. IntroductionWelcome, my friends, to Windows 8! On behalf of the thousands of designers, program managers,developers, test engineers, and writers who have brought the product to life, Im delighted to welcomeyou into a world of Windows Reimagined.This theme is no mere sentimental marketing ploy, intended to bestow an aura of newness tosomething that is essentially unchanged, like those household products that make a big splash on theidea of "New and Improved Packaging!" No, Microsoft Windows truly has been reborn—after morethan a quarter-century, something genuinely new has emerged.I suspect—indeed expect—that youre already somewhat familiar with the reimagined userexperience of Windows 8. Youre probably reading this book, in fact, because you know that the abilityof Windows 8 to reach across desktop, laptop, and tablet devices, along with the global reach of theWindows Store, will provide you with tremendous business opportunities, whether youre in business, asI like to say, for fame, fortune, fun, or philanthropy.Well certainly see many facets of this new user experience throughout the course of this book. Ourprimary focus, however, will be on the reimagined developer experience.I dont say this lightly. When I first began giving presentations within Microsoft about buildingWindows Store apps, I liked to show a slide of what the world was like in the year 1985. It was the timeof Ronald Reagan, Margaret Thatcher, and Cold War tensions. It was the time of VCRs and the discoveryof AIDS. It was when Back to the Future was first released, Michael Jackson topped the charts withThriller, and Steve Jobs was kicked out of Apple. And it was when software developers got their firsttaste of the original Windows API and the programming model for desktop applications.The longevity of that programming model has been impressive. Its been in place for over aquarter-century now and has grown to become the heart of the largest business ecosystem on theplanet. The API itself, known today as Win32, has also grown to become the largest on the planet! Whatstarted out on the order of about 300 callable methods has expanded three orders of magnitude, wellbeyond the point that any one individual could even hope to understand a fraction of it. Id certainlygiven up such futile efforts myself.So when I bumped into my old friend Kyle Marsh in the fall of 2009 just after Windows 7 had beenreleased and heard from him that Microsoft was planning to reinvigorate native app development forWindows 8, my ears were keen to listen. In the months that followed I learned that Microsoft wasintroducing a completely new API called the Windows Runtime (or WinRT). This wasnt meant to replaceWin32, mind you; desktop applications would still be supported. No, this was a programming modelbuilt from the ground up for a new breed of touch-centric, immersive apps that could compete withthose emerging on various mobile platforms. It would be designed from the app developers point ofview, rather than the systems, so that key features would take only a few lines of code to implement19
  20. 20. rather than hundreds or thousands. It would also enable direct native app development in multipleprogramming languages. This meant that new operating system capabilities would surface to thosedevelopers without having to wait for an update to some intermediate framework. It also meant thatdevelopers who had experience in any one of those language choices would find a natural home whenwriting apps for Windows 8.This was very exciting news to me because the last time that Microsoft did anything significant to theWindows programming model was in the early 1990s with a technology called the Component ObjectModel (COM), which is exactly what allowed the Win32 API to explode as it did. Ironically, it was my roleat that time to introduce COM to the developer community, which I did through two editions of InsideOLE (Microsoft Press, 1993 and 1995) and seemingly endless travel to speak at conferences and visitpartner companies. History, indeed, does tend to repeat itself, for here I am again!In December 2010, I was part of the small team who set out to write the very first Windows Storeapps using what parts of the new WinRT API had become available. Notepad was the text editor ofchoice, we built and ran apps on the command line by using abstruse Powershell scripts that required usto manually type out ungodly hash strings, we had no documentation other than oft-incompletefunctional specifications, and we basically had no debugger to speak of other than the tried and truewindow.alert and document.writeln. Indeed, we generally worked out as much HTML, CSS, andJavaScript as we could inside a browser with F12 debugging tools, only adding WinRT-specific code atthe end because browsers couldnt resolve those APIs. You can imagine how we celebrated when we gotanything to work at all!Fortunately, it wasnt long before tools like Visual Studio Express and Blend for Visual Studio becameavailable. By the spring of 2011, when I was giving many training sessions to people inside Microsoft onbuilding apps for Windows 8, the process was becoming far more enjoyable and exceedingly moreproductive. Indeed, while it took us some weeks in late 2010 to get even Hello World to show up on thescreen, by the fall of 2011 we were working with partner companies who pulled together completeStore-ready apps in roughly the same amount of time.As weve seen—thankfully fulfilling our expectations—its possible to build a great app in a matter ofweeks. Im hoping that this ebook, along with the extensive resources on http://dev.windows.com, willhelp you to accomplish exactly that and to reimagine your own designs.Who This Book Is ForThis book is about writing Windows Store apps using HTML5, CSS3, and JavaScript. Our primary focuswill be on applying these web technologies within the Windows 8 platform, where there are uniqueconsiderations, and not on exploring the details of those web technologies themselves. For the mostpart, then, Im assuming that youre already at least somewhat conversant with these standards. We willcover some of the more salient areas like the CSS grid, which is central to app layout, but otherwise Itrust that youre capable of finding appropriate references for most everything else.20
  21. 21. Im also assuming that your interest in Windows 8 has at least two basic motivations. One, youprobably want to come up to speed as quickly as you can, perhaps to carve out a foothold in theWindows Store sooner rather than later. Toward that end, Ive front-loaded the early chapters with themost important aspects of app development along with "Quickstart" sections to give you immediateexperience with the tools, the API, and some core platform features. On the other hand, you probablyalso want to make the best app you can, one that performs really well and that takes advantage of thefull extent of the platform. Toward this end, Ive also endeavored to make this book comprehensive,helping you at least be aware of whats possible and where optimizations can be made. (Note, though,that the Store itself is discussed in Chapter 17.)Many insights have come 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 linesbringing those first apps to the Windows Store. This has involved writing bits of code for those apps andinvestigating bugs, along with conducting design, code, and performance reviews with members of theWindows engineering team. As such, one of my goals with this book is to make that deepunderstanding available to many more developers, including you!What Youll Need (Can You Say “Samples”?)To work through this book, you should have Windows 8 installed on your development machine, alongwith the Windows SDK and tools. All the tools, along with a number of other resources, are listed onDeveloper Downloads for programming Windows Store Apps. You’ll specifically need Microsoft VisualStudio Express 2012 for Windows 8. We’ll also acquire other tools along the way as we need them in thisebook. (Note that for all the screenshots 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 “Sample app pack” listed on this page, or visit Windows 8 app samplesand specifically download the SDK’s JavaScript samples. Well be drawing from many—if not most—ofthese samples in the chapters ahead, pulling in bits of their source code to illustrate how many differenttasks are accomplished.One of my secondary goals in this book, in fact, is to help you understand where and when to use thetremendous resources in what is clearly the best set of samples I’ve ever seen for any release ofWindows. You’ll often be able to find a piece of code in one of the samples that does exactly what youneed in your app or that is easily modified to suit your purpose. For this reason I’ve made it a point topersonally look through every one of the JavaScript samples, understand what they demonstrate, andthen refer to them in their proper context. This, I hope, will save you the trouble of having to do thatlevel of research yourself and thus make you more productive in your development efforts.In some cases I’ve taken one of the SDK samples and made certain modifications, typically todemonstrate an additional feature but sometimes to fix certain bugs or demonstrate a betterunderstanding that came about after the sample had to be finalized. I’ve included these modifications in21
  22. 22. the companion content for this book, which you can download athttp://go.microsoft.com/FWLink/?Linkid=270057That companion content also contains a few additional examples of my own, which I always refer toas “examples” to make it clear that they aren’t official SDK content. (I’ve also rebranded the modifiedsamples to make it clear that they’re part of this book.) I’ve written these to fill gaps that the SDKsamples don’t address, or to provide a simpler demonstration of a feature that a related sample showsin a more complex manner. You’ll also find many revisions of an app I call “Here My Am!” that we’ll startbuilding in Chapter 2 and refine throughout the course of this book. This includes localizing it into anumber of different languages by the time we reach the end.Beyond all this, you’ll find that the Windows 8 samples gallery as well as the Visual Studio samplegallery also lets you search and browse additional projects that have been contributed by otherdevelopers—perhaps also you! (On the Visual Studio site, by the way, be sure to filter on Windows Storeapps as the gallery covers all Microsoft platforms.) And of course, there will be many more developerswho share projects on their own.In this book I occasionally refer to posts on the Windows 8 App Developer blog, which is a goodresource to follow. I also recommend following the Windows Store for Developers blog for anyannouncements related to what is effectively your place of business. And if you’re interested in theWindows 8 backstory—that is, how Microsoft approached this whole process of reimagining theoperating system—check out the Building Windows 8 blog.A Formatting NoteThroughout this book, identifiers that appear in code, such as variable names, property names, and APIfunctions and namespaces, are formatted with a color and a fixed-point font. Here’s an example:Windows.Storage.ApplicationData.current. At times these fully qualified names—those that thatinclude the entire namespace—can become quite long, so it’s necessary to occasionally hyphenate thenacross line breaks, as in Windows.Security.Cryptography.CryptographicBuffer.convertString-ToBinary. Generally speaking, I’ve tried to hyphenate after a dot or between whole words but notwithin a word. In any case, these hyphens are never part of the identifier except in CSS where hyphensare allowed (as in -ms-high-contrast-adjust) and with HTML attributes like aria-label ordata-win-options.Occasionally, you’ll also see identifiers that have a different color, as in datarequested. Thesespecifically point out events that originate from Windows Runtime objects, for which there are a fewspecial considerations for adding and removing event listeners in JavaScript, as discussed toward theend of Chapter 3. I make a few reminders about this point throughout the chapters, but the purpose ofthis special color is to give you a quick reminder that doesn’t break the flow of the discussion otherwise.22
  23. 23. AcknowledgementsIn many ways, this isnt my book—that is, its not an account of my own experiences and opinions aboutwriting apps for Windows 8. Im serving more as a storyteller, where the story itself has been written bythe thousands of people in the Windows team whose passion and dedication have been a constantsource of inspiration. Writing a book like this wouldnt be possible without all the work thats gone intocustomer research; writing specs; implementing, testing, and documenting all the details; managingdaily builds and public releases; and writing again the best set of samples Ive ever seen for a platform.Indeed, the words in some sections come directly from conversations Ive had with the people whodesigned and developed a particular feature. Im grateful for their time, and I’m delighted to give thema voice through which they can share their passion for excellence with you.A number of individuals deserve special mention for their long-standing support of this project. Firstto Chris Sells, with whom I co-authored the earliest versions of this book and who is now leadingdevelopment efforts at Telerik. To Mahesh Prakriya, Ian LeGrow, Anantha Kancherla, Keith Boyd andtheir respective teams, with whom Ive worked closely, and to Keith Rowe, Dennis Flanagan, and UlfSchoo, under whom Ive had the pleasure of serving.Thanks also to Devon Musgrave at Microsoft Press, who put in many long hours editing my manylong chapters, many times over. My direct teammates, Kyle Marsh, Todd Landstad, Shai Hinitz, PatrickDengler, Lora Heiny, Leon Braginski, and Joseph Ngari have also been invaluable in sharing what theyvelearned in working with real-world partners. A special thanks goes to Kenichiro Tanaka of MicrosoftJapan, for always being the first one to return a reviewed chapter to me and for joyfully researchingdifferent areas of the platform whenever I asked. Many bows to you, my friend! Nods also to others inour international Windows Ecosystem teams who helped with localizing the Here My Am! app forChapter 17: Gilles Peingné, Sam Chang, Celia Pipó Garcia, Juergen Schwertl, Maaten Van De Dospoort,and Li-Qun Jia (plus Shai Hinitz on Hebrew).The following individuals all contributed to this book as well, with chapter reviews, answers to myquestions, deep discussions of the details, and much more. I’m grateful to all of you for your time andsupport :Shakil Ahmed Scott Dickens Kishore Kotteri Daniel Oliver Sam SpencerChris Anderson Tyler Donahue Victoria Kruse Jason Olson Ben SrourErik Anderson Brendan Elliott Nathan Kuchta Elliot H Omiya Adam StritzelAxel Andrejs Matt Esquivel Elmar Langholz Larry Osterman Shijun SunTarek Ayna David Fields Bonny Lau Rohit Pagariya Sou SuzukiArt Baker Erik Fortune Travis Leithead Ankur Patel Simon TaoAdam Barrus Jim Galasyn Chantal Leonard Harry Pierson Henry TappenMegan Bates Gavin Gear Cameron Lerum* Steve Proteau Chris TavaresTyler Beam Derek Gephard Brian LeVee Hari Pulapaka David Tepper23
  24. 24. Ben Betz Marcelo Garcia Gonzalez Jianfeng Lin Arun Rabinar Sara ThomasJohnny Bregar Sunil Gottumukkala Tian Luo Matt Rakow Ryan ThompsonJohn Brezak Scott Graham Sean Lyndersay Ramu Ramanathan Bill TicehurstJohn Bronskill Ben Grover David Machaj Ravi Rao Stephen ToubJed Brown Paul Gusmorino Mike Mastrangelo Brent Rector Tonu VanataluVincent Celie Rylan Hawkins Jordan Matthiesen Ruben Rios Jeremy ViegasRaymond Chen John Hazen Ian McBurnie Dale Rogerson Nick WaggonerRian Chung Jerome Holman Jesse McGatha Nick Rotondo David WashingtonArik Cohen Scott Hoogerwerf Matt Merry David Rousset Sarah WaskomJustin Cooperman Stephen Hufnagel Markus Mielke George Roussos Marc WautierMichael Crider Sean Hume Pavel Minaev Jake Sabulsky Josh WilliamsPriya Dandawate Mathias Jourdain John Morrow Perumaal Shanmugam Lucian WischikDarren Davis Damian Kedzierski Feras Moussa Edgar Ruiz Silva Kevin Michael WoleyJack Davis Suhail Khalid John Mullaly Karanbir Singh Charing WongRyan Demopoulos Daniel Kitchener Jan Nelson* Peter Smith Michael Ziller* For Jan and Cameron, a special acknowledgement for riding down from Redmond, Washington, to visit me inPortland, Oregon (where I was living at the time), and sharing an appropriately international Thai lunch while wediscussed localization and multilingual apps.I would also like to bid adieu to the extra pounds that have accompanied my body while I’ve beensitting at a computer far more than I should! I’m sure you’re looking forward to a resumption in ourmore usual fitness routines as I am.Finally, special hugs to my wife Kristi and our young son Liam (now six), who have lovingly beenthere the whole time and who dont mind my traipsing through the house to my office either late atnight or early in the morning.Errata & Book SupportWe’ve made every effort to ensure the accuracy of this ebook and its companion content. Any errorsthat are reported after the book’s publication will be listed on our Microsoft Press site at oreilly.com. Atthat point, you can search for the book at http://microsoftpress.oreilly.com and then click the“View/Submit Errata” link. If you find an error that is not already listed, you can report it to us throughthe same page.If you need additional support, email Microsoft Press Book Support at mspinput@microsoft.com.Please note that product support for Microsoft software is not offered through the addresses above.24
  25. 25. Support for developers, however, can be found on the Windows Developer Center’s support section,especially in the Building Windows Store apps with HTML5/JavaScript forum. There is also an activecommunity on Stack Overflow for the windows8 and winrt tags.We Want to Hear from YouAt Microsoft Press, your satisfaction is our top priority, and your feedback our most valuable asset.Please tell us what you think of this book athttp://aka.ms/tellpressThe survey is short, and we read every one of your comments and ideas. Thanks in advance for yourinput!Stay in TouchLet’s keep the conversation going! We’re on Twitter: http://twitter.com/MicrosoftPress. And you cankeep up with Kraig here: http://www.kraigbrockschmidt.com.25

×