Whether you’re an existing Microsoft Silverlight developer wanting to branch out into the mobile space, an existing mobile developer looking to extend your reach across a second or third
Trang 3Windows® Phone 7
Development Internals
Andrew Whitechapel
Trang 4Published with the authorization of Microsoft Corporation by:
O’Reilly Media, Inc
1005 Gravenstein Highway North
Sebastopol, California 95472
Copyright © 2012 by Andrew Whitechapel
All rights reserved No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher
ISBN: 978-0-7356-6325-1
1 2 3 4 5 6 7 8 9 LSI 6 5 4 3 2 1
Printed and bound in the United States of America
Microsoft Press books are available through booksellers and distributors worldwide If you need support related
to this book, email Microsoft Press Book Support at mspinput@microsoft.com Please tell us what you think of this book at http://www.microsoft.com/learning/booksurvey
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 of
their respective owners
The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred
This book expresses the author’s views and opinions The information contained in this book is provided without any express, statutory, or implied warranties Neither the authors, O’Reilly Media, Inc., Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly
or indirectly by this book
Acquisitions Editor: Russell Jones
Developmental Editor: Russell Jones
Production Editor: Melanie Yarbrough
Editorial Production: Octal Publishing, Inc.
Technical Reviewer: Peter Torr
Copyeditor: Bob Russell
Indexer: WordCo Indexing Services
Cover Design: Twist Creative • Seattle
Cover Composition: Karen Montgomery
Illustrator: Robert Romano
Trang 5Contents at a Glance
Foreword xvii Introduction xix
PART II APPlICATIon MoDEl
PART III ExTEnDED sERvICEs
PART Iv vERsIon 7.5 EnhAnCEMEnTs
ChAPter 15 Multi-tasking and Fast App Switching 553
Trang 7Foreword xvii
Introduction xix
PART I BuIlDIng BloCks Chapter 1 vision and Architecture 3 Windows Phone Vision .3
Metro 4
Developer Guidelines 7
Windows Phone Architecture 8
Comparison of Silverlight and XNA 9
Developer Tools 10
Development Cycle 11
The Anatomy of a Basic Windows Phone Application .13
XAP Contents 14
Standard Project Types .15
Themes and Accent Colors 17
Standard Application Images 22
Version 7 vs Version 7.1 24
Summary .27
Chapter 2 uI Core 29 Phone UI Elements 29
Standard UI Elements 29
Visual Tree 32
Screen Layout 38
UserControl vs Custom Control 41
Routed Events 44
Resources 47
Content vs Resource 48
Resource Dictionaries 49
Trang 8Dependency and Attached Properties 54
Dependency Properties .54
Attached Properties 56
Summary .59
Chapter 3 Controls 61 Standard Controls 61
Platform, SDK, Toolkit 61
SDK Controls: Pivot .63
SDK Controls: Panorama 69
Toolkit Controls .78
Transient Panels 81
Summary .89
Chapter 4 Data Binding and layer Decoupling 91 Life without Data Binding 91
Simple Data Binding and INotifyPropertyChanged .94
Data Binding Collections 98
Data Templates 100
Dynamic Data-Bound Collections 103
Template Resources 105
Type/Value Converters 106
Element Binding 108
Data Validation 110
Separating Concerns .113
Design-Time Data .115
The Model-View ViewModel Pattern 117
The Visual Studio Databound Application Project 124
Summary .133
Trang 9Chapter 5 Touch uI 135
Logical Touch Gestures .135
Manipulation Events: Single Touch (Tap) .138
Manipulation Events: Single Touch (Flick) 140
Manipulation Events: Multi-Touch 142
Mouse Events 144
FrameReported Events 147
Combining Manipulation and Mouse Events 148
Click vs Mouse/Manipulation Events 150
The Silverlight Toolkit GestureService 150
Pinch and Drag 152
Flick and Tap 153
Problems with the GestureService 154
Behaviors 155
Keyboard Input 159
Orientation .162
The Application Bar .167
Summary .172
PART II APPlICATIon MoDEl Chapter 6 Application Model 175 Lifetime Events and Tombstoning 175
Application Closing 180
Application Deactivated .181
Application Deactivated (the Non-Tombstone Case) .183
Unhandled Exceptions 185
Why Is There No App.Exit? 186
Obscured and Unobscured .186
Launchers/Choosers and Tombstoning 189
User Expectations 189
Trang 10Page Model 190
Page Creation Order 195
Summary .198
Chapter 7 navigation state and storage 199 Navigation and State 199
Application and Page State 200
Detecting Resurrection 207
Navigation Options .209
Using NavigateUri 209
Pages in Separate Assemblies 210
Fragment and QueryString 211
The NavigationMode Property .214
Rerouting Navigation and URI Mappers 215
Nonlinear Navigation Service .217
Isolated Storage .220
Simple Persistence 221
Persisting the ViewModel 225
Serialization Options 229
Isolated Storage Helpers 237
Summary .241
Chapter 8 Diagnostics and Debugging 243 Visual Studio Debugging 243
Simple Diagnostics 244
Setting Up a Diagnostics Pop-Up Window 244
Fixed Diagnostics Control 249
Post-Release Diagnostics .251
Persisting Logs 253
Configurable Diagnostics 255
Screen Capture 259
Emulator Console Output 261
Debugging Tombstoning and Lock-Screen 263
Debugging MediaPlayer 264
Trang 11Device and User Information 267
Windows Phone Performance Counters 271
Memory Diagnostics 273
The Device Emulator 278
Emulator vs Device 279
XDE Automation 280
Using the Microsoft Network Monitor 283
Fiddler 285
Silverlight Spy .287
Summary .288
PART III ExTEnDED sERvICEs Chapter 9 Phone services 291 Phone Hardware 291
Launchers and Choosers 293
Photo Extras .297
Accelerometer 301
Reactive Extensions for NET 304
Level Starter Kit .307
Shake 311
Geo-Location 314
Summary .318
Chapter 10 Media services 319 Audio and Video Hardware 319
Audio and Video APIs .320
Media Playback 320
The MediaPlayerLauncher Class 321
The MediaElement Class 321
The MediaStreamSource and ManagedMediaHelpers Classes 323
MediaElement Controls 325
Trang 12Audio Input and Manipulation 328
The SoundEffect and SoundEffectInstance Classes 329
Audio Input and the Microphone 331
The DynamicSoundEffectInstance Class 339
Music and Videos Hub 343
The FM Tuner 345
Summary .348
Chapter 11 Web and Cloud 349 The WebClient Class 349
WebClient: The DownloadStringAsync Method .349
WebClient: The OpenReadAsync Method 351
The HttpWebRequest Class 353
Web Browser Control 353
Silverlight and Javascript 355
Web Services 358
WCF Data Services 361
The OData Client and XML Data 361
JSON-Formatted Data 369
Bing Maps and Geolocation 372
Using the Map Control 372
Geolocation 374
Bing Maps Web Services 375
Deep Zoom (MultiScaleImage) 378
Windows Azure 383
Windows Azure Web Services 385
Windows Azure Toolkit for Windows Phone 390
bitly 394
Facebook .396
Windows Live 400
SkyDrive 405
Summary .407
Trang 13Chapter 12 Push Notifications 409
Architecture 409
Push Notification Server .412
Push Notification Client 418
Additional Server Features .423
Batching Intervals 423
XML Payload 424
Response Information 426
Additional Client Features 427
Persistent Client Settings .427
The ErrorOccurred Event 428
User Opt-In/Out 429
Implementing a Push ViewModel 431
The Push Notification Server-Side Helper Library 437
Common Push Notification Service 439
Summary .443
Chapter 13 security 445 Device Security 445
Application Safeguards 446
Application Deployment 447
Managed Code Constraints 449
Chambers and Capabilities 451
Missing Security Features 454
Data Encryption 455
SDL Tools .460
Threat Modeling 461
Static Code Analysis/FxCop 462
Web Service Security 467
Authentication 468
Forms Authentication 468
Basic Authentication 479
SSL 484
Trang 14Push Notification Security 490
OAuth 1.0 491
OAuth 2.0 493
Securing Web Service IDs 494
Implementing Security for the WebBrowser Control 496
Summary .497
Chapter 14 go to Market 499 Threading 499
Performance .505
UI vs Render Thread, and BitmapCache Mode 505
UI Layout and ListBoxes 512
More UI Performance Tips 513
Non-UI Performance Tips 515
Silverlight Unit Testing Framework .517
Certification and Publication .523
Updates 530
Marketplace Reports 533
Beta Testing 534
Versions 534
Light-Up Features 535
Obfuscation 537
Ads 540
Trial Mode 544
Silverlight Analytics Framework 546
Summary .549
Trang 15PART Iv vERsIon 7.5 EnhAnCEMEnTs
Fast Application Switching .553
Multi-Tasking 557
Alarms and Reminders 558
Alarms .558
Reminders 561
Background Transfer Service 564
Generic Background Agents 568
Background Audio 578
Background Audio: The Main Application 583
Background Audio: The Background Agent 585
Summary .587
Chapter 16 Enhanced Phone services 589 Sensor APIs 589
Accelerometer .590
Compass .593
Gyroscope 598
Motion APIs 601
Camera Pipeline .606
Augmented Reality 610
The Geo Augmented Reality Toolkit .614
New Photo Extensibility 616
Launcher and Chooser Enhancements 619
The DeviceStatus and DeviceNetworkInformation classes 621
Version 7.1.1 623
Summary .626
Trang 16Chapter 17 Enhanced Connectivity Features 627
Push, Tile, and Toast Enhancements 627
Local Tiles .628
Pinning Tiles 632
Push Enhancements 638
Sockets 642
TCP Sockets 643
OData Client 650
Search Extensibility 657
App Connect .657
App Instant Answer 664
Summary .665
Chapter 18 Data support 667 Local Database and LINQ-to-SQL 667
Create and Read 669
Update and Delete 675
Schema Updates 677
Associations 681
Isolated Storage Explorer Tool 684
Performance Considerations 692
Database Encryption 695
Encrypting Data and Credentials 697
Contacts and Calendar 699
Sync Framework .703
Service Configuration 705
Database Provisioning 707
Code Generation 707
Summary .710
Trang 17Chapter 19 Framework Enhancements 711
Navigation Enhancements 711
Frame and Page Navigation 711
Backstack Management 714
UI Enhancements .717
Enhanced Controls 718
The ApplicationBar and SystemTray Classes, and the ProgressIndicator Property .723
The Clipboard API .727
32 Bits per Pixel .728
Background Image Decoding 729
Touch Thread .729
Silverlight 4.0 730
Implicit Styles 730
Command Binding 732
Data-Binding Enhancements 736
Summary .744
Chapter 20 Tooling Enhancements 745 Emulator Improvements .745
Debugger Experience 747
Marketplace Test Kit 749
The Profiler 754
UserVoice Forums 764
Portable Library Tools .765
Async Framework 769
Summary .772
Index 773
Trang 19So, you’re curious about Windows Phone development? Welcome aboard! Whether you’re an
existing Microsoft Silverlight developer wanting to branch out into the mobile space, an existing
mobile developer looking to extend your reach across a second or third ecosystem, a rising star who’s
ready to create the Next Big Thing and take the world by storm, or maybe just a curious phone user
who wants to know what all the “app” fuss is about, Windows Phone is the platform for you
Getting started with Windows Phone development is free and easy; everything you need to write
apps is just a couple of clicks away You can have your first app up and running in a matter of minutes,
even if you know next to nothing about Windows Phone development or don’t even own a device As
your apps become more ambitious and you encounter more complex development issues, a vibrant
developer community on the web is ready and willing to help you out along the way Mastery of this
platform, with its rich feature set, unique application model, integrated end-to-end experiences, and
burgeoning international marketplace, takes time and effort—and an expertly written guide Luckily
for you, this book is just such a guide
The Windows Phone platform stands on the shoulders of giants—giants such as Silverlight, XNA,
Microsoft Visual Studio, and Microsoft Expression Blend—and as we built the platform, we embraced
the power and familiarity that these existing technologies afforded us; our goal was to introduce new
concepts only when strictly necessary to enable new scenarios, and to re-use existing concepts
every-where else We spent less time re-solving old problems (such as navigation and microphone capture)
and more time tackling new ones so that we could ship a vast array of new phone-specific APIs for
developers to wrap their heads around—cameras, gyroscopes, multi-tasking, phone integration, user
data access, and live tile updates, just to name a few—and Andrew covers all of them (and more!) in
this book
As you’ve probably heard (and seen), Windows Phone ushered in a new design language for
Microsoft, code-named “Metro.” Adhering closely to this design is critical when building user
experi-ences that will delight and engage your customers As you would expect, the Windows Phone
devel-oper tools give you a big helping hand in this department, providing user interface elements and
ap-plication templates that “just work” by default Nevertheless, as the owner of your apap-plication’s overall
experience you are ultimately responsible for ensuring it performs optimally, adhering not just to the
graphic design rules, such as “content over chrome,” but also the fast and fluid interaction model that
your customers will come to expect Throughout this book you’ll find practical examples and
guid-ance that show how to embody the Metro design language in your applications, along with examples
of common pitfalls and how to avoid them—particularly with respect to application performance and
responsiveness, which are key factors in user satisfaction (and hence, app ratings and profitability)
Trang 20On a more personal note, I was thrilled when Andrew asked me to tech-review this book (although writing this foreword was more than a little daunting!) As an infrastructure guy at heart, I love build-ing platforms and enabling developers to be successful on top of them, but there are only so many people you can reach via blogs or conference speaking sessions I’ve been asked to author books before, but I've never had the time or inclination to do so By piggybacking on Andrew’s hard work with this book, I feel like I’ve made a difference—if only a small one—and that makes me grateful for the opportunity I also learned a lot while reviewing this book, and I know that you will, too.
Peter Torr
Program Manager in the Windows Phone Application Platform team
Trang 21The smart phone is increasingly important in people’s daily lives It is used for a wide variety of
tasks, both work-related and non-work related People use smart phones to keep up to date
with friends and family, for relaxation, and for entertainment, as well as for viewing documents and
spreadsheets, surfing the Internet, and enriching their lives There is therefore considerable scope
for building smart phone applications Windows Phone is not just another smart phone; rather, it is
positioned as an opportunity for developers to build applications that can make a real difference to
people’s lives The platform has been designed from the ground up to support an all-encompassing,
integrated, and attractive user experience
Windows Phone 7 Development Internals covers the breadth of application development for the
Windows Phone platform, both the major 7 and 7.1/7.5 versions and the minor 7.1.1 version, and
shows how you can build such compelling and useful applications You can build applications for
Windows Phone 7.x by using either the Microsoft Silverlight runtime or the XNA runtime This book
focuses on Silverlight applications The primary development and design tools are Microsoft Visual
Studio and Microsoft Expression Blend Here again, this book focuses on Visual Studio
Each chapter covers a handful of related features For each feature, the book provides one or more
sample applications and walks you through the significant code (C# and XAML) This will help you
to understand the techniques used and also the design and implementation choices that you have
in each case Potential pitfalls are called out, as are scenarios in which you can typically make
per-formance or user experience improvements An underlying theme is to conform not only to the user
interface design guidelines, but also to the notion of a balanced, healthy phone ecosystem
Who should Read This Book
This book is intended to help existing developers understand the core concepts, the significant
pro-grammable feature areas, and the major techniques in Windows Phone development The book is
tai-lored for existing Silverlight developers that want to jump into the exciting world of mobile application
developer with the Windows Phone platform Developers experienced with other mobile platforms
will find this book invaluable in learning the ins and outs of Microsoft’s operating system, but will
likely need additional resources to pick up C# and XAML languages
The Windows Phone 7 release only supports C#, and although support for Visual Basic was
intro-duced with the 7.1 SDK, this book focuses purely on C# and XAML The basic architecture of the
platform is covered in Chapter 1, “Vision and Architecture,” and most chapters go deeply into the
internal behavior of the system This is knowledge that helps to round out your understanding of the
platform, and inform your design decisions, even though, in some cases, the internal details have no
immediate impact on the exposed API
Trang 22The book assumes that you have a reasonable level of experience of developing in managed code, specifically in C# Basic language constructs are not discussed, nor is basic use of Visual Studio, the project system or the debugger, although more advanced techniques, and phone-specific features are, of course, explained in detail You should also have some knowledge of XAML development, preferably in Silverlight, although Windows Presentation Foundation experience would also be useful background
Although many component-level diagrams are presented as high-level abstractions, there are also many sections that describe the behavior of the feature in question through the use of UML sequence diagrams It helps to have an understanding of sequence diagrams, but it is not essential, as they are fairly self-explanatory
Who should not Read This Book
This book is not intended for use by application designers—if designers are defined as developers who use Expression Blend—although designers might find it useful to understand some of the issues facing developers in the Windows Phone application space The book is also not suitable for XNA developers because it does not cover game development at all
organization of This Book
Windows Phone 7 was first released in October 2010 The first major update, code-named “Mango,” was released in September 2011 The Mango release includes a wide range of enhancements and additional features Note that the user-focused version number for the Mango release (that is, the product version) is version 7.5; however, the developer-focused number is 7.1 (for both the OS version and the SDK version) The reason for this slightly confusing numbering situation is that the Mango release includes improvements across the board—in the operating system, the developer tooling, in the emulator, in the application platform, in Silverlight itself, and also in the server-side experience
of marketplace, and in ingestion All of this is Windows Phone, or Windows Phone 7.5 A developer is normally focused more on the pure technical aspects: the operating system, tooling, and application platform subset of the overall release, and that is technically the 7.1 release (both SDK and OS).This book covers all 7.x versions: the original Windows Phone 7 release, the later Windows Phone 7.1 release, and the minor 7.1.1 release Applications built for version 7 also work without change on 7.1 devices Note that, while there are still about a million version 7 phones in use, it is safe to assume that most of these will be upgraded to 7.1 at some point However, to keep things simple, the first
14 chapters focus on the basic infrastructure, programming model, and the core features that are common to both versions Where there are material differences, these are called out, with references
to the later chapter where the 7.1 behavior is explained in detail Chapter 15, “Multi-Tasking and Fast App Switching,” onward focuses on the features and platform enhancements that are specific
to version 7.1
Trang 23The 7.1.1 version is a narrowly scoped release intended to support phones with low memory capabilities (256 MB) for specific target markets Most developers—and most applications—will not
be affected by this For the small number that might be affected, the 7.1.1 release provides additional support for performance tuning and an additional marketplace submission option, as discussed in Chapter 16, “Enhanced Phone Services.”
It’s also worth reading Chapter 14, “Go To Market” ahead of time This chapter focuses on the end-game of bringing your application to market, including tuning the design for performance and robustness, and marketplace certification Even before you have a thorough understanding of the architecture and fundamentals, it is instructive to see what you’ll be aiming for
Conventions and Features in This Book
This book presents information by using conventions designed to make the information readable and easy to follow
■
■ In some cases, especially in the early chapters, application code is listed in its entirety More often, only the significant code is listed Wherever code has been omitted for the sake of brev-ity, this is called out in the listing In all cases, you can refer to the sample code that accompa-nies this book for complete listings
■
■ In the XAML listings, attributes that are not relevant to the topic under discussion, and that have
already been explained in previous sections, are omitted This applies, for example, to Grid.Row, Grid.Column, Margin, FontSize, and similarly trivial attributes In this way, you can focus on the
elements and attributes that do actually contribute to the feature at hand, without irrelevant distractions
■
■ A vertical bar between two or more menu items (for example, File | Close), means that you should select the first menu or menu item, then the next, and so on
Trang 24system Requirements
You can build and run the accompanying sample code, or you can create your own solutions from scratch, following the instructions in the text In either case, you will need the following hardware and software to create the sample applications in this book:
■
■ Either Windows Vista (x86 and x64) with Service Pack 2, all editions except the Starter Edition,
or Windows 7 (x86 and x64), all editions except the Starter Edition If you install the Windows Phone SDK 7.1.1 Update, this also works with the Windows 8 Consumer Preview, although this
is not a supported configuration
■
■ The Windows Phone SDK version 7.0 or 7.1 These are both free downloads that include Visual Studio 2010 Express Edition and all other standard tools, as listed in Chapter 1 If you install the SDK version 7.1, you can then also upgrade this with the SDK version 7.1.1 This is an update to 7.1, not a stand-alone install
Depending on your Windows configuration, you might require Local Administrator rights to install
or configure Visual Studio 2010, and to install or configure features such as Internet Information Services, if not already installed
For the latest requirements, visit the Windows Phone SDK download page at http://www.microsoft com/download/en/details.aspx?id=27570.
Trang 25Code samples
All of the chapters in this book include multiple sample solutions with which you can interactively try out new material learned in the main text All sample projects can be downloaded from the following page:
http://go.microsoft.com/FWLink/?Linkid=248889
Follow the instructions to download the WP7xDevInternals.zip file
Installing the Code Samples
Follow these steps to install the code samples on your computer so that you can refer to them while learning about the techniques that they demonstrate
1 Unzip the WP7xDevInternals.zip file that you downloaded from the book’s website to any able folder on your local hard disk The sample code expands out to nearly 200 MB, and you will need even more space for the binaries if you choose to build any of the samples
suit-2 If prompted, review the displayed end-user license agreement If you accept the terms, select the accept option, and then click Next
Note If the license agreement doesn’t appear, you can access it from the same webpage
from which you downloaded the WP7xDevInternals.zip file
Using the Code Samples
When you unzip the sample code, this creates a number of subfolders, one for each chapter Within each chapter’s subfolder there are further subfolders In most cases, there is one subfolder per applica-tion (or per version of an application), but in some cases, multiple applications are grouped together; for example, where there is a server-side application as well as a client-side application in the solution
In keeping with the book's structure, the samples for the first 14 chapters were built as version 7 ects, and the remaining samples were built as version 7.1 projects However, you can use the version 7.1 (or 7.1.1) SDK for all the sample projects, for all chapters
proj-All of the samples are complete, fully functioning applications Note, however, that in some cases, you might need to update assembly references, depending on where you install the SDK as well as where you install supplementary libraries and frameworks that don’t ship with the main SDK (for instance the Silverlight toolkit, Live SDK, Azure toolkit, and so on)
For samples that demonstrate the use of some supplementary framework, you will need to load and install that framework so that you can reference its assemblies Also note that, in some cases, this requires a user ID, such as for Bing maps, FaceBook, or Google Analytics, as described in the relevant sections In all cases, you can sign up for the ID without charge as of the time of this writing
Trang 26The Windows Phone development space is truly inspiring, and the Windows Phone teams at Microsoft are chock-full of smart, helpful people The list of folks who helped me prepare this book is very long I’d particularly like to thank Peter Torr for doing all the heavy lifting in the technical review It’s mainly thanks to Peter that this book isn’t riddled with schoolboy errors In addition, I’d like to thank all the other people who answered my dumb questions, and corrected my various misinterpretations of the internal workings of the platform, especially Tim Kurtzman, Wei Zhang, Jason Fuller, Vij Vasu, Abolade Gbadegesin, Andrew Clinick, Darin Miller, Mark Paley, Jeff Wilcox, Thomas Fennel, Matt Klupchak, Alper Selcuk, Gary Lin, Conrad Chang, Justin Horst, Sai Prasad Patro, Yasser Shaaban, Mike Battista, Jorge Raastroem, and Joao Guberman Raza I’d also like to thank the folks at O’Reilly Media and Mi-crosoft Press who helped to turn my scattered thoughts into polished prose, especially Russell Jones, Devon Musgrave, Melanie Yarbrough, and Bob Russell (at Octal Publishing, Inc.) Finally, none of this would have been possible without the patience and support of Narins Bergstrom
Errata & Book support
We’ve made every effort to ensure the accuracy of this book and its companion content Any rors that have been reported since this book was published are listed on our Microsoft Press site at oreilly.com:
er-http://go.microsoft.com/FWLink/?Linkid=248888
If you find an error that is not already listed, you can report it to us through the 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
We Want to hear from You
At Microsoft Press, your satisfaction is our top priority, and your feedback our most valuable asset Please tell us what you think of this book at:
Trang 27Part I
Building Blocks
ChAPTER 1 Vision and Architecture 3 ChAPTER 2 UI Core .29 ChAPTER 3 Controls 61 ChAPTER 4 Data Binding and Layer Decoupling .91 ChAPTER 5 Touch UI .135
This part describes the overall vision and architecture of Windows Phone applications, and the basic building blocks that every application requires in order to support minimum functionality
This includes the core user interface features, the various dard controls, touch manipulation, and data-binding
Trang 29stan-C h A P T E R 1
Vision and Architecture
There are two dimensions to this chapter: an introduction to the vision of the Windows Phone
plat-form and the revolutionary Metro design philosophy, and an introduction to the basic
architec-ture and building blocks of a Windows Phone application The vision is extremely important; it should
inform the way you think about applications, from first concept through design to implementation
and final publication The application platform provides support and guidance, such that it’s quite
difficult to build a truly bad application, but it is definitely possible to build an application that is in
conflict with the system and fails to provide a good user experience (UX) An understanding of the
vision should steer you toward good design choices and help you to identify potential pitfalls, thereby
accelerating your development cycle
Windows Phone vision
“Windows Phone is a software platform that can improve a person’s life.” This is a quote from the
Microsoft User Experience Design Guidelines (kept up-to-date online at http://msdn.microsoft.com/
en-us/library/hh202915(VS.92).aspx) It is a philosophy on which the teams that are responsible for
building the Windows Phone operating system, application platform, and SDK are highly focused
It’s not just marketing-speak, and it’s not just an inspirational motto—it really does speak to the core
vision of the platform
Traditional desktop operating systems such as Windows 7 and Mac OS are used for all sorts of
rea-sons and purposes, but predominantly for work-related activities So applications built for the desktop
(including browser clients for web applications) are typically business-focused (although
buttoned-down PCs are also increasingly being used for social networking applications like Facebook)
Applica-tions for Microsoft Xbox and other game consoles are predominantly geared toward entertainment
The idea behind the Windows Phone UX model is that this is a device that users turn to for
every-thing—for work and play, for keeping in touch with friends and family, for relaxation, games, music
and videos, for research and fact-finding—in short, for enhancing their day-to-day lives As
develop-ers, you have the weighty responsibility of living up to this vision You are encouraged (and extensively
supported through the application platform) to build applications that do improve the user’s life.
A good Windows Phone application is engaging, compelling, and attractive to the user A great
Windows Phone application can make a meaningful contribution to the user’s life The user
interac-tion is well thought out, predictable, and familiar It gives him enjoyment every time he uses it, or it
fulfills some pragmatic need in a simple, unobtrusive manner The application integrates seamlessly
Trang 30with standard features on the phone, such as email, contacts, photos, and so on It’s a ”team player,” cooperating with the system It’s conservative in its use of CPU, memory, and sensor resources It doesn’t consume battery power in an unbounded way, and it is thoughtful about its use of the user’s data plan The application should have a way to keep itself up-to-date so that its data is always fresh
It can also be location-aware; this way, it can ensure that it is always relevant to the user’s context, and functions in the smart way that user’s expect from a “smart” phone
A good application should also look and feel like it’s a part of the overall phone ecosystem, using the Metro design guidelines in an appropriate way, so that it doesn’t jar the senses or look out of place The same applies to navigation and the way the application behaves when the user switches away from it, and perhaps comes back to it later It should be configurable, so that the user can per-sonalize it, just as he can personalize other parts of the phone experience, such as the Start page, the theme, and accent colors There should be a way for the user to provide feedback to the developer, to report bugs, or to request new features The user should be able to consider the phone as an exten-sion of his personality, configured the way he likes it, and tailoring the set of installed applications to suit his own personal needs and preferences
Metro
Metro is the code name for the design language used in establishing the UX for Windows Phone Metro is modern and clean, light, open, and fast Metro is alive and in motion—hence, the extensive use of page transition animations and the considerable thought that has gone into perfecting the standard animations to provide a visually pleasing experience Consider just one feature: when the user swipes to scroll through a list, the scrolling speed closely matches the force of the swipe gesture
It responds immediately when the user holds a finger on the screen to stop the scrolling If the user drags a list down (or up) to its limits, there’s a visible compression effect, which provides clear feed-back that she’s reached the end of the list When she releases her finger, the compression bounces back in a pleasing and intrinsically recognizable way that makes the phone seem almost organically alive The standard animations have all been designed to provide just the right level of feedback—again, in a pleasing way, without becoming intrusive or distracting
You are encouraged to use the Metro design style for your application Metro covers all aspects
of the user interface (UI), including the use of space, control styles, and typography Content is seen
as an important part of any application; this is in deliberate and emphatic contrast to chrome (that
is, artifacts of the UI that allow the user to manipulate the UI, such as buttons and grab-handles that are presented in addition to the actual content) Other phone platforms focus a lot on chrome—shiny buttons, gradient fills, 3D images, arbitrary custom animations, and so on All these chrome effects might seem entertaining for a brief period, but they soon become a distraction, and they also lead to
a cluttered, inconsistent, confusing UI By contrast, Windows Phone and Metro considers content to
be king, whereas chrome should always be unobtrusive: it should serve its purpose, and then get out
of the user’s way Think about the implementation of the system tray; most of the time, this is invisible
If the user wants to see it, she taps the top of the screen, the tray drops down with a slight bounce, stays around long enough for the user to see the information she needs, and then disappears, leaving
Trang 31the screen free for the application It also has no shiny, colorful, arbitrarily animated distractions The same applies for the application bar.
The aim is to achieve a UI that looks and feels clean, light, and open Figure 1-1 shows an example
of a panorama-based application in the spirit of Metro: clean lines, no gradient fills, content-driven
FIguRE 1-1 Metro applications should be clean and open
This really represents a major shift in the way you design applications What you might call the
“90s aesthetic” was all about iconography, whereby the chrome took center stage, and the model was hyper-realistic Metro brings a content-focused aesthetic, through which content is represented in its cleanest form, without embellishment or adornment, and without distractions The premise is that the user can get to the information directly, without having to navigate some developer’s view of what is suitable UI decoration Consider, for example, the scrollbar In Metro, this is mostly invisible; the user
scrolls the content, not some shiny scrollbar chrome thumb or widget This is especially important on a
mobile device, given the smaller screen real estate and the use of a touch-based input model
Metro celebrates typography: after all, this is a large part of what the user will see in all tions, so the typography must be true to the Metro principles To embody this principle, the font selected as the standard system font on Windows Phone is Segoe WP (in regular, bold, semi-bold, semi-light and black variants), as shown in Figure 1-2
Trang 32applica-FIguRE 1-2 Segoe WP is the standard font on Windows Phone.
The FontSize values for the standard theme fonts are listed in Table 1-1.
TABlE 1-1 Standard Theme Font Sizes
Resource name size in Points size in Pixels
■ The Windows Phone Design system—Codename Metro A visual explanation of the
inspiration behind the Windows Phone design system, including the Red Threads principles (Personal, Relevant, Connected)
■
■ Design Templates for Windows Phone 7 A collection of 28 layered Photoshop templates
that help designers to maintain a consistent look and feel across applications
The focus is on building applications that can take part in a holistic UX This extends beyond the visuals to include all aspects of the application Navigation, for example, is deliberately enforced to be very simple, very linear, and predictable The user can quickly become familiar with the standard navi-gation model, and all applications follow this model Thus, the user can quickly become familiar with any new application There are constraints on what your application can do to avoid interfering with this predictability The user must be able to trust the hardware, so all the hardware buttons always behave the same way, and you cannot override this in a damaging way The Start button always goes
to the Start page The Back button always goes back in navigation (both within an application’s pages, and between applications in the backstack) When the user backs up to the beginning of the back-stack, he always ends up at the Start page
Trang 33Adhering to Metro design principles is not a burden: it actually frees you to concentrate on making your application the best it can be, because you don’t have to spend time on inventing a new design paradigm Instead, you can focus on making your application truly useful, compelling, and delightful, such that it offers a benefit to the user’s daily life Note that Metro is also being applied within Micro-soft for Windows 8 and for Xbox It will be the dominant design aesthetic for the next several years.
Developer Guidelines
If you want to build an ecosystem in which the inhabitants co-exist in harmony to their mutual efit, then there must be rules and guidelines Rules in Windows Phone development are enforced by the operating system, the application platform, and the platform API There are certain programming techniques that might be appropriate in a desktop development environment, but you simply cannot
ben-do them in Winben-dows Phone You cannot currently build a Winben-dows Phone application using native code You also cannot use COM or RPC, or indeed, any kind of inter-process communication Every application is strictly “sandboxed” and has no access to any other application You cannot consume CPU cycles (and battery power) when you’re not running in the foreground However careless you might be in handling exceptions, you cannot bring down the entire system Clearly, these rules have been put in place to optimize the stability of the phone and the overall UX
Then there are guidelines These are recommendations for how your application should look and behave, but they are not explicitly enforced by the phone itself Rather, they are enforced by the mar-ketplace: if you build a bad application, users will quickly uninstall it and give it a bad review You’re not forced to use Metro in your design, but if you don’t, you might end up with an application that clashes with the ecosystem You’re not constrained in how much disk space you use up with applica-tion data, but if you use too much, the user will soon realize your application is making it difficult to run or install other applications You can use more than 90 MB of memory at runtime, but sooner or later the system will run up against a memory cap, and then your application will crash The Windows Phone marketplace publishes a comprehensive set of certification requirements, and the developer has a lot of support (especially in Windows Phone SDK 7.1) in preparing applications for publication However, the marketplace performs only a small set of automated and manual tests; consequently, it
is entirely possible to publish a bad application which then fails at runtime Users typically have very low tolerance for things that crash, so this is very much a self-policing system
In the market today, there is a spectrum of application models from iOS at one end (for which there’s really only one logical device, and applications are severely constrained as to what they can and cannot do), to Android at the other (where there’s a very wide and heterogeneous range of devices, and applications have very wide latitude to do all kinds of things, which might or might not function well, or at all, on every device) Windows Phone sits somewhere in the middle, offering the best of both worlds: there is a small set of supported devices, with a tightly controlled hardware requirements specification to which they must minimally adhere, and an application platform that offers a wide range of features, yet enforces some reasonable constraints in the interests of maintain-ing a consistent UX as well as overall device health
Trang 34Windows Phone Architecture
Apart from a few applications provided by Microsoft, the device manufacturer, or the service vider, Windows Phone 7 applications are developed in managed code, using either the Windows Phone version of the Microsoft Silverlight runtime or the Windows Phone version of the XNA runtime (or some combination) These are slightly modified, phone-specific versions of the standard Silver-light/XNA libraries The phone application platform includes a set of standard controls and wrap-per classes to the phone services A high-level view of the architecture is shown in Figure 1-3 The underlying operating system is Windows CE, with the Microsoft NET Compact Framework and the Silverlight or XNA runtime layered on top
pro-Silverlight/XNA Application Host Process
Native Application Platform
Operating System Kernel
Install/Update Manager
Window Manager Execution Manager
Managed Runtime
Native Application Runtime
Phone Controls & Services NetCF
Platform Interop Runtime Host Managed Manager Proxy Execution
Silverlight/XNA Runtime
DB
FIguRE 1-3 The Windows Phone application architecture has managed and native layers
The application model exposed to marketplace developers is very robust An important principle is that the core services of the phone must continue to function at all times, regardless of what custom applications might be installed or running
Trang 35From a UX perspective, this means that the user can rely on the following behavior:
■
■ The user is always able to get back to the Start menu, lock the phone, and turn the phone off She is always able to make and receive calls, navigate to hubs, and so on The phone protects itself mainly by its application isolation/security model
■
■ A new application installs cleanly and cannot break any existing core feature of the phone or any other installed application The same applies to updates The architecture ensures that there can be no versioning conflicts with shared components, because applications cannot install shared components
Comparison of Silverlight and XNA
You can build applications for Windows Phone by using either Silverlight or XNA or a constrained combination of both, as described in Table 1.2
TABlE 1-2 Comparison Between Silverlight and XNA Applications
Primary target app N-tier business applications, tools Games.
Developer
experience XAML-driven, using Microsoft Expression and Microsoft Visual Studio, very similar to Windows
Presentation Foundation (WPF) and desktop Silverlight development.
Visual Studio–code-driven Also similar
to Xbox console and Windows games development.
Typical artifacts Built-in support for controls, data binding, web
services, and text. Models, meshes, sprites, textures.
Execution model Event-driven (via UI controls or external events),
and application-focused. Gaming loop, display-focused.
Graphics Retained mode graphics (application code
up-dates an in-memory model of the graphics, which the OS renders later on), with 2D and limited 3D (PlaneProjection) Cannot use XNA graphics in 7.
Immediate mode graphics (application code causes direct rendering of graphics), with full 3D support.
Audio Focused on simple media playback (music and
video); can use XNA sounds and recording. Multichannel audio, including recording.Screen Standard Silverlight visual tree model, with a
hierarchy of controls. The game always uses the full screen.
Trang 36Feature silverlight xnA
Controls Rich set of standard controls None.
Data binding Built in to the standard controls None.
Regardless of whether you choose Silverlight or XNA as the primary framework, you can also use some features from the other framework In Windows Phone 7, a Silverlight application can use any
of the XNA classes, except those in Microsoft.Xna.Framework.Games and Microsoft.Xna.Framework Graphics A common scenario is for a Silverlight application to use the advanced audio playback and
recording support in XNA Conversely, an XNA application can use some of the Silverlight features, but is more restricted; it cannot use any of the controls, data, messaging, input, media, browser, navi-gation, or threading features Windows Phone 7.1 introduced significant support for combining the two runtimes in a seamless manner
Developer Tools
The primary reference for Windows Phone platform APIs is MSDN, which is kept up to date online at
http://msdn.microsoft.com/en-us/library/ff402535(VS.92).aspx Another great resource is the AppHub, which you can access at http://create.msdn.com This is a development portal for Windows Phone and
Xbox 360 development, including links to download the core WP7 tools The primary tools are listed
in Table 1-3 Further ancillary tools and early-release frameworks are also mentioned in each chapter
of this book, where appropriate
TABlE 1-3 The Primary Windows Phone Development Tools are available from the AppHub
Windows Phone
Developer Tools This is the 7 version of the tools: you only need these if you want to use the 7 emulator Otherwise, you can use the 7.1 or 7.1.1 SDK for developing both version 7 applications
and version 7.1 applications Available at http://www.microsoft.com/download/en/details.
Windows Phone SDK 7.1 This is the 7.1 version of the tools You can use this to target both versions 7 and 7.1
Available as a free download from http://www.microsoft.com/download/en/details.
Trang 37Tool Description
Windows Phone SDK 7.1.1
Update An incremental update to the existing Windows Phone SDK 7.1 This update adds sup-port for developing applications that are optimized to run on 256 MB devices It includes
an updated version of the standard (512 MB) emulator, plus a new 256 MB emulator For details, see Chapter 16, “Enhanced Phone Services.” With version 7.1.1 installed, you can
target all versions: 7, 7.1, or 7.1.1 Available for download at http://www.microsoft.com/
Training Kit Hands-on labs for the Windows Phone 7.5 application platform Available at http://www.microsoft.com/download/en/details.aspx?id=28564
Windows Azure Toolkit
for WP7 Visual Studio templates for Windows Phone projects that connect with cloud services run-ning in Windows Azure Available at http://watwp.codeplex.com.
Windows Phone
Developer Guide Patterns & Practices guide to Windows Phone development Available at http://wp7guide.codeplex.com.
Silverlight Media
Framework Includes Windows Phone 7 support for video playback, live/smooth streaming Available at http://smf.codeplex.com.
Note The online MSDN documentation covers version 7.1 If you need to see
documenta-tion that’s specific to version 7, you can download the 7 offline documentadocumenta-tion from
http://www.microsoft.com/download/en/details.aspx?id=20558.
The Windows Phone 7.1 SDK is a complete replacement for the version 7 SDK You cannot run these side by side on the same computer, but you can use the version 7.1 SDK to target both 7 applications and 7.1 applications The one and only reason why you might want to keep a computer with only the version 7 tools on it is because the version 7.1 SDK uses the 7.1 emulator; the version 7.1 emulator will run version 7 applications in backward-compatibility mode on top of the version 7.1 platform Although this has a very high degree of compatibility, you should always run on a real ver-sion 7 device (or emulator) to ensure that your application will work on the version 7 OS Therefore, if you want to be able to test your application on a version 7 emulator, you need to have an installation
of the version 7 tools In all other respects, the version 7.1 tools are preferred
Trang 38Development Cycle
Developing and publishing applications for Windows Phone is very straightforward, as shown in Figure 1-4
Visual Studio, Expression Blend AppHub Portal
Developer
User
Retail Phone
Emulator
unlocked Phone
Analytics
Review,Feedback
Test, Sign,CertifyTest
1
2
3
Use,Uninstall
Download,install
Update,Revoke
6 5
8
7 4
Payments,Ratings/Reviews,Crash Report
9
Marketplace Catalog
FIguRE 1-4 The develop-publish-feedback cycle is very straightforward
You can download the free tools and get started building applications straight away As part of the development phase, you will typically test first on the emulator that is part of the SDK and then also
on a physical device To deploy unpublished applications to a phone, that phone must be unlocked To do this, you must first register with the AppHub as a developer Each developer account allows you to unlock up to three physical devices These devices will be registered with your AppHub account
developer-When you’re ready to submit your application for publication, there is a simple set of forms to fill out on the AppHub This is a front-end to the Windows Phone marketplace The marketplace inges-tion process will test your application against the certification requirements and then rebuild and sign the final XAP, making it available publicly in the marketplace catalog
Customers can then download and install your application onto their retail phones They can also subsequently update the application (if you publish an update to marketplace), provide a review and feedback, and uninstall/reinstall whenever they choose You can track payments, feedback, and pur-chase analytics in the AppHub portal
Trang 39The Anatomy of a Basic Windows Phone Application
When you build a Windows Phone application, the output of the build process is a XAP file XAP (pronounced “zap”) is the file extension for a Silverlight-based application package (.xap) This is a zip-format compressed file that contains all your assemblies, your manifest, and any loose image files or other data files that you chose not to embed in your assemblies When the user installs your applica-tion on his phone, the XAP is deployed to an install folder on the filesystem, as shown in Figure 1-5 Each application gets its own install folder The exact location is opaque—there is no supported way
to examine the phone filesystem and no good reason to do so
XAP
XAP Phone Filesystem
In-Memory
Security Sandbox Host Process Application DLLs
MyApp Start Menu
OtherApp App 3
Application Install Folder
Application Isolated Storage Applications Installed
DB
MyApp.dll MyClassLib.dll WMAppManifest.xml
Image & data files
Construct Sandbox,Create Process
4
3 5
FIguRE 1-5 Components from your XAP are loaded into memory at runtime
Trang 40At install time, the installer service extracts critical metadata from your WMAppManifest.xml and stores it in the phone’s database Information about all installed applications is entered in this data-base Standard parts of the phone UI such as the Start page and the installed application list gather the information they need from this database, including application name, icon, and background tile image Your application manifest includes details of the capabilities that your application requires, and these are used to configure the correct security sandbox for your application This configuration
is also stored in the application database
When the user chooses to launch your application, the system reads the database to construct the security sandbox within which your application will run Then, the platform loads your application assemblies into memory, performs security checks, and instantiates the class that you’ve marked as the entry point to the application Once your application is running, it has implicit access to any of the loose data files that were in the original XAP and deployed at install time to the application’s install folder Any reference in your code to such files is assumed to be relative to the root of the applica-tion’s install folder The application also has exclusive read/write access to its own private isolated storage area on the filesystem This is in a different location than the install folder, both for security reasons and to aid in the application update process
XAP Contents
A Windows Phone XAP is essentially the same as a regular desktop Silverlight XAP—a zip file that contains all the application’s local DLLs, resources, and the AppManifest.xaml, plus an additional file named WMAppManifest.xml The AppManifest.xaml file is a regular Silverlight artifact: it contains a list of “deployment parts” (typically, assemblies local to the application), and the name of the class (and its containing assembly) to be instantiated as the entry point for the application It also contains information about localized resources (if any), and thus the languages that the application supports
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas microsoft.com/winfx/2006/xaml" EntryPointAssembly="WindowsPhoneApplication1" EntryPointType="Win dowsPhoneApplication1.App" RuntimeVersion="3.0.40624.0">
browser, and so on), then you will need the ID_CAP_NETWORKING capability