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

wrox press professional windows 8 programming, application development with c# and xaml (2013)

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

ffirs.indd 2 11/27/2012 4:46:33 PM
PROFESSIONAL WINDOWS® 8 PROGRAMMING
INTRODUCTION xxv
CHAPTER 1 A Glimpse into the Future 1
CHAPTER 2 What Is XAML? 49
CHAPTER 3 Enhancing Your Apps with Control Styles,
Data Binding, and Semantic Zoom 79
CHAPTER 4 Windows 8 User Interface Final Touches 121
CHAPTER 5 Application Life Cycle 151
CHAPTER 6 Handling Data, Files, and Networking 181
CHAPTER 7 Sensors 229
CHAPTER 8 Geolocation 249
CHAPTER 9 Application Contracts and Extensions 269
CHAPTER 10 Windows Store Application Architecture 303
CHAPTER 11 Windows Store and Monetization 339
CHAPTER 12 Putting it All Together: Building a Windows Store Application 383
INDEX 449
ffirs.indd 1 11/27/2012 4:46:33 PM
ffirs.indd 2 11/27/2012 4:46:33 PM
PROFESSIONAL
Windows
®
8 Programming
ffirs.indd 3 11/27/2012 4:46:33 PM
ffirs.indd 4 11/27/2012 4:46:33 PM
PROFESSIONAL
Windows
®
8 Programming
APPLICATION DEVELOPMENT WITH C# AND XAML


Nick Lecrenski
Doug Holland
Allen Sanders
Kevin Ashley
ffirs.indd 5 11/27/2012 4:46:34 PM
Professional Windows
®
8 Programming: Application Development with C# and XAML
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-20570-9
ISBN: 978-1-118-22852-4 (ebk)
ISBN: 978-1-118-24082-3 (ebk)
ISBN: 978-1-118-26569-7 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,
(978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or
online at />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specically disclaim all warranties, including
without limitation warranties of tness for a particular purpose. No warranty may be created or extended by sales or

promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If
professional assistance is required, the services of a competent professional person should be sought. Neither the publisher
nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this
work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses
the information the organization or Web site may provide or recommendations it may make. Further, readers should be
aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written
and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard
print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD
or DVD that is not included in the version you purchased, you may download this material at
http://booksupport
.wiley.com.
For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2012947694
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its afliates, in the United States and other
countries, and may not be used without written permission. Windows is a registered trademark of Microsoft
Corporation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated
with any product or vendor mentioned in this book.
ffirs.indd 6 11/27/2012 4:46:34 PM
This book is dedicated to my remarkably patient
family, my wife Kristie and daughters Tabetha and
Cheyenne for once again tolerating another
year-long book authoring process!
—N L
Thanks to my wife Wendi and our children Mekella,
Jaimee, Andrew, and Jake for their love and support.

—D H
To Olga, my father Gregory, my mother Vera, and
to all of you for reading this book. Enjoy!
—K A
ffirs.indd 7 11/27/2012 4:46:34 PM
ffirs.indd 8 11/27/2012 4:46:34 PM
ABOUT THE AUTHORS
NICK LECRENSKI is a developer with over 10 years of experience in a wide range of Microsoft
technologies including Silverlight, XAML, C#, VB.NET, ASP.NET, C++, Java, HTML, MVVM,
SQL Server, and more. He has a BS in Computer Science and has worked in various elds from
biometrics to nancial services. He is also the founder and lead developer of
MyFitnessJournal
.com
, an online tness tracking site that utilizes the latest web development technologies
including ASP.NET MVC and JQuery.
DOUG HOLLAND is an architect with Microsoft’s Developer & Platform Evangelism team. He works
with Microsoft’s strategic ISV partners to help them bring new and exciting experiences to consum-
ers on Windows 8 and Windows Phone 8. Before joining Microsoft DPE, he was awarded both the
Microsoft MVP (Visual C#) and Intel Black Belt Developer awards and holds an M.Sc. in Software
Engineering from Oxford University.
ALLEN SANDERS is an architect at Teksouth Corporation and co-owner of LiquidKey, LLC. He
provides expertise from the UX (user experience) to the database for LOB (line of business),
Windows 8, and Windows Phone solutions.
KEVIN ASHLEY (@kashleytwit) is an architect evangelist at Microsoft, author of top Windows 8
and Windows Phone apps (
), code junkie and a part-time ski instructor.
Prior to Microsoft, Kevin founded a successful cloud-based business intelligence startup and worked
in nance. In his role as a senior software developer and architect, Kevin developed grid, data
warehousing and real-time trading solutions for Fortune 500 companies and hedge funds worldwide:
US, UK, Europe and Asia. Kevin has degrees in Mathematics, Computer Science and has an MBA in

Finance. He enjoys writing about software and technology on his blog:
.
ffirs.indd 9 11/27/2012 4:46:34 PM
ffirs.indd 10 11/27/2012 4:46:34 PM
ABOUT THE TECHNICAL EDITORS
JOHN BOX has almost 30 years of experience in the computer industry. Currently, he is nishing his
seventh year at Microsoft as a senior technical evangelist in the Developer & Platform Evangelism
organization (DPE). In past lifetimes, Jon has been a developer, architect, software manager, consul-
tant, instructor, and a general manager of a consulting ofce. Today, he is working with customers in
the central US build Windows 8 applications for the Windows Store. You can nd more background
at his blog (
or on Twitter (@jonbox).
FRANK LA VIGNE works for Microsoft as a public sector technical evangelist and Windows 8
Champ. Prior to joining Microsoft, Frank was a Tablet PC MVP and co-authored a book on
Silverlight 4. He has been in software development since the days of Visual Basic 3. Frank blogs
regularly about Windows 8 development at
www.FranksWorld.com/blog.
DON REAMEY is an architect/principal engineer for TIBCO Software working on TIBCO Spotre
business intelligence analytics software. Prior to TIBCO, Don spent 12 years with Microsoft
corporation as software development engineer working on SharePoint, SharePoint Online and
InfoPath Forms Service. Don has also spent 10 years writing software in the nancial service
industry for capital markets.
ffirs.indd 11 11/27/2012 4:46:34 PM
ffirs.indd 12 11/27/2012 4:46:34 PM
CREDITS
ACQUISITIONS EDITOR
Mary James
PROJECT EDITOR
Maureen Spears
TECHNICAL EDITORS

John Box
Frank La Vigne
Don Reamey
PRODUCTION EDITOR
Daniel Scribner
COPY EDITOR
San Dee Phillips
EDITORIAL MANAGER
Mary Beth Wakefield
FREELANCER EDITORIAL MANAGER
Rosemarie Graham
ASSOCIATE DIRECTOR OF MARKETING
David Mayhew
MARKETING MANAGER
Ashley Zurcher
BUSINESS MANAGER
Amy Knies
PRODUCTION MANAGER
Tim Tate
VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER
Richard Swadley
VICE PRESIDENT AND EXECUTIVE
PUBLISHER
Neil Edde
ASSOCIATE PUBLISHER
Jim Minatel
PROJECT COORDINATOR, COVER
Katie Crocker
PROOFREADERS

Jennifer Bennett, Word One
Josh Chase, Word One
Scott Klemp, Word One
INDEXER
Robert Swanson
COVER DESIGNER
LeAndra Young
COVER IMAGE
@archana bhartia/iStock
ffirs.indd 13 11/27/2012 4:46:34 PM
ffirs.indd 14 11/27/2012 4:46:34 PM
ACKNOWLEDGMENTS
WHEN YOU AUTHOR A BOOK and you get to the process of writing any acknowledgments it is a very
good day. It means you are nally at the end of a very long journey that has many ups and downs.
From late nights working through coding issues, to scouring the web for any new information on
the topics you are trying to write about, getting here requires a lot of help. First and foremost, I
want to thank Maureen Spears for once again leading me through this journey and keeping me
sane when deadlines were missed or things just didn’t work the way I wanted them to. I also need to
thank Mary James for keeping all of us on track and taking care of the various project management
details of which there were many, given the number of authors involved. Finally, I want to thank
Paul Reese who initiated this entire process quite some time ago and got the entire ball rolling!
—N L
THANKS TO MY WIFE for her love and support throughout this project, and thanks also to my man-
agers, Leslie Pickering and Matt Thompson, for their support in writing this book. Windows 8 has
been completely re-imagined, as has the associated developer platform. As such, I owe a debt of
gratitude to numerous people within Microsoft’s Developer Platform & Evangelism (DPE) team, the
Developer Division, as well as the Windows team. Their time and expertise was invaluable as the
book was researched and written. Thanks to Jon Box and Kevin Ashley for their attention to detail
during the technical edit, and a special thank you to Mary James and Maureen Spears at Wiley.
—D H

THANKS TO OLGA for all her support and love, and her family. Thanks to my mother Vera and my
father Gregory; your dedication to Physics will always be my inspiration. Special thanks to Warren
Wilbee and the team at Microsoft—all of you made many dreams possible.
—K A
ffirs.indd 15 11/27/2012 4:46:34 PM
ffirs.indd 16 11/27/2012 4:46:34 PM
CONTENTS
INTRODUCTION xxv
CHAPTER 1: A GLIMPSE INTO THE FUTURE 1
The Game Changer 1
What Makes Windows 8 Dierent? 2
Understanding Windows 8: The Zune Concept 3
Windows Phone 7 Carry-overs 4
Getting Around in Windows 8 4
The Login Screen 5
The Start Screen 5
The Search Feature 6
Application Life Cycle 7
Accessing Desktop Mode 7
Windows Store App Development 10
Hello Windows 8 13
Selecting a Language and Default Folders 13
Building a Simple Windows Store App 14
Setting App Capabilities 16
What About HTML Developers? 21
Types of Windows Store Apps 23
Grid Applications 24
Split Applications 44
Creating a Split Application 44
Summary 48

CHAPTER 2: WHAT IS XAML? 49
A Quick XAML History Lesson 50
XAML Basics 51
XAML in Visual Studio 2012 53
Controls for Windows 8 54
Layout Controls 55
Action Controls 66
Summary 78
ftoc.indd 17 11/27/2012 4:47:54 PM
xviii
CONTENTS
CHAPTER 3: ENHANCING YOUR APPS WITH CONTROL STYLES,
DATA BINDING, AND SEMANTIC ZOOM 79
Customizing Your Apps 79
Styling Controls 80
Understanding Basic Styling 80
Referencing Styles Across an App 86
Using Microsoft’s Default Styles 88
Data Binding 91
Understanding Basic Data Entry 91
Binding Objects to the User Interface 92
Updating Data with Two-Way Data Binding 96
Data Binding Summary 98
Windows 8 Data Binding Controls 98
ComboBox 98
ListBox 101
ListView 102
GridView 106
Grouped GridView 108
Using SemanticZoom 113

Using Custom Controls 116
Summary 119
CHAPTER 4: WINDOWS 8 USER INTERFACE FINAL
TOUCHES 121
Application Bars, Notifications, Splash Screens,
and Live Tiles 121
Working with the App Bar 122
Creating the Top App Bar Navigation 123
Wiring Up the App Pages 129
Adding Filtering Capability 133
Adding Finishing Touches to the App 135
Adding Notifications 136
Understanding Templates 136
A Toast Example 139
Creating Live Tiles 143
Available Tile Templates 144
Live Tiles Example 145
Splash Screen 149
Summary 150
ftoc.indd 18 11/27/2012 4:47:54 PM
xix
CONTENTS
CHAPTER 5: APPLICATION LIFE CYCLE 151
Applications Reborn 151
What Is the Windows 8 Life Cycle? 151
App Launch 152
App Activation 162
App Resume 165
App Close 167
Background Operations 168

Triggers and Conditions 169
Lock Screen 174
Progress Reporting 174
Debugging 178
Deadlock 179
Summary 179
CHAPTER 6: HANDLING DATA, FILES, AND NETWORKING 181
Getting Started with Data, Files, and Networking 182
Handling Application Data and Files 182
Getting Started with the Data Samples App 182
Understanding Windows.Storage API 184
Working with Data and Files Locations 185
File Access Permissions 186
Local Settings and Application Data 188
Roaming Settings and Application Data 190
Temporary Application Data 192
Versioning Application Data 192
Clearing Application Data 193
Displaying Pictures Library Content 193
Selecting Files: User Experience 197
Tracking Files and Folders 199
Serializing and Deserializing Data 201
Data Encryption and Decryption 203
Networking 204
Establishing Socket Connectivity 204
Data Transfers 211
Activating Proximity and Tapping 215
Syndicated Content 221
Accessing Network Information 222
Example: Leaderboard App 223

Summary 228
ftoc.indd 19 11/27/2012 4:47:54 PM
xx
CONTENTS
CHAPTER 7: SENSORS 229
Windows Sensor Platform 229
Hardware for the Sensor Platform 230
Windows Sensor Platform Overview 230
Using the 3-D Accelerometer 232
Using the 3-D Compass 234
Using the Compass Class 234
Calculating True North Headings 236
Using the 3-D Gyrometer 237
Using the Inclinometer 239
Using the Ambient Light Sensor 241
Using the Orientation Sensors 243
Using the OrientationSensor Class 243
Using the SimpleOrientationSensor Class 245
Summary 247
CHAPTER 8: GEOLOCATION 249
What Is Geolocation? 249
Geolocation in Windows 8 251
Using the Geolocator Class 251
Understanding the CivicAddress Class 253
Using the Bing Maps SDK 256
Referencing the Bing Maps SDK 256
Using the Bing.Maps.Map Class 257
Using Pushpins on the Map 258
Adding Trac Information 260
Getting Directions 262

Enabling Directions with Pushpins 263
Summary 267
CHAPTER 9: APPLICATION CONTRACTS AND EXTENSIONS 269
App Contracts and Extensions 269
Using the File Picker Contract 270
Selecting a Single File 270
Selecting Multiple Files 271
Selecting Files from Windows Store Apps 272
Debugging File Picker Activation 275
Using the Cached File Updater Contract 276
Using the Play To Contract 276
ftoc.indd 20 11/27/2012 4:47:55 PM
xxi
CONTENTS
Introducing the PlayToManager Class 276
Testing PlayTo Scenarios 278
Using the Search Contract 279
Using the Settings Contract 284
Using the Share Contract 285
Introducing the DataTransferManager Class 286
DataTransferManager.DataRequested 286
DataTransferManager.TargetApplicationChosen 286
Share Contract Scenarios 287
Using the Account Picture Provider Extension 287
Using the AutoPlay Extension 289
Using the Background Tasks Extension 291
Using Push Notifications 291
Using Background Tasks 292
Using the Camera Settings Extension 293
Using the Contact Picker Extension 294

Using the File Activation Extension 295
Implementing the File Activation Extension 295
Debugging File Activation 296
Using the Game Explorer Extension 297
Using the Print Task Settings Extension 298
Using the Protocol Activation Extension 298
Activating the Maps App 298
Making the Required Declarations 299
Debugging Protocol Activation 300
Using SSL/Certificates Extension 301
Summary 302
CHAPTER 10: WINDOWS STORE APPLICATION ARCHITECTURE 303
Best Practices for Your Apps 303
Understanding MVVM 304
Locating ViewModels 306
Refactoring the Artist Browser 307
Instantiating a ViewModelLocator 308
Removing DefaultViewModel 314
Simplifying the Models 324
Using Commands to Handle Input 326
Using MVVM Frameworks 332
Understanding MVVM Light 332
Messaging in MVVM Light 335
Summary 337
ftoc.indd 21 11/27/2012 4:47:55 PM
xxii
CONTENTS
CHAPTER 11: WINDOWS STORE AND MONETIZATION 339
Windows Store Overview 339
How Consumers See Your App 340

App Discovery 341
Making the First Good Impression 342
Promoting Your App 343
Selling Your Apps 343
Windows Store Economics 344
Windows Store API Overview 344
Getting Started with the Color Shopping App 345
Supporting Trials 349
In-App Purchases 360
Adding Advertisements 368
Summary: The Economics of Monetizing Your App 372
Application Packaging 374
Preparing your app in Visual Studio 375
Packaging Apps Using a Command Line 379
Packaging Enterprise Line-of-Business (LOB) Apps 380
Testing with Windows App Certification Kit 381
Understanding Windows Store Certification Requirements 381
Summary 382
CHAPTER 12: PUTTING IT ALL TOGETHER: BUILDING
A WINDOWS STORE APPLICATION 383
Welcome to the Final Chapter of the Book 383
Designing the Wrox BookStore App 384
Displaying Wrox Press Books 384
Adding a Wish List Across Devices 386
Diving into the Code 387
Getting Ready for MVVM 388
Creating Sample Data 391
Creating the Home Page 399
Configuring the XAML 400
Updating the ViewModel 406

Finishing the Code Behind 409
Drilling Down into Groups 411
Configuring the XAML 411
Updating the View Model 416
Finishing the Code Behind 418
Showing Detailed Book Information 422
Configuring the XAML 422
ftoc.indd 22 11/27/2012 4:47:55 PM
xxiii
CONTENTS
Updating the View Model 427
Finishing the Code Behind 428
Providing a Wish List Feature with SkyDrive 430
Making Files Available Locally 430
Registering Your App 434
Loading/Creating the Wish List File 434
Saving the Wish List File 439
Adding the Commands 440
Updating the Tile and Splash Screen 441
Getting Ready for the Store 442
Opening a Developer Account 443
Reserving an App Name 443
Acquiring a Developer License 444
Editing the App Manifest 444
Associating the App with the Store 445
Capturing Screenshots 445
Creating App Packages 446
Uploading App Packages 446
Concluding Remarks on the Store Checklist 447
Summary 447

INDEX 449
ftoc.indd 23 11/27/2012 4:47:55 PM

×