Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
1. Programming Windows Store Apps with C 1st
Edition Matthew Baxter-Reynolds pdf download
https://ebookgate.com/product/programming-windows-store-apps-
with-c-1st-edition-matthew-baxter-reynolds/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
Developing Windows Store Apps with HTML5 and JavaScript
1st Edition Rami Sarieddine
https://ebookgate.com/product/developing-windows-store-apps-with-
html5-and-javascript-1st-edition-rami-sarieddine/
Windows Store App Development C and XAML Pete Brown
https://ebookgate.com/product/windows-store-app-development-c-
and-xaml-pete-brown/
Automating Microsoft Windows Server 2008 R2 with
Windows PowerShell 2 0 1st Edition Matthew Hester
https://ebookgate.com/product/automating-microsoft-windows-
server-2008-r2-with-windows-powershell-2-0-1st-edition-matthew-
hester/
GameMaker Game Programming with GML 1st Edition Edition
Matthew Delucas
https://ebookgate.com/product/gamemaker-game-programming-with-
gml-1st-edition-edition-matthew-delucas/
3. Head First HTML5 Programming Building Web Apps with
JavaScript 1st Edition Eric T Freeman
https://ebookgate.com/product/head-first-html5-programming-
building-web-apps-with-javascript-1st-edition-eric-t-freeman/
Programming Chrome Apps Develop Cross Platform Apps for
Chrome 1st Edition Marc Rochkind
https://ebookgate.com/product/programming-chrome-apps-develop-
cross-platform-apps-for-chrome-1st-edition-marc-rochkind/
Programming With C 3rd Edition Bl Juneja
https://ebookgate.com/product/programming-with-c-3rd-edition-bl-
juneja/
CryENGINE Game Programming with C C and Lua 1st Edition
Lundgren
https://ebookgate.com/product/cryengine-game-programming-with-c-
c-and-lua-1st-edition-lundgren/
Linear programming with MATLAB 1st Edition Michael C.
Ferris
https://ebookgate.com/product/linear-programming-with-matlab-1st-
edition-michael-c-ferris/
8. Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Making the Transition from .NET (Part 1). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why WinRT? 1
Philosophical Differences 2
Objectives 3
The New Project Templates 3
WinRT Metadata 4
Project Settings and Adding References 9
Building a Basic User Interface 11
UI Tracks 11
XAML Parsing Basics 14
Building a Basic Page 15
Implementing MVVM 25
WPF and Silverlight 26
MVVM Structure and Inversion of Control 28
Creating the View-Model and Running the App 38
2. Making the Transition from .NET (Part 2). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Inversion of Control 47
Installing TinyIoC 48
Initializing IoC Defaults 49
Understanding Asynchrony 53
How Asynchrony Works in WinRT 55
Calling the Server 60
Building the Service Proxies 60
Building the Register Method 63
Finishing the UI to Call the Register Server Function 67
Logon 68
iii
9. Building LogonServiceProxy 69
Building the Logon Page 70
Busy Indicators 75
Positioning the Indicator 75
Showing the Indicator 77
3. Local Persistent Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
SQLite and sqlite-net 84
Working with SQLite 85
A Primer on Object-Relational Mapping 86
Using the Micro-ORM in sqlite-net 87
Storing Settings 89
The SettingItem Class 89
Linking in sqlite-net 91
Creating the Database Table for SettingItem 95
Reading and Writing Values 96
Modifying LogonPageViewModel 97
Caching Data Locally 100
Local Caching 100
Mapping JSON to Database Entities 101
Creating Test Reports 102
Setting Up the User Database 103
Creating ReportsPage 105
Using Templates 106
Building a Local Cache 109
Updating the Cache 112
Returning Reports from the Server 113
The Items Property 114
4. The App Bar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Adding a Simple App Bar 120
Getting Started with an App Bar 121
App Bar Behavior 124
App Bar with Single-Select Grid 126
App Bar with Multiselect Grid 126
A More Complex App Bar Implementation 127
Showing the App Bar on Multiple Selections 128
Checking Touch Operations 133
Showing the App Bar on Right-Click 135
Showing Context Options 136
App Bar Images 140
The Glyph Method 140
iv | Table of Contents
11. Sharing Images 251
Quick Links 254
8. Searching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Implementing Search 258
Creating the Search Results Page 258
Creating SearchResultsPageViewModel 258
Implementing the Search Operation 263
Refining Search 276
Placeholder Text 277
Suggestions 278
Remembering Where We Were 284
Using the SearchBox 289
Other Best-Practice Notes 291
9. Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Adding Options 293
Standard Options 294
Adding Custom Options 294
Implementing the Settings Flyout 297
Building a Settings Pane 297
Building MySettingsFlyout 301
Developing a Help Screen 303
Creating a Help Pane 303
Handling the F1 Key 305
Rendering Markup 306
10. Location. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Creating a Singleton View 311
Creating the View-Model 312
Creating the View 315
Navigating to the View 318
Retrieving a Current Location 322
Using the Simulator with Location 327
Integrating Maps 328
Adding the Bing Maps Control 329
Handling Input with the View 331
Packaging Points for Display 332
Showing Points on the Map 336
Shelling to the Maps App 339
11. Using the Camera. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
vi | Table of Contents
12. Capturing Photos 344
Creating EditReportPage 345
Building EditReportPageViewModel and Its View-Model 346
Saving and Canceling 352
Adding the New Option 355
Handling Temporary Files 356
Changing the Manifest 356
Taking Pictures 357
Implementing Save 360
Validating and Saving 360
Resizing Images 363
12. Responsive Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Updating the Grid View 371
The VisualStateManager 371
Creating MyListView 373
Modifying the App Bar 375
Updating Singleton Views 377
Adding a More Button to the App Bar 380
Handling Views That Don’t Support 320-Pixel Width 385
13. Resources and Localization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
.pri Files 387
Adding Strings 390
Localizing Strings 393
Default Project Locales 393
Localizing Strings in XAML 394
Conventions 398
Changing Other Properties 399
Explicitly Loading Strings 399
Localizing Images 402
Varying Images by Locale 402
Varying Images by Display DPI 405
14. Background Tasks and App Lifetime. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
App Lifetime 410
Background Tasks API 411
CPU Usage Quota 412
Triggers and Conditions 413
Execution Model 415
Implementing a Sync Background Task 416
Building the Façade 422
Table of Contents | vii
13. Debugging the Task 425
Troubleshooting Background Tasks 427
Restricting the Run Period 428
Implementing the Sync Function 433
Sending Changes 434
Receiving New Work 438
Signaling the App from the Background Task 443
Putting the App on the Lock Screen 444
15. Sideloading and Distribution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Using the Windows App Certification Kit 450
Distribution Through Production Sideloading 451
Turning on Sideloading on Windows 8 452
Installing Apps 453
Distribution Through the Windows Store 453
A. Cryptography and Hashing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
B. Unit Testing Basics for Windows Store Apps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
viii | Table of Contents
14. Preface
The computing industry is changing. PC sales are on the decline, and sales of post-PC
devices (tablets and smartphones) are on the ascendancy. This change can be under‐
stood easily enough—computers are no longer something used for work, they are
something used for life, and happily there is more to our society than just work.
The massive commercial success of post-PC devices suggests that this change works
OK for most, but for companies like Microsoft it creates a big problem. The PC is not
going to be as important over the next 20 years as it has been for the last 20 years.
Windows 8.1 and Windows RT are Microsoft’s first move to try to address that problem
by making the Windows operating system “play more nicely” in the tablet space.
Microsoft has done this by introducing a new user interface paradigm called Modern
UI. This new user interface paradigm is monochronistic (one thing at a time), rather
thanthepolychronistic(manythingsatatime)natureofanormalwindowingoperating
system. It is also optimized for touch.
As well as providing a new user interface, Microsoft has introduced a new API, called
Windows Runtime (WinRT), and a new execution and packaging model for the apps,
called Windows Store apps. We’ll talk more about the actual construction of Windows
Store apps in Chapter 2.
This book is designed to treat Windows 8.1 and Windows 8.1.1 RT equally—nothing
we do in the book will exclude operation from either variant of the operating system.
Similarly, everything we do can be used in apps that are distributed through the Win‐
dows Store.
Generally, we will be writing all the code ourselves, but from time to time we will be
using third-party products. Virtually all of these are open source—there is only one
exception, which is the Bing Maps component discussed in Chapter 11. Everything else
is unrestricted.
So let’s go! We’ll start by learning about the app that we’re going to build.
ix
15. Audience
What I’ve tried to do with writing this book is to tell a story that takes you, the reader,
through the process of moving from .NET development over to Windows Store app
development. There is a slight bias in the book in that I’m assuming most developers
have day jobs developing web applications and have been asked to look into develop‐
ment tablet apps that run on Microsoft’s tablet operating systems.
Some of you will also have done quite a bit of desktop development on Windows, par‐
ticularly using Silverlight and/or Windows Presentation Foundation (WPF). This book
isn’t a primer on developing XAML, although you will see and work with enough ex‐
amples that use XAML to become proficient.
I’ll also tell you a bit more about the app we’ll be discussing so you can judge if this is
the right book for you. The app has within it the common sorts of functionality that you
findinline-of-businessapps(LOB)generally.Atthetimeofwriting,theWindowstablet
story is not established, so the elements that we’ll go through are those that apply to real
applications on Windows Mobile, Android, and iOS that I’ve built over the past 10 years
or so.
Although the application that we’ll build is a LOB app, everything you’ll see and do in
this book applies equally well to a normal retail app that you might sell in a business-
to-consumer fashion.
The Application
As I mentioned, we’re going to build a line-of-business app, rather than a “retail” app.
The way that I distinguish between these two is that in a retail app, the software vendor
typically doesn’t have a strong relationship with the end customer. In retail, the end
customerfindstheappthroughindirectrecommendationsand/orthroughtheappstore
catalog. In a LOB app, proactive marketing and relationship-building activities look to
tie a client and vendor together through some sort of commercial offering. Technically,
however, there isn’t a big difference between retail apps and LOB apps.
The specific example I’m going to show you is a “field service” app. This type of app is
a classic mobile working application. In field service you have a number of operatives
whose operational control is within your remit. You send them out into the field to do
something—either something specific (“go here, fix this”), or something reactive (e.g.,
someone “patrols” an area and reports back on problems).
The app we will build will be called StreetFoo, and it’s a blend of those last two examples.
I have created a simple server that is hosted on AppHarbor that will serve as the backend
service for the app. When the user logs in to the app, it will download a set of “problem
reports.” Each report will be something that needs fixing—the sample data happens to
show graffiti, but it could be anything. The concept of the app is that the user would
x | Preface
16. then either fix the problem or could report new problems into the app. Updates to
problems or new problems are then updated to the server.
That’s the basic functionality. There are additional things that we’ll look at, such as
capturing photos and location information, as well as all of the various special user
experience features in Windows 8.1/Windows 8.1.1 RT—sharing, snapped view, search,
and so on.
The Chapters
We’ll start in Chapters 1 and 2 with a primer designed to get you up and running in
terms of moving from .NET into this new world.
Chapter 1, Making the Transition from .NET (Part 1)
Starts by explaining the “break” between .NET and associated technologies (specif‐
ically WPF) over to Windows Runtime (WinRT). You’ll then build a basic user
interface and implement a Model/View/View-Model (MVVM) pattern.
Chapter 2, Making the Transition from .NET (Part 2)
Walks you through making the UI you built in Chapter 1 do something—specifi‐
cally, calling up to the server to register a new user account. This chapter also has
a detailed look at asynchrony—probably the most important thing that you will
learn during your time with Windows Store app development.
The remaining chapters in this book each focus on a specific API feature area.
Chapter 3, Local Persistent Data
Explores SQLite. The reason I’ve brought up this topic so early in the book is that
you can’t build a practically useful application without having some sort of persis‐
tent store. Although you can store information on disk easily enough using the
Windows Store APIs, SQLite is the de facto relational database used in mobile sol‐
utions, and so we’ll use it in our app.
Chapter 4, The App Bar
Introduces the first of the special Windows 8.1 user experience (UX) features: the
app bar. App bars are the small panels that pop in from the top and bottom of the
screen and provide access to options and tabs. (The app bar is essentially analogous
to toolbars.) We’ll look at how to build an app bar and how to make up our own
images for use on the buttons.
Chapter 5, Notifications
Discusses notifications. Notifications in Windows Store apps can be used to update
the tile on the Start screen, add badges to the tile, and display toast (the notifications
that wind in from the top-right side of the screen). Notifications can be created
locally and shown locally, or alternatively, created on the server and pushed out to
Preface | xi
17. all connected devices using Windows Push Notification Services (WNS). In this
chapter we’ll look at both routes.
Chapter 6, Working with Files
Looks in detail at working with files. To be honest, when I first planned this book
I didn’t intend to include a chapter on files, as this tends to be a topic well served
by the community whenever a new platform is introduced. However, I ended up
adding this chapter to handle images. Each report that we track in the app will have
exactly one image. Rather than storing these images in SQLite, which is impractical,
we’ll store them on disk.
Chapter 7, Sharing
FocusesontheWindows8.1sharingfeature.Sharingisoneofthekeydifferentiators
between Microsoft’s tablet strategy and other platforms. Most platforms “silo off”
apps and make it hard to share data. Windows 8.1 has a declarative model for
sharing where apps indicate they can serve up certain types of data. That data can
then be read in by another app that supports consumption of shared data. In this
chapterwe’lllookatbothsharingdatafromourappandconsumingdatafromother
apps.
Chapter 8, Searching
Looks at the Windows 8.1 UX feature of searching. The idea here is that, generally,
all apps need some sort of search feature. In Windows 8.1 this is accessed from the
charms or by using the SearchBox control. In this chapter we’ll look at implement‐
ing a search feature that we can use to find problem reports.
Chapter 9, Settings
Concludes our look at Windows 8.1 UX specifics with a discussion of the settings
charm, which—as its name implies—provides a common area where developers
can put settings. It’s also a common place to put links up for support information
and privacy policies. In this chapter we’ll go a little broad with this by using the
SettingsFlyout control to load and render Markdown-formatted text.
Chapter 10, Location
Explores location, a very common requirement for mobile LOB apps because it’s
often helpful to have some “evidence” of where a particular activity took place, or
to utilize the user’s location as a way of creating new data. In this chapter we’ll look
at the basics of reading locational information from the device, and we’ll also use
the Bing Maps Windows Store apps control to present a map within the application.
Chapter 11, Using the Camera
Helps you discover how to use the camera. In mobile LOB apps it’s often a require‐
ment to gather photographic evidence of work done. (For example, if someone is
asked to fix a sink, you may find it helpful to have a photo of the sink before and
xii | Preface
18. after it was fixed.) In this chapter we’ll look at how to create new problem reports,
starting with a photograph taken from the webcam.
Chapter 12, Responsive Design
Helps you master how to implement responsive design so the application can be
resized in width to support even the smallest width size of 320 pixels, previously
known as “snapped mode.” Another Windows 8.1 UX feature that differentiates
Windows from the other platforms is the ability to run apps side by side. The way
this works is that you can have one app running in a thin strip on the left or right
side of the screen, with another app taking up the remainder of the space. The only
problem with this is that you need to build an entirely parallel UI to get your app
running in this thin strip. In fact, this isn’t as bad as it sounds, because the MVVM
pattern that we’ll use abstracts a lot of the work away. Specifically, in this chapter
we’ll build in the ability to run our application in different width sizes.
Chapter 13, Resources and Localization
Looks at resources and localization. By the time you get to this chapter, you will
alreadyhaveseenquiteafewwaysofworkingwithresources,sosomeofthischapter
is given over to covering the things that we haven’t yet looked at in detail. In the
other part of the chapter, we’ll discuss how to implement proper localization of the
app (i.e., how to add in support to present the app in different languages).
Chapter 14, Background Tasks and App Lifetime
Tackles background tasks, a special way of blocking off functionality that Windows
will run on a schedule on the application’s behalf. Common to all tablet platforms,
Windows Store apps look to restrict what your application can do when it’s not
actually running in the foreground. In this chapter we’ll look in some detail at
implementing such background tasks—specifically, we’re going to look at how to
use this functionality to download new reports and upload local change reports
back to the server in the background.
Chapter 15, Sideloading and Distribution
Details how you can actually package and distribute apps on the Windows Store.
We’ll look at using developer licenses to create sideloading packages for internal
testing, and we’ll also look at how to do proper enterprise sideloading. (Sideloading
is the process whereby you distribute apps to a private audience rather than using
the Windows Store.) We’ll also look at the rules that you need to adhere to in order
to get Microsoft to distribute your app on the Windows Store.
The book has two appendixes:
Appendix A, Cryptography and Hashing
Coverssomecommonrequirementsrelatedtocryptographyandhashingthatyou’ll
likely either need or be asked about, but don’t fit into the main body of the text.
Preface | xiii
19. Appendix B, Unit Testing Basics for Windows Store Apps
Looks at how to unit test your code using the unit testing projects provided with
Visual Studio. This will use the inversion of control containers that we built and
used throughout the book.
And that’s it! By the time you’ve been through the whole story, you should have a great
understanding of how to build full-featured Windows Store applications.
Prerequisites
The only thing that you will need in order to get working is Visual Studio 2013. Out of
the box, this edition of Visual Studio comes with everything you need to build Windows
Storeapps.YoucanuseeithertheProfessionaleditionortheExpressedition.Ihappened
to use the Professional edition, but everything has been tested on Express.
You will need a Windows Store developer account if you want to actually get your apps
listed on the store, although nothing in this book requires that level of paid account.
You will need to create a free account in order to obtain a developer license, which is
required to locally deploy any apps that you build.
Source Code
The source code for this book is available on GitHub.
The easiest way to work with this code is to grab the entire repo and put it on your local
disk. Each chapter is represented by one folder, where the code in the folder is the same
as the state of the application at the end of each chapter. (For example, the Chapter8
folder includes everything from Chapter 2 up to and including Chapter 8. The Chap
ter9 folder builds on the Chapter8 folder and also includes the work that we go through
in Chapter 9.) From time to time, the code downloads may contain more than what we
have specifically gone through in the book.
If you’re not accustomed to using GitHub or git, here’s a quick run-through.
Using git
This section is intended to get you through the basics of installing git and using it to
fetch the code from the repository. It’s not intended to show you how to use git as a
source control system, but GitHub offers a decent walkthrough of that.
You’ll need a git client to get started. You can download a client from the git website.
Do this and install the package that’s downloaded.
The installer will install both a command-line client and a GUI. Personally, when I’m
actually using git I always use the command line. A lot of people use the GUI. If you’re
xiv | Preface
20. only interested in using git to get the code for this book, you might as well just use the
GUI.
To open the GUI in Windows 8.1, access the Start screen by pressing the Windows key.
Type git directly into the Start screen. You’ll get options for Git Bash and Git GUI.
Open up the Git GUI and select the Clone Existing Repository option.
You’ll need to copy and paste the path of the repo from GitHub. To do this, access the
repo using a web browser. The URL you want is https://github.com/mbrit/Program
mingWindowsStoreApps.
On the page you’ll find a “Quick setup” box that contains the actual URL of the repo.
You’ll need to copy this to the clipboard. The URL will look something like https://
github.com/mbrit/ProgrammingWindowsStoreApps.git. Figure P-1 illustrates.
Figure P-1. The area of the GitHub page showing the actual repo URL
Back in the GUI, copy and paste the repo path into the Source Location field, and type
the path to any local folder that you like into the Target Directory field. Figure P-2
illustrates.
Figure P-2. Setting up the clone operation
Click the Clone button, and the repo will come down to your local machine. You can
then use Visual Studio to open the solution files contained in each folder.
Preface | xv
21. Contacting the Authors
Should you want to get hold of Matt directly, the best way is via Twitter (@mbrit).
Alternatively, try his website. Iris Classon can be contacted via Twitter (@irisclasson)
and her website.
Let’s Go!
And that’s it. You should now be ready to get going building Windows Store apps.
Conventions Used in This Book
The following typographical conventions are used in this book:
Plain text
Indicates menu titles, menu options, menu buttons, and keyboard accelerators
(such as Alt and Ctrl).
Italic
Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames,
directories, and Unix utilities.
Constant width
Indicates commands, options, switches, variables, attributes, keys, functions, types,
classes, namespaces, methods, modules, properties, parameters, values, objects,
events, event handlers, XML tags, HTML tags, macros, the contents of files, or the
output from commands.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values.
This icon signifies a general note.
This icon signifies a tip or suggestion.
xvi | Preface
22. This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, if this book includes code
examples, you may use the code in your programs and documentation. You do not need
to contact us for permission unless you’re reproducing a significant portion of the code.
For example, writing a program that uses several chunks of code from this book does
not require permission. Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of ex‐
ample code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Programming Windows Store Apps with
C# by Matt Baxter-Reynolds and Iris Classon (O’Reilly). Copyright 2014 Matthew
Baxter-Reynolds, 978-1-449-32085-0.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that
delivers expert content in both book and video form from
the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.
Preface | xvii
23. How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/prog-win-store-apps-csharp.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Thank you to the technical reviewers, Oren Novotny, Stefan Turalski, Matt Fitchett, and
Nathan Jepson, without whom this book would not have been possible.
This book would be fundamentally different, and nowhere near as good or complete,
were it not for Twitter. Twitter is perhaps the most important learning resource for those
involved in the computer industry that’s ever been invented. This book has got quite a
lot of advice in it, and the most important piece is this: if you’re a professional software
developer and you don’t use Twitter, start.
Here’s a list of my various Twitter friends who have given support, saved me hours upon
hours of work, come up with new ideas, and provided invaluable input:
• Alex Papadimoulis (@apapadimoulis)
• Casey Muratori (@cmuratori)
• Chris Field (@mrcfield)
• Chris Hardy (@chrisntr )
xviii | Preface
24. • Craig Murphy (@camurphy)
• Daniel Plaisted (@dsplaisted)
• David Kean (@davkean)
• Duncan Smart (@duncansmart)
• Edward Behan (@edwardbehan)
• Filip Skakun (@xyzzer)
• Frank Krueger (@praeclarum)
• Gill Cleeren (@gillcleeren)
• Ginny Caughey (@gcaughey)
• Haris Custo (@hariscusto)
• Hermit Dave (@hermitdave)
• Iris Classon (@irisclasson)
• Jamie Mutton (@jcmm33)
• Joel Hammond-Turner (@rammesses)
• Jose Fajardo (@josefajardo)
• Keith Patton (@kpatton)
• Kendall Miller (@kendallmiller)
• Liam Westley (@westleyl)
• Mark Tepper (@binaerforceone)
• Matt Hidinger (@matthidinger)
• Matthieu GD (@tewmgd)
• Mike Harper (@mikejharper)
• Nic Wise (@fastchiken)
• Peter Provost (@pprovost)
• Ross Dargan (@rossdargan)
• Tim Heuer (@timheuer)
• Tomas McGuinness (@tomasmcguinness)
Finally, thank you to Rachel Roumeliotis, Maria Gulick, Melanie Yarbrough, and the
rest of the O’Reilly team for their hard work and patience in making this book a reality.
Preface | xix
26. CHAPTER 1
Making the Transition from .NET (Part 1)
In this chapter and the next we’re going to start looking at the work that we have to do
to move our .NET skills over to WinRT and start building Windows Store apps. Unlike
theotherchaptersinthisbook,whichfocusonaparticularAPIfeaturearea,thischapter
and the next are more mixed and intermingled, mainly because the changes that we
have to make in order to achieve a transition are also mixed and intermingled.
Given Microsoft’s history with .NET, you might have expected WinRT to be a direct
evolution. In fact, it’s not. WinRT represents a major shift in strategy from the team
within Microsoft that “owns” the Windows API. It’s coming to market at a time when
considerable changes are happening within the broader world of software engineering.
This is the “post-PC” age. Microsoft rose to dominance in the microcomputer/PC age.
Why WinRT?
WinRT has emerged at the same time as Microsoft’s “reimagining” of Windows into
two new operating systems—Windows 8 and Windows RT—although the timing that
brings the launch of the new OSes and a new API model together is more luck than
judgment. WinRT is about fixing the fundamental limitations of writing software na‐
tively for Windows. Native applications in Windows are written using the Win32 API,
which is a very old, non−object-oriented API. Alongside Win32 we also have COM, an
object-oriented subsystem that allows for components to be plugged in and out of Win‐
dows. If you’re a relative newcomer to writing software for Windows, there’s a good
chance you’ve never used either of these, or you’ve used .NET. If you’re slightly longer
in the tooth, there is a chance that you did use these technologies once, but—especially
if you’ve selected this book—the likelihood is that over the past n years you’ve been
using .NET to write software that targets Windows OSes.
.NET is very different from Win32 or COM. .NET is a Java-inspired framework library
and execution environment designed to make it easier to write software for Windows.
1
27. We call .NET a “managed code” environment because the runtime takes over a lot of
the “management” of the code execution. Conversely, Win32 apps are “unmanaged.” In
its initial incarnation, .NET was built to let developers build websites in ASP.NET, or
native applications with Windows Forms. (We’ll ignore console applications or Win‐
dows services for the time being, as I want to talk about user interface technologies.)
Both of these user interface technology tracks have evolved and changed over time, but
regardless the more important thing about .NET was that it allowed developers to be
more expressive. The Base Class Library (BCL) within .NET provided easy, object-
oriented access either into Windows operating system features (e.g., System.IO.File
Stream) or classes designed to save the developer time and effort (e.g., System.Collec
tions.Generic.List).(Theformersetisrelevanthere,asagreatdealoftheBCLsimply
thunks down into Win32, which is how it provides access to OS functions.) In addition
to the BCL, the CLR provides features like garbage collection so that under regular
operations, developers don’t need to worry about the mechanics of working with mem‐
ory management and other important bits and pieces.
Philosophical Differences
Where this starts to get untidy is that WinRT and .NET are philosophically very differ‐
ent. .NET is inspired by Java, and the big compromise with a system where memory is
managed by garbage collection is that you inevitably cede control to the framework. If
you’re building an operating system (like the Windows Division—aka WinDiv—team
within Microsoft), or building a major software product like Office, you wouldn’t start
with Java. Java, and by extension .NET, is too abstract, too “magical” for building that
sort of software. But most of us don’t build “that sort of software”; what most of us do
is work within very small budgets to build relatively small-scale applications where the
compromise of working within an execution environment like the CLR is much less
keenly felt.
As .NET developers, we have to learn to play nicely within this philosophical difference
imposed by a shift to WinRT, and therein lies the challenge. It should be said, though,
that the general premise of this is, in my opinion, a bit broken. While the rationale for
moving away from .NET and back to COM is understood, it’s not necessarily a good
idea. It would have been better in many ways if Windows Store apps had been built more
squarely on .NET, and the oddities that come into play because Windows Store apps are
fundamentally COM-based were negated. However, we are where we are.
In terms of the assumptions that I’m going to make, I’m assuming that the readers of
this book are on the spectrum of “reasonably familiar” with .NET up to “very familiar”
with .NET. I’ll also assume that most of the modern .NET concepts up to and includ‐
ing .NET Framework v3.5 are understood—we’re going to be seeing a lot of generics.
We’ll be seeing a bit of Linq (but I will go through that). I’ll assume no knowledge of
2 | Chapter 1: Making the Transition from .NET (Part 1)
28. the Task Parallel Library (TPL)—which we’ll be using a lot. As long as you can put
together production-quality code in .NET, you’ll be covered.
Most .NET developers will have been working on ASP.NET applications, so again I’m
assuming that this is the user interface technology of choice for most readers of this
book. For our Windows Store apps we’re going to be using the XAML user interface
track (more later). XAML is aligned with Silverlight and Windows Presentation Foun‐
dation (WPF), although I’m going to be assuming most readers of this book have little
or no Silverlight/WPF/XAML experience.
Objectives
In the next two chapters, our objective is to get a Windows Store app built, with a user
interface,andsomebusinesslogicthatcancalluptotheserver.We’realsogoingtoprove
that we can build a unit test library to run alongside the application. Specifically:
• We’ll build a new Windows Store app project in Visual Studio 2012. The purpose
of this is to learn about the new project templates, and understand the difference
in emitted outputs between the new-style Windows Store app projects and old-
style .NET projects.
• Within that project, we’ll build a new page in XAML, and from there we’ll look at
building in the infrastructure to support Model/View/View-Model (MVVM). (I’ll
explain what this is shortly.) We’ll also look at building support for inversion of
control. (Again, if you don’t know what “inversion of control” is, you will find an
explanation later.) The code will look to call up to a publicly accessible server. In
the first instance, we’ll fake this call and simulate the server.
• We’ll take the view-model that we built and wrap a unit test around it, just so that
we know that we can.
• Once we know we can test the model, we’ll build the real implementation of our
server communication. We can then test our app end-to-end and know that it’s
working.
The New Project Templates
The first thing to get a handle on is that the version of .NET used in Windows Store
apps is a cut-down, limited version of .NET referenced internally as .NETCore. There’s
precedent for Microsoft creating subsets of .NET; one example is the .NET Compact
Framework used in Windows CE. Another is the Client Profiles introduced in v3.5 that
are “optimized” for client applications. Likewise, the toolset for Windows Phone 8 is a
cut-down version of the Silverlight libraries, which in turn is a cut-down version of
WPF.
Objectives | 3
29. The motivation behind all of these “cutting down” operations is to limit what developers
can do. There are a few reasons Microsoft might want to do this. One argument is that
the Microsoft engineers might want to make a given API set more secure by removing
exploit vectors. However, another important reason why Microsoft engineers will do
this sort of thing is to “create a better experience.” What this actually means is that
Microsoft’s engineers will control the API such that you as a developer can’t do things
that make Windows 8 look bad.
A good example of this is battery life. When you’re using Windows 8 on a tablet, battery
life is very important. The longer the battery lasts, the happier the user will be. If Mi‐
crosoft designs the API so that it’s hard for you as a developer to do things that use a
relatively high amount of battery power, the battery life as the user perceives it will be
better, and hence the user will perceive Windows 8 as being a good tablet operating
system.
You can see this idea exemplified in background tasks, which we’ll
look at in Chapter 14.
So we can only access the bits of the framework that happen to be in .NETCore. You
should note that even if you could violate this rule, you probably wouldn’t want to, as
the app would not pass certification for inclusion in the Windows Store—something
we’ll talk about in Chapter 15.
WinRT Metadata
A standout excellent feature of .NET available from introduction was the level of detail
included within its metadata system. (Metadata at its most basic in this context is simply
a description of how all the types and members within them are structured.) Each .NET
assembly could describe itself to a hitherto unrealized level of detail. Conversely, normal
Windows DLLs had very little metadata—essentially just an EXPORTS table of func‐
tions that could be called. COM sat somewhere in the middle by being mostly self-
descriptive using IDL, but the level of detail was nothing like the .NET metadata. (Plus,
consuming COM metadata was a chore, whereas consuming .NET metadata was a
breeze.)
WinRT is, under the hood, COM with knobs on—COM++, if you will. (Although don’t
call it that because you will get looked at peculiarly.) Microsoft borrowed .NET’s met‐
adata subsystem for use within WinRT. Thus, when you compile a WinRT DLL you get
a.winmdfilethatcontainsboththemetadataandthebinaryexecutablecode.Theformat
of the metadata within that .winmd file happens to be compatible with .NET’s.
4 | Chapter 1: Making the Transition from .NET (Part 1)
30. The .NET behavior is unchanged—compile a .NET assembly, and the
metadata gets embedded within as before.
What all this means is that the interoperability story between these two worlds is rather
good. Because both parties understand each other well thanks to the shared metadata,
Microsoft’s job in getting actual calls going between the two is straightforward.
As most of you are likely familiar with the structure of .NET assemblies, I’ll take you
throughthestructureofthenewassembliesusingReflectorandwe’llseehowaWindows
Store application references the central WinRT components. (If you don’t know what
Reflector is, we’ll look at that in a short while.)
To begin with, we can create projects within Visual Studio in the usual way. Figure 1-1
illustrates adding a new C# Windows Store “Blank App” project to an existing solution.
Notice how the Windows Store projects have their own entry in the tree away from
the .NET projects that you’re used to creating normally.
Figure 1-1. Options for a new Windows Store app project
If we create a new project—I’ll create a Blank App type for this illustration—we can look
under References in Solution Explorer and see something like Figure 1-2.
ThislooksquitedifferentfromtheReferencesviewofanormal.NETproject;whatwe’re
actually seeing here are placeholder references to the actual libraries and assemblies that
the project will compile against. Specifically, these are references to the .NETCore as‐
sembly set and the core Windows WinRT libraries.
The New Project Templates | 5
31. Because the rules are set in stone as far as what you have to refer‐
ence in order to be a proper Windows Store app that gets through
store certification, you can’t change these references.
Figure 1-2. Placeholders for the .NETCore assembly and Windows WinRT libraries
What Visual Studio is doing here is representing bundles of referenced assemblies/
libraries as single items. In the normal .NET world, these would be a discrete set of
explicit assemblies. We can use Reflector to get a better view of what’s going on.
For the uninitiated, Reflector is a popular .NET tool that allows you
to see the structure of types and members within an assembly, and
also decompile it. See the Reflector website.
Ifyouwanttofollowalong,downloadatrialcopyofReflectorifyoudon’thavealicensed
copy. If we point Reflector at the output assembly—which happens to be called Struc
tureFoo.UI.exe in my example—we’ll see something like Figure 1-3. What this is
showing us is a bunch of regular .NET assemblies that make up .NETCore (System.Col
lections, etc.) and a reference to Windows. (Looking back at Figure 1-1, we see
something different. Visual Studio just showed us one item, “.NET for Windows Store
apps.” Reflector is showing us the actual references.)
The Windows reference isn’t an assembly—it’s a reference to the WinRT metadata file.
With the information in that file, the runtime is able to bind through to the unmanaged,
native code components that contain the implementations. When we get going, you’ll
6 | Chapter 1: Making the Transition from .NET (Part 1)
32. 1. Thunking is the process of making calls across system boundaries. In this context, it refers to making calls
from the “managed code” world of .NET to the unmanaged world of WinRT.
see that under the hood this thunking1
down to WinRT happens a lot, but you wouldn’t
even know it was happening unless you looked really hard.
Figure 1-3. The actual references in the output assembly
If you select the Windows entry in Reflector, you’ll see something like Figure 1-4. (The
version of Reflector that I’m using at the moment cannot automatically reference the
metadata.) Notice the version number of 255.255.255.255—this is a good hint that we
are referencing WinRT metadata and not a .NET assembly.
The metadata file that it’s looking for is stored in C:Program Files (x86)WindowsKits
8.0ReferencesCommonConfigurationNeutralWindows.winmd. That folder tree
happens to be the WinRT development kit.
If we go into Reflector and tell it where to find Windows.winmd, we’d find something like
Figure 1-5.
The New Project Templates | 7
33. Figure 1-4. Prompting for the Windows metadata
Figure 1-5. Linking through to the Windows WinRT library reference
You’ll notice a reference to mscorlib, implying a reference back to .NET from WinRT.
Ignore that—it’s a red herring. It’s an artifact of the metadata system being a .NET thing
that’s been repurposed for WinRT.
8 | Chapter 1: Making the Transition from .NET (Part 1)
34. Figure 1-6. Disabled target framework and selectable project types
What I’ve tried to show here is how the worlds of .NET and WinRT interoperate. What
we’ve done is created a more or less standard .NET executable assembly, and referenced
a collection of normal .NET assemblies and also the WinRT libraries.
To close this loop, let’s go back into Visual Studio and look at the project settings and
adding references.
Project Settings and Adding References
Thefirstpointofinterestisthatifweopenupthepropertiesforourproject,you’llnotice
that we can’t change the target framework. In a normal .NET project, we would be able
to change the target framework and this option would not be greyed out. (Although
obviously this is how it is at the time of writing, I’m actually expecting this to change as
I assume that ultimately multiple framework versions will be supported on the various
devices.) You’ll also notice that the output types are different—we can create a Windows
Store App, a Class Library, or a Windows Runtime Component. Figure 1-6 illustrates.
The New Project Templates | 9
35. Figure 1-7. With .NETCore selected, we can’t choose any other assemblies in the way
we usually can with normal .NET projects
The Windows Store App is a normal, deployable-and-runnable executable. The Class
Library is a .NET assembly that can be consumed from managed code. The WinMD
File is used in scenarios where you want to consume the assembly/library from Java‐
Script or C++/CX. That latter case is out of scope for this book, although we will touch
on it in Chapter 14 when we look at background tasks. Generally, in the work we do in
this book we’re going to create one executable and a support library to go along with
it. Let’s turn our attention now to references.
In Visual Studio 2012, the dialog has changed for adding references.
Thankfully, we now have a search option!
If you right-click on the project in Solution Explorer and select Add Reference, you’ll
see something like Figure 1-7. Note how we cannot add any Framework references. In
Metro style we are given .NETCore, and that’s all we’re allowed to have. We can’t add or
remove any part of those references. Notice also at the top that it reads “Targeting: .NET
for Windows Store apps.”
Likewise, although I haven’t included a screenshot of this, if you select Windows from
the tree (i.e., “WinRT libraries”), you’ll see a similar story.
The Solution option lists the projects in the solution. This works in the way that you
would expect: simply select the projects whose output you want to reference, and you
10 | Chapter 1: Making the Transition from .NET (Part 1)
36. should be good to go. Use some caution, however, as there’s nothing to stop you doing
things such as adding a normal, full .NET class library project and trying to reference
it. You’ll get an error if you do this, but it’s not a particularly descriptive error—it just
reads “Unable to add a reference to project <projectName>.”
You can use the Browse option to add any assemblies that you fancy,
although your mileage will vary. I, for example, added a reference to
a normal .NET 2.0 assembly. The reference went in fine, but it com‐
plained about classes missing from mscorlib. This makes sense if
you consider that things will be missing from .NETCore.
Building a Basic User Interface
Now that we’ve explored how the Windows Store projects are put together, we can look
at how we build the user interface.
UI Tracks
You can build Windows Store apps using one of three user interface tracks, which are a
combination of a display technology and a coding language.
In this book, I’m going to be basing the work we do on XAML, and I’ll talk about this
in much more detail in a moment.
I’ve excluded DirectX/C++ from this book for the reason that it’s more
aimed at developing games, and this book isn’t about building games.
HTML
The HTML5/CSS3/JavaScript track is actually more interesting and in many ways
hugely appropriate to developers looking to target Windows 8 and Windows RT. In the
HTML5 scenario you build a self-contained, locally executing web application that runs
inside of IE on the device. It’s packaged up just like a normal Windows Store application.
(We’ll talk about application packaging in Chapter 15.) The language you use to build
the application is JavaScript. Just for clarity, you don’t get any backend, server-side ex‐
ecution (à la ASP.NET) with this—it’s all done with JavaScript, although in this new
world you have WinJS, which can get into the full WinRT library. (The prevailing
wisdom is that it’s this capability to thunk down from WinJS into WinRT that caused
Microsoft’s engineers to eschew basing Windows Store apps entirely on .NET.)
You might also be interested to know that the standard Mail, Calendar, and People apps
in Windows 8 are based on the HTML5 track rather than the XAML track. However,
Building a Basic User Interface | 11
37. that seems to be unusual. My informal analysis of the store at various points during the
later half of 2012 shows that XAML tends to be much more popular, with about 70% of
apps released into the Store being XAML-based. Moreover, there’s a skew toward apps
that repackage web content being more likely to be HTML5-based.
On paper, the ability to build apps using HTML5 is incredibly appealing and very sen‐
sible. With the market consolidation that’s going on at the time of writing (early 2013),
it’s hard for people investing in software to know where to put their money. Targeting
a platform-neutral technology like HTML5 seems like a winning plan because any in‐
vestment you do make can be taken to other platforms in a way that follows profit
without dramatically increasing complexity.
However, what that doesn’t account for is that in the post-PC world, the user experience
(UX) argument tends to be very strong, and it’s typically the case that users demand
apps that have a high degree of “slickness.” It’s counterintuitive to suggest that a platform
that is inherently a compromise (i.e., HTML and the Web) can offer this slick user
experience.(Itendtocallthissortofapproach“nearnative”asittendstobegoodenough
to be operational, but not classifiable as “native.”) The iPad is a popular device because
the apps are so good, and those apps tend to be based on the native toolset provided by
Apple. Even though cross-platform technologies are available for iPad (in particular,
Apache Cordova née PhoneGap), their adoption tends to be low, as developers under‐
stand that compromising UX is typically a move that harms the proposition in the post-
PC world.
There are other incidental problems with using HTML5 to gain cross-
platform advantage with a Windows tablet strategy, the main one
being that the UI metaphors used in the modern UI design aesthet‐
ic tend to be horizontally biased, whereas the Web itself is vertically
biased. You have to wonder how much you really gain from going
down an HTML5 route.
Better experience
When we think about our UI track for Windows Store apps, it follows that the native
experience should offer a better UX. This means using the XAML track, not the HTML5
track, given that the XAML track is the native UI technology for Metro style, as opposed
to HTML5, which is the cross-platform, “near native” choice. You may choose to read
the word compromise where I have written choice in that last sentence.
There are two ancillary considerations here. First, we know Microsoft can execute on
native UI technologies better than it can execute on web technologies. The second ar‐
gument is that Silverlight developers are likely to migrate to Metro-style development
before other types of developers, and they will likely gravitate toward the XAML track
because there’s a natural evolution there. This will likely increase the volume and quality
12 | Chapter 1: Making the Transition from .NET (Part 1)
38. of community-created content around the XAML track. Working with technology
where there is greater community involvement tends to be easier. You should note that
it appears that building Windows Store apps in HTML5 seems to be more difficult than
building the equivalent apps in XAML, although this statement in particular is relatively
subjective.
But what actually is the XAML track?
During the development of Longhorn—the codename for what would eventually be
called Vista—Microsoft had a new vision for replacing the subsystem that composed
the user interface within Windows. This new vision was called Windows Presentation
Foundation, or WPF. At the time, the existing Windows UI composition engine, GDI,
wasextremelyoldandold-fashioned.WPFwastobeanewenginebasedonadeclarative
model rather than a programmatic model. (In GDI you have to write code to specifically
place UI elements on the screen.) A declarative model would look much more like
HTML, which was popular for obvious reasons. Thus, eXtensible Application Markup
Language (XAML) was born. WPF was bundled into .NET 3.0 and happens to use
DirectX to physically arrange pixels on the screen.
InternallywithinMicrosoft,WPFdidnotget(andhasnotgotten)muchtraction,mainly
because it was based on .NET. We’ve already spoken about how the Windows Division
and the Office/Business Division don’t like managed code—WPF is entirely a managed
code proposition. In hindsight, that core division was never going to use it.
After WPF was released, Microsoft decided that it wanted to compete with Adobe Flash
and created a new product called Silverlight to do just that. The idea of Silverlight was
that it would run inside a web browser (the Microsoft engineers’ vision of this was that
it would run as an ActiveX control within IE). At this time, most of the interest in .NET
was around line-of-business (LOB) applications that were either built as web applica‐
tions (ASP.NET) or as desktop applications using Windows Forms; this happens to be
a wrapper over GDI. Without internal adoption within Microsoft, or really much need
to use it as a replacement for Windows Forms, Silverlight became a common delivery
vector for WPF.
As a Flash competitor, Silverlight didn’t gain much ground. The timing was off—by this
time, Flash was looking past its best and HTML5 was getting much better. Some de‐
velopersstartedtoadoptSilverlightforinternalLOBapplicationsdeployedasSilverlight
applications running “out of browser” (OOB). What actually happened, though, in the
end, was that by the time Silverlight and WPF were effectively deprecated, Silverlight’s
use as a foundation technology for private LOB apps was quite well established.
Now let’s look at what happened with Windows Phone. When Microsoft junked Win‐
dows Mobile and moved over to Windows Phone, it needed a UI platform and chose
Silverlight. More accurately, it chose Silverlight and cut it down as previously discussed.
Building a Basic User Interface | 13
39. “Silverlight for Windows Phone” is the only game in town for building nongame apps
on Windows Phone.
So if you loop that in, you have native WPF being used hardly anywhere, Silverlight
having no traction on the Web, Silverlight having some traction in private OOB appli‐
cations, and Silverlight being the only option for Windows Phone.
The next thing is that we have Microsoft wanting to “reboot” the way that we build
Windows applications, and to do this it takes WinRT and also takes WPF and divorces
it from .NET. As part of this process, Microsoft dumps the WPF name and goes with
XAML. XAML then becomes unmanaged—that is, native implementation built using
WinRT components housed in WinRT libraries. This is why XAML is not called “WPF”
in WinRT—the former is unmanaged and the latter is managed.
Importantly, the API remains roughly compatible. For example, in WPF there is a class
called System.Windows.Controls.Button that represents a button on a page. It so hap‐
pens that this class has a Content property available that can be used for setting the text,
and a Click event available that is raised when the user clicks it. This is a managed code
housed in the System.Windows.dll assembly. Over in WinRT/XAML, our button rep‐
resenting class is called Windows.UI.Xaml.Controls.Button. This is an unmanaged
implementation of the same control—it supports Content, Click, and other members
—but this time it’s unmanaged and implemented via a WinRT control referenced
through the Windows.winmd metadata. (You will find some rough edges to this model,
but this “compatible API” approach is the general shape of the solution.)
XAML Parsing Basics
The killer problem with coming to XAML cold is that if you’re used to HTML, it’s easy
to look at it and wonder why on earth Microsoft didn’t just use HTML. To understand
why XAML exists, you need to understand the difference between it and HTML.
HTML is a document markup language. The original vision was that you start with
some text and annotate it such that areas of the document appear different (e.g., bold,
italics) or behave differently (e.g., link to another document). Over time, as a developer
community using many different types of technology, we’ve taken that foundation and
turned it into a way of declaring a user interface.
XAML is the other way around. It starts from the basis that you’re not trying to describe
a document, you’re trying to describe a user interface. As it was born to support Win‐
dows,whatyou’reactuallylookingtodoisdescribewindowsanduserinterfaceelements
within. HTML is a document that needs to be parsed and interpreted. XAML is just an
object graph expressed as XML.
The following is some sort of XAML. I’ve removed some of the attributes to make it
easier to understand, so this code won’t actually work:
14 | Chapter 1: Making the Transition from .NET (Part 1)
40. <Page>
<StackPanel>
<Button Content="Foo" />
<Button Content="Bar" />
</StackPanel>
</Page>
The XAML parser works on a fairly simple basis. It walks the XML Document Object
Model (DOM), creating instances of classes as it goes. Starting with the Page, the first
element that it reaches is called StackPanel. The XAML parser will find a type with that
name (given that it has a list of candidate namespaces to try, which is one of the things
I’ve taken out of the XML in order to make it simpler), create an instance from it, and
add it to the Content property of the current UI element under consideration—in this
case, the page. This continues; the next element is a Button, which is added to the
Children property of the panel. At this point we are looking at an element that has
attributes, and the values in the attributes are set to properties found on the control.
(This is as per ASP.NET’s parsing behavior, incidentally.) The next element is another
Button, and so on.
In many ways, this is how an HTML parser works in terms of creating its own internal
HTML DOM representation, but seeing as HTML doesn’t have to be valid XML, the
XAML parser’s job is much easier. (And there’s very little ancillary information about
scripts, alternate views, styles, and so forth like you get with HTML.)
In this book, it’s not my intention to tell you how to build beautiful
and wondrous apps using XAML. That would involve going into too
much detail on the construction of the user interfaces, whereas my
goal is to show you how to get things happening, functionally. There‐
fore, I’ll focus on pointing you to various helpful controls and look‐
ing at how to implement common constructs.
Building a Basic Page
We’ll now start building a basic user interface. Specifically we’re going to build a regis‐
tration form that will capture a username, email address, and password, and have a
button. It’ll look something like Figure 1-8.
Building a Basic User Interface | 15
41. Figure 1-8. The intended layout of our registration form
App Bars
You should note that the Register button in Figure 1-8 is probably in the wrong place if
we consider Windows 8 UX guidelines. The button should be positioned more properly
on the app bar, which is the little panel that winds up from the bottom of the screen
when you want to access more options. (You do this either by swiping up or down from
the edge of the screen, or using the right mouse button.)
However, the situation is slightly complicated by the fact that if the action relates to the
primary purpose of the form, you can put it on the main view. Oftentimes apps don’t
do this—they leave the button on the app bar but show the app bar rather than asking
the user to show it.
Thissituationiscomplicatedfurtherbysomeapps—notablythebuilt-inMailapp,which
shows the New button, for example, in the top-right of the page.
We don’t get into building app bars until Chapter 4. For now, we’ll leave the button here.
In Chapter 4 we’ll discuss proper placement and grouping more fully.
Throughout this book, we’re going to be using a publicly accessible service that I’ve
created and hosted on AppHarbor. (If you’re unfamiliar with AppHarbor, it’s a .NET
platform-as-a-service provider that I heartily recommend. You can find it at AppHar‐
bor’s website.) The business problem that the service solves was discussed in the preface
—to recap, the idea that individuals can report problems in their local environment. For
example, the individual might spot some graffiti or litter and wish to have it removed.
My reason for choosing this “problem domain” is that it contains all of the common
16 | Chapter 1: Making the Transition from .NET (Part 1)
42. components of mobile apps—specifically, working with accounts, taking and uploading
photos, reviewing historical data, and capturing location. What we’ll implement in this
next part of our work is the account registration. We’ll capture the new user’s details
and send it up to the server, whereupon the user can perform other functions such as
creating new issues. I’ll be referring to the application as StreetFoo.
To get started, we need a new solution and project within Visual Studio. As a rule, I like
to create a blank solution first, and then add projects into that solution. (I find this
creates the most logical and natural folder structure on disk.) However you do it, create
a new Visual C# by navigating to Windows Store→Blank App project and call it Street‐
Foo.Client.UI. Figure 1-9 illustrates.
Figure 1-9. The structure of a newly created Windows Store→Blank App project
In Figure 1-9, the assets are relatively obvious—these are the various graphics that we
need to drive the application. (We’ll look at these later.) We already discussed the Ref‐
erences node earlier in this chapter. Properties and its attendant AssemblyInfo.cs are
unchanged from .NET.
App.xaml is a cross between the Global.asax file in ASP.NET and the void static
main method used to boot Windows Forms and console application executables. The
boilerplate code in here responds to the Launched event and creates the first page to
view. (We’ll learn more about application lifecycle events in Chapter 14.)
MainPage.xaml is the default page that gets created. We’ll delete this and replace it with
RegisterPage.xml shortly.
Package.appxmanifest contains metadata about the application that affects how the ap‐
plication is deployed (i.e., installed) and what it can do. (If you happen to have done
Building a Basic User Interface | 17
43. Android development, it’s analogous to how manifests work on that platform.) We’ll
see various facets of this as we go, but for now we don’t need to worry about it. Likewise,
we also don’t need to worry about the .pfx file down at the bottom. This is used for
signing, but we’ll talk more about that in Chapter 15.
Out of the box, a standard project template doesn’t really do much—all you get is an
app that will install and show a blank page. However, there is a sort of “subproject” that
we can trigger, and when we do that we get a whole load of additional templates and
functionality. This additional functionality does things like adding a set of default styles,
creating a page layout that has a default header, and creating pages that supports even
the smallest window size for this type of application. (We talk about this more in Chap‐
ter 12.)
To access this extra functionality, first delete MainPage.xaml and then add a new item
to the project of type Basic Page and call it RegisterPage.xaml. Visual Studio will prompt
you to add the missing files.
When we do this, the Windows Store app project template will add a new folder called
Commontotheproject,andthisfoldercontainsawholebunchofnewstuffthatsupports
thespecialtemplates.Thereadmefileinthisfolderoffersastarkwarningthatdevelopers
are not supposed to change the contents of the files in this folder, as it’ll break the VS
project template. You can take this with a grain of salt; like all these things, you have to
tread relatively carefully, but it’s hard to do any real damage.
I mentioned that the code in App.xaml was responsible for starting the application. The
code that was created on project inception contains a reference to the MainPage class.
However, we deleted the MainPage class from the project when we deleted Main
Page.xaml. We need to replace the reference with a reference to RegisterPage.
Open up App.xaml and change the OnLaunched method to use RegisterPage:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already
// has content, just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate
18 | Chapter 1: Making the Transition from .NET (Part 1)
44. // to the first page
rootFrame = new Frame();
if (e.PreviousExecutionState ==
ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the
// first page, configuring the new page by passing required
// information as a navigation parameter
if (!rootFrame.Navigate(typeof(RegisterPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
If you run the project, you should see something like Figure 1-10.
The XAML for that page is quite verbose, so I won’t reproduce it all here. However,
here’s an important part of the layout that we need to consider:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<AppBarButton x:Name="backButton" Icon="Back" Height="95"
Margin="10,46,10,0"
Command="{Binding NavigationHelper.GoBackCommand,
ElementName=pageRoot}"
Visibility="{Binding IsEnabled, Converter=
{StaticResource BooleanToVisibilityConverter},
RelativeSource={RelativeSource Mode=Self}}"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
Building a Basic User Interface | 19
45. Figure 1-10. Preview of our newly created page
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{StaticResource AppName}"
Style="{StaticResource HeaderTextBlockStyle}"
Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap"
VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
<!-- deleted for brevity... -->
</Grid>
This is where we can start to see the divergence between XAML and HTML. Back in
the day we would have laid out this HTML using TABLE controls, and if you look at
that XAML from that perspective we don’t have any TR or TD elements to help us. (Of
course, now we’re supposed to do that sort of layout using DIV elements and attendant
CSS declarations, but I digress.) What we have instead is one Grid control inside of
another. We also have some magic going on where we define RowDefinition values to
lay out the rows, and ColumnDefinition values to lay out the columns. You’ll also notice
that we can put elements inside of grid cells by using Grid.Column attributes on the
controls. HTML and CSS, this is not.
20 | Chapter 1: Making the Transition from .NET (Part 1)
46. Understanding XAML
What XAML is trying to do for us is deal with a world where we want a very explicitly
laid out user interface (much as we would have done with very old technologies such as
raw Win16/Win32 calls, MFC, VB, etc.) but with certain flexibilities, such as making it
easiertodealwithviewsthatresize,andalsoofferingsomeadvantagesthatyougenerally
get from declarative user interfaces. Windows Forms introduced some of these ideas
through standard Dock and Anchor properties on the controls. XAML is an extension
of that kind of approach, as opposed to what HTML has evolved into. XAML is very
much “windows”-based (lowercase w), whereas HTML is still based on documents.
Importantly, XAML is much more precise. In the first row definition, we’re specifying
a specific pixel value. This is not a minimum value, or some value that gets changed
depending on other content, unlike HTML and CSS. If we say “140” pixels, we’re going
to get 140 pixels regardless.
Before we go on to create the form, we want to change the header. At the moment, the
header is defined in a TextBlock control, with a Text value that refers to a StaticRe
source.
Here’s a portion of the XAML markup that was created when RegisterPage.xaml was
created:
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<AppBarButton x:Name="backButton" Icon="Back" Height="95"
Margin="10,46,10,0"
Command="{Binding NavigationHelper.GoBackCommand,
ElementName=pageRoot}"
Visibility="{Binding IsEnabled, Converter=
{StaticResource BooleanToVisibilityConverter},
RelativeSource={RelativeSource Mode=Self}}"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{StaticResource AppName}"
Style="{StaticResource HeaderTextBlockStyle}"
Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap"
VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
Building a Basic User Interface | 21
47. When attribute values are surrounded by braces in that way, this tells the XAML parser
that regular processing needs to stop and something else needs to happen. These are
called markup extensions. StaticResource is one type of extension. In the next section,
we’ll meet Binding. (There’s one of these references in the Button control in that snippet
that happens to show or hide the default back button depending on whether the page
is at the top of the stack or not.) For now, replace the Text value with Register. Here’s
the code:
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<AppBarButton x:Name="backButton" Icon="Back" Height="95"
Margin="10,46,10,0"
Command="{Binding NavigationHelper.GoBackCommand,
ElementName=pageRoot}"
Visibility="{Binding IsEnabled, Converter=
{StaticResource BooleanToVisibilityConverter},
RelativeSource={RelativeSource Mode=Self}}"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="Register" Style="{StaticResource
HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap"
VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
You’ll see the WYSIWYG preview update as you make this change.
Next we’ll restructure the page so that we have a single Grid control that occupies the
whole page. The default layout is designed for views that scroll off the right side of the
page. What we want for our form is just a place to enter some values underneath the
caption. Therefore, if we redefine the grid with a row at the top 140 pixels high and a
column on the left 120 pixels wide, we can put the back button in the top-left cell, the
label in the top-right, and the form in the bottom-right. (We need the back button, as
ultimately when we start the app we’ll present the logon page and have a button that
takes us into the registration page.)
This is now where we can use the StackPanel control. This is a very useful control for
laying our controls vertically (the default) or horizontally. We’ll also use TextBlock
22 | Chapter 1: Making the Transition from .NET (Part 1)
48. controls (which are labels), TextBox, PasswordBox, and Button controls. Here’s the
modified markup for our form. Figure 1-11 shows what we’re aiming for.
<local:StreetFooPage
x:Name="pageRoot"
x:Class="StreetFoo.Client.UI.RegisterPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:StreetFoo.Client.UI"
xmlns:common="using:StreetFoo.Client.UI.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- Back button and page title -->
<AppBarButton x:Name="backButton" Icon="Back" Height="95"
Margin="10,46,10,0"
Command="{Binding NavigationHelper.GoBackCommand,
ElementName=pageRoot}"
Visibility="{Binding IsEnabled, Converter={StaticResource
BooleanToVisibilityConverter}, RelativeSource=
{RelativeSource Mode=Self}}"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="Register" Style="{StaticResource
HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap"
VerticalAlignment="Bottom" Margin="0,0,30,40"/>
<!-- Registration form -->
<StackPanel Grid.Row="1" Grid.Column="1">
<TextBlock Text="Username"></TextBlock>
<TextBox HorizontalAlignment="Left" Width="400" Text="{Binding
Username, Mode=TwoWay}"/>
<TextBlock Text="Email"></TextBlock>
<TextBox HorizontalAlignment="Left" Width="400" Text="{Binding
Email, Mode=TwoWay}"/>
Building a Basic User Interface | 23
50. “They’re small footprints,” went on Joe, “about the size of the feet
of Margie and Lucy. Of course, other girls could have made these
marks,” he admitted. “But when we know we heard Margie and Lucy
yelling for help and find footprints of girls’ shoes here why, it’s pretty
certain Margie and Lucy were here.”
“I think so, too,” admitted Teddy. “The question is where are the
girls now?”
“And where are our planes?” asked Joe.
“And where is the deer?” added Dick. “Gosh, we’ve got three
mysteries here instead of one, I guess.”
“Look over here,” and Teddy directed the attention of his chums to
another bare patch. “The deer was here and he was sort of jumping
around heavy. The hoof marks are deeper.”
Teddy’s chums agreed that this was so and Joe exclaimed:
“Gosh, fellows, it looks as if that deer bashed up our planes and
then made off with Margie and Lucy.”
“How could he do that?” Teddy inquired.
“Well, by jumping up and down on the planes, he could easily
bash them to bits.”
“There’d be some pieces left,” Dick argued.
“Yes, I guess there would be unless the deer ate them,” Joe had
to admit.
“And how do you figure the deer took the girls away?” asked
Teddy.
“On his back, maybe,” declared Joe. “He was a pretty big deer,
and he acted sort of savage. I’m sure that’s what happened. The
51. deer broke our toy planes. Then the girls came along and the deer
rushed at them, tossed them over his head with his horns and—”
“And, I suppose,” laughed Teddy, “Margie and Lucy landed on the
deer’s back and went hitch-hiking.”
“Well, I guess that couldn’t exactly happen,” replied Joe with a
funny little smile. “But something has happened, all right. Model
airplanes don’t disappear and deer don’t suddenly appear and sisters
don’t vanish after they cry for help—not unless something has
happened.”
“This sure is a mystery, fellows!” Teddy exclaimed. “Isn’t it queer
how I always seem to get mixed up in a mystery? First it was a dog
and then a monkey and now—”
“The way it looks to me,” interrupted Joe, “is that you have all the
mystery fun, Teddy.”
“That’s right!” chimed in Joe. “We hardly ever get a chance.”
“Say, look here!” cried Teddy. “That’s right. But you fellows are
going to be in on this mystery. How about forming a Mystery Club?
Just us three?”
“Swell!” exclaimed Joe.
“All right,” went on Teddy. “Then the Deer Mystery Club is hereby
formed. What’s the first order of business?”
“I think,” said Joe, “we ought to notify the police that our toy
planes are missing.”
“And so are Margie and Lucy,” said Teddy. “The girls ought to
come first. If they have really disappeared, I think we should—”
He was interrupted by a loud voice shouting:
52. “Get out of there! Get out of my meadow! Get out!”
54. CHAPTER VI
FATTY NOLAN
Teddy Benson and his two chums were so surprised, for a moment, at
hearing the ordering voice that they made no move to obey. They
assumed, of course, the order was for them. Though it was the first
time they had ever been told to get out of Mr. Mason’s meadow. But
the voice cried again:
“Get out, I tell you! I don’t want you in my meadow spoiling the
fodder. Next I know you’ll be eating all my corn and beans! Get out
before I get my gun!”
“Say, he can’t mean us!” exclaimed Teddy. “Mr. Mason wouldn’t
talk that way to us.”
“Besides,” added Joe. “We aren’t hurting his meadow fodder.”
“And we surely aren’t going to eat his corn and beans,” said Dick.
“What’s he mean—talking about getting his gun?”
“I have it!” suddenly exclaimed Teddy. “Mr. Mason must mean the
mysterious deer. He’s trying to drive the deer away. They eat garden
crops, you know.”
“But is this Mr. Mason?” asked Joe.
The boys learned, a few seconds later, that it was Mr. Mason,
owner of the meadow, who had been so angrily shouting. They saw
him as they walked up out of a little hollow to the top of a small hill.
They also saw the farmer throwing stones at some object they could
not see.
55. “It must be the deer,” said Teddy.
Just then Mr. Mason turned and caught sight of the three boys. He
walked toward them, asking:
“Is that your deer that’s been running around my meadow?”
“No, sir,” answered Teddy, “it isn’t ours.”
“Did you see a deer?” asked Joe.
“I certainly did. Quite a big one, too.”
“Did it have any girls on its back?” asked Dick.
“Girls? Land sakes, what do you mean? What girls?” asked Mr.
Mason, much surprised.
“My sister, and Teddy’s,” explained Dick. “Did you see them on the
deer’s back?”
“I should say not! What do you think it was? A circus deer?”
“It’s a mystery deer,” said Teddy.
“Oh, then it is your deer!” cried Mr. Mason. “Why didn’t you say so
at first? I don’t like deer, mystery or any other kind, making free with
my farm. Where did you get this deer, anyhow?”
“We didn’t get him. He isn’t ours. We just saw him,” said Teddy.
“Which way did he go?”
“I stoned him back into the woods,” said Mr. Mason. “Oh, I didn’t
hit him with any stones,” he was quick to add. “I wouldn’t hit any
animal with stones. I just pegged a few rocks up close to him, so
he’d know he wasn’t wanted. He went for the woods in high gear.
But what do you fellows know about this deer? And what do you
mean,” he continued, looking at Dick, “by girls on the deer’s back?”
56. “Well, my sister has disappeared,” said Dick. “So has Teddy’s. And
two of our toy airplanes are missing. We found a place where the
deer had been jumping around in your meadow.”
“And we found a place, near there, where the girls had been,” put
in Teddy. “We thought maybe the deer went for the girls and got
them on his back and—”
“Say,” laughed Mr. Mason, “you’re Teddy Benson, aren’t you? The
boy who was mixed up with a mystery dog?”
“Yes,” Teddy admitted, “I was. And so was my sister.”
“And now you’ve got a mystery deer on your trail. Well, my boy,
there were no girls on the back of the deer I saw. So you needn’t
worry about that. But how did you come to see this deer, anyhow?
And where is he from?” asked Mr. Mason.
The boys told of first seeing the deer when they went in the
woods to look for Teddy’s plane. As to where the deer had come
from, they could give no information.
“Most likely from a circus,” decided Mr. Mason as he listened to the
boys’ story.
“But there hasn’t been any circus around here,” Teddy objected.
“That’s so,” agreed the farmer. “Well, anyhow, there’s a deer
around here and I’ll have to notify the game warden to get rid of
him. There may be more than one of the animals. I can’t afford to
have my crops ruined.”
“We thought you said something about getting your gun,” said
Teddy.
“Oh,” laughed Mr. Mason, “that was just to scare the pesky deer. I
wouldn’t have shot him. In the first place, it’s against the law to
57. shoot deer now. Out of season, you know.”
“Yes,” murmured Teddy.
“And in the second place,” went on the farmer, “I wouldn’t shoot a
deer, anyhow. All I wanted was to scare him off my place, and I
think I did; either with the stones which didn’t hit him, or by my talk
of the gun. Of course, it was only talk,” he resumed with a laugh.
“But sometimes strong talk does a lot of good.”
“Do you want us to let you know if we see that deer again?” asked
Joe.
“If it’s on my land, yes. But I don’t believe it will come back.”
“You haven’t any idea whose deer it might be, have you?” asked
Dick.
“Not the least in the world, my boy. Either it got away from a
circus or a traveling show, or else it must have made its way here
from a long distance. There is no deer country around here.”
“So it’s a sort of mystery, isn’t it?” asked Teddy.
“You’re right there, my boy. It sure is a mystery.”
“Well, we’re going to solve it!” Teddy declared as he and his
chums started toward their homes.
“I wish you luck,” called Mr. Mason. “I say!” he called as he turned
back. “I just happened to think maybe that deer got loose out of a
railroad car. He might be one of a large shipment of deer from one
place to another and he got out. Ask the railroad freight or express
agent.”
“We will,” promised Joe.
58. The three boys walked slowly across the big meadow back toward
the road that led to Oakdale. They were talking of what had
happened and Joe and Dick were wondering what had become of
their planes. Dick and Teddy were also rather anxious about their
sisters.
But since Mr. Mason had laughed at the idea that the deer might
have carried the girls off on his back, the boys no longer gave it any
serious thought.
“I guess the girls just got scared at seeing the deer and ran away,”
suggested Joe.
“What about our planes?” asked Dick.
Joe didn’t answer. But there was no need. For a little later the
three boys heard their names called from beyond a fence. Lucy and
Margie bobbed into sight, each one with a plane in her hands.
“Oh, so that’s what happened?” asked Dick.
“Yes, we found your planes,” Margie said.
“And did you get chased by a deer?” asked Lucy.
“No, the deer didn’t chase us. We chased the deer,” said Teddy.
This was not strictly true, for there was a time when the deer
seemed very much to be chasing the boys. But at least the chums
had seen Mr. Mason make the deer run away.
“Whose deer is it?” asked Lucy.
“That’s what our club is going to find out,” said Teddy.
“Your club?” chorused the two girls.
“The Mystery Club,” explained Joe.
59. Then, of course, the girls had to be told more about it. They
teased to be made members but, for a time, the boys refused. Then
Joe, who had no sister and was rather neutral, said:
“Couldn’t they be sort of extra members? You know lots of clubs
have women and girls as extra members.”
“Oh, yes! Could we be that?” begged Margie.
After further discussion the boys agreed to this. The five walked
along together, out of the meadow, talking about the mystery deer
when, just as they were about to go from a lane into the main road,
a fat boy, whom none of them knew, came out on the run, very
much excited.
“Hello! Hello!” he greeted Teddy and the others. He talked very
fast, as if he were having a race with words. “Did you see him?” he
asked. “The man—the man with a rope—a long rope like a lasso? He
was running over to the woods—I thought he was a cowboy and he
asked me if I had seen him and I said who and he said a steer and I
thought he was trying to make fun of me so I said no I hadn’t and
say—Oh, gosh! Did you see him? He came this way and—oh, but
you don’t know who I am, do you? Well, I’m Charlie Nolan.
Everybody calls me Fatty Nolan and you can if you like. Oh, say,
there he is now! The man with the rope. Look! I’m going to run after
him!”
61. CHAPTER VII
MRS. TRADDLE’S GARDEN
Fatty Nolan, whose rapid-fire talk had taken Teddy and the others by
surprise, raced toward a man who was crossing one end of the
meadow into the woods. The man had a rope, as the boys and girls
could notice. But he did not appear to be a cowboy.
“I’m going to help him catch that steer!” cried Fatty.
A little later he and the man, whom Teddy and his friends did not
know, disappeared in the woods where the deer had first been seen.
“Well, what do you make of this?” asked Teddy of his chums.
“You’ve got me,” replied Dick. “Fatty Nolan? Who is he, anyhow?”
“I never saw him before,” said Joe. “He must have just come to
Oakdale.”
“He seems friendly enough,” said Lucy.
“Didn’t he talk fast!” laughed Margie. “And isn’t he fat?”
“His name sure fits him!” agreed Teddy. “But I’d like to know how
many wild animals there are running loose around here? First we see
a deer and now Fatty Nolan tells us about a steer.”
“I think it’s the same thing,” suggested Joe. “The man must have
said deer and Fatty took it to be steer.”
“Having seen the man with a lasso,” spoke Dick, “Fatty would
naturally think of a runaway steer. But I believe the man must have
62. said deer. You’re right, Joe.”
“Then he’s after the deer,” Teddy remarked. “And I guess that’s
about the end of the mystery.”
“If the man catches him,” said Joe. “He might not, you know. That
deer is a fast runner.”
“That’s right,” Teddy agreed. “Maybe he can’t catch the deer, and
our club will still have a chance to do it and solve the mystery.”
“Do you think it is much of a mystery?” asked Margie.
“You can’t tell,” said Lucy. “We didn’t think the dog was going to
be a mystery, did we, Teddy?”
“No. Nor the pony and parrot, either. But they both turned out to
be swell mysteries,” said Teddy.
“And I think the deer will,” declared Joe.
“Besides, the deer, there’s this mystery about Fatty Nolan,” said
Dick. “Who is he, anyhow?”
This small mystery was soon solved. For though Fatty and the man
with the rope did not appear again for some time, as the boys and
girls were coming from the lane into the main highway they met Mr.
Mason once more. The farmer was in a small auto and stopped to
ask if the Mystery Club wanted a ride home.
“Thanks. If you will drop us off in town, near Mrs. Traddle’s store,
we’ll be much obliged,” said Teddy.
“Why do you want to get out at Mrs. Traddle’s store?” asked Dick.
“Because I’m going to treat this club to sodas,” Teddy answered.
“We’ve had a hard day. A soda will be good for us.”
63. “Fine!” chorused his chums.
“Do you mean us, too?” asked Margie.
“Of course,” laughed Lucy’s brother.
“What club is this?” asked Mr. Mason when they were all in his car.
“Oh, the deer mystery club,” Teddy explained. “You know. The
deer that was in your meadow.”
“Oh, yes. Well, he’d better keep out of my garden! Did you see the
deer again?”
“No but we saw a man with a rope who was running after him, I
guess,” Joe said.
“Hum! Just as I thought! A stray deer got out of a railroad car,”
said the farmer. “Well, I hope they catch him.”
“Who is this new boy, Fatty Nolan?” asked Teddy.
“Nolan? A fat lad? Why, he’s the son of Samuel Nolan who is a
farmer I hired to work part of my place on shares. The Nolan family
just moved here yesterday. Came from over Portchester way. They’re
occupying that little old house where Mr. Huntley used to live. So
you’ve met the fat boy, eh?”
Teddy told of the meeting and something of the stout lad.
“Yes, he is quite a talker, I noticed that,” said Mr. Mason. “Well,
here you are at Mrs. Traddle’s.”
“Thanks for the ride,” Teddy said. “Won’t you come in and have a
soda?”
“Thanks, no. I’ve got to get along. But if you see that deer, I hope
you capture him, or help that man to do it. I don’t want a deer
64. messing up my garden and cornfields.”
The boys and girls crowded into Mrs. Traddle’s small store.
“I’m glad Mr. Mason didn’t accept my invitation,” said Teddy in a
low voice to Joe. “I only have enough money to treat this crowd. I’d
have had to charge Mr. Mason’s soda.”
“Lucky he didn’t come in,” laughed Joe.
Mrs. Traddle came bustling out from her rooms in the rear of the
store.
“Give your orders, girls and boys,” invited Teddy. “What flavors
have you got, Mrs. Traddle?”
“Oh, yes, I know you’re all neighbors,” smiled the little old lady,
her deafness causing her to mistake the words of Teddy.
“You can see the list up over the mirror,” said Lucy to her brother.
“And I think,” she went on, “it will be easier to point to the flavors of
soda we want instead of trying to tell her.”
“That’s right,” said Joe. “Then she won’t mix lemon and vanilla as
she did for me once.”
Mrs. Traddle quickly understood when the soda flavors were
pointed out by Teddy on the list as his friends named them. And
soon the five chums were sitting on stools and enjoying the drinks.
“Where have you been? To a party?” asked Mrs. Traddle when she
had rung up the sales on the cash register.
“We’ve been chasing a deer,” Teddy said.
“Oh, my goodness, a bear! I wouldn’t chase bears if I were you,”
said the old lady. “I don’t think your folks would like that. Besides,
it’s dangerous. Bear! My gracious!”
65. “Not a BEAR. A DEER,” said Teddy in a loud voice.
“Oh, a deer? That’s different. A deer is harmless, I guess, though I
never chased one.”
“This one chased us,” said Margie. “And we ran.”
“Whose deer was it?” asked Mrs. Traddle.
“It’s ours,” Teddy said.
“Oh, I didn’t know you had a deer,” Mrs. Traddle was much
surprised. “But then I suppose I’m old fashioned. Dogs and cats
were all we had for pets when I was a child.”
“It isn’t exactly our deer, but we sort of saw it and we are going to
get it and solve the mystery of it,” Teddy said. But it is doubtful if
Mrs. Traddle heard this last explanation. Some other customers
came in.
And as Teddy and his chums went out, they heard the store
keeper telling her new customers something about the deer the
Benson children had for a pet.
“No use bothering to explain,” Teddy said. “It’s too hot to have to
talk loud enough for Mrs. Traddle to hear.”
Margie and Lucy had decided to go on a little picnic next day.
Teddy asked Joe and Dick what they planned to do.
“Why not have another try for that deer?” asked Teddy as his
chums had no particular place to go.
“Sure,” agreed Joe and Dick.
“If we’re going to solve the mystery,” Teddy went on, “we might as
well start. Come over to my house right after breakfast.”
66. “We’ll do that,” Joe promised and Dick agreed, adding:
“We can have a talk with Fatty Nolan and see if he found out
anything about the man with the rope.”
“That’s a good idea,” Teddy assented.
The boys and girls soon separated to go to their several homes, all
being in the vicinity of Teddy Benson’s house.
After spending an hour or two that evening making some repairs
to his toy plane, Teddy went to bed. He thought with pleasure of
what might happen next day, when he and his chums would start on
the trail of the mysterious deer.
Once during the night Teddy was awakened by hearing a noise at
the back door. He sat up in bed, thinking for a moment it might be
the deer, coming to knock as, once, a mysterious pony rang the door
bell. But then Teddy heard a clatter of milk bottles and knew what
had caused the noise.
Teddy was at breakfast next morning when he saw Mrs. Traddle
coming around the side of the house. She saw Mr. Benson, who was
cutting the grass before he went to the office.
“Good morning, Mrs. Traddle!” greeted Teddy’s father. “What
brings you out so early?”
“It’s your children’s pet deer!” said Mrs. Traddle in a loud voice.
“A pet deer!” exclaimed Mr. Benson. “My children have no pet
deer. There must be some mistake.”
“No. Excuse me, but there is no mistake,” said Mrs. Traddle. “They
told me about their pet deer yesterday. Last night the deer got in my
garden and ate it all up. I’ll have to be paid damages, Mr. Benson.
You should see the ruin that deer made in my garden!”
68. CHAPTER VIII
THE LASSO MAN
Teddy’s father was puzzled. He leaned on the handle of the lawn
mower. He looked at Mrs. Traddle. Then he looked toward the house
where Teddy and Lucy were at breakfast.
“I am very sorry, Mrs. Traddle,” began Mr. Benson. But the old lady
store keeper, who had, seemingly, been hearing quite well a moment
before, suddenly became deaf.
“I didn’t come to borrow anything,” she said rather crossly. “Not
even your lawn mower.”
“I didn’t say you had come to borrow anything,” went on Mr.
Benson. “I said I was sorry about your garden. I am sure it wasn’t
any deer of Teddy’s that got into your garden.”
“No, I didn’t say the deer came there steady,” said Mrs. Traddle,
mixing Teddy’s name up in that way. “But the deer came last night
and he ate up most of my garden. It was a big loss. Somebody has
to pay for it.”
“I’ll see about it,” said Mr. Benson, pushing the lawn mower to one
side. He walked toward the house, followed by Mrs. Traddle.
“Teddy!” called his father. “Come out here, please.”
Teddy was already on his way to the side porch. Lucy followed
him, whispering:
“Oh, what do you suppose is going to happen?”
69. Both children had heard the last of Mrs. Traddle’s remarks as they
crossed the porch.
“I don’t know,” Teddy answered. “Anyhow Mrs. Traddle can’t
blame us for what a stray, mysterious deer did to her garden.”
“Teddy,” began Mr. Benson as he saw his son. “What is this about
your deer getting into the garden of Mrs. Traddle?”
“It isn’t our deer at all,” Teddy explained.
“Is there a deer?” his father wanted to know.
“Oh, yes!” exclaimed Lucy. “I saw it. I was chased by it and so
was Margie, yesterday.”
“This is the first I have heard of any deer,” said Mr. Benson.
“Where is it, Teddy?”
“That’s what we don’t know. But we are going to find out. It is a
mystery deer,” Teddy answered.
Mr. Benson smiled at this. He had often heard his children speak
of “mysterious” animals. But sometimes the animals were just that.
“The reason we didn’t tell you about the deer last night,” went on
Teddy, “is that you and mother were over to the church supper, and
it was so late when you got home I forgot it.”
“So did I,” added Lucy.
“Well, tell me about it now,” suggested Mr. Benson.
He was told the story of the deer—as much as Teddy and Lucy
knew—and Teddy explained that he and his chums were going to try
to get on the trail of the mysterious animal that day.
“First we have to find Fatty Nolan,” said Teddy.
70. “Is that the deer’s name?” asked Mr. Benson.
“No. It’s the name of a new fat boy,” Teddy went on, laughing.
“His father works part of Mr. Mason’s farm. Fatty saw a man with a
lasso running across the fields. After the deer, maybe. We’re going to
see if he caught the deer.”
“Well, if he has,” said Mr. Benson, “you might tell the owner of the
deer that Mrs. Traddle wants damages for her garden. All her corn
and beans are gone.”
“No, no!” hastily exclaimed Mrs. Traddle. “I didn’t say the deer
sang a song. He just trampled and ate my garden. I didn’t even see
the deer. He came during the night.”
“Well, it wasn’t our deer,” Teddy stated, taking pains to speak in a
loud voice so Mrs. Traddle could understand.
“But in my store I’m sure you said it was your deer,” insisted the
confused old lady.
“Well,” explained Teddy, “I meant we sort of called it our deer. We
sort of feel we have to solve the mystery about it.”
“Oh, well, then I guess I can’t blame you,” said Mrs. Traddle. “I’m
sorry I made any trouble,” she went on. “But my poor garden is
ruined.”
“If we find the man who owns the deer we’ll make him pay for the
damage,” promised Teddy.
“Thanks,” murmured Mrs. Traddle as she turned and went back to
her store.
Teddy and Lucy started toward the house to finish their
breakfasts. Mr. Benson returned to cutting the grass, saying:
71. “So you have a new mystery, have you?”
“Maybe it will be a mystery and maybe it won’t,” admitted Teddy.
“I’m going over to see Fatty Nolan as soon as the fellows come.”
A little later, when Dick and Joe arrived at Teddy’s house, they
were told of what had happened to Mrs. Traddle’s garden.
“Let’s go have a look,” suggested Dick.
“What for?” Teddy wanted to know. “The deer isn’t there now.”
“No. But maybe he left a trail,” said Joe. “If we’re going to find this
animal we’ve got to follow his trail. Come on.”
Mrs. Traddle’s garden was at the rear and to one side of her house
and store. The boys found several men of Oakdale looking at the
ruin caused by the deer.
“Looks like a herd of elephants was in there,” commented Sam
Kean, the grocer.
“Guess that deer spoiled more than he ate,” said Luke Lanter, the
butcher. “Looks like he lay down and rolled in the corn.”
“Maybe he was sort of celebrating,” said Mr. Kean. “He probably
never had such a free feast before.”
When most of the curious ones had departed, Teddy and his
chums asked permission of Mrs. Traddle to look in the garden.
“Look as much as you like,” she said with a sniff. “There isn’t much
left to see. Dear me.”
“We want to see if he left a trail,” explained Teddy.
“Left a tail? Land sakes, why would a deer want to go and leave
his tail behind?” asked the old lady.
72. “I mean any marks so we could go after him and find him,” Teddy
explained.
“Oh, I understand. Like the Indians I used to hear my grandfather
tell about. Well, look if you like. All you’ll see are a lot of paw marks.
Or maybe I should say hoof marks, bein’ as how it’s a deer,” said
Mrs. Traddle.
The boys did find plenty of hoof marks but they were so jumbled
up, it was impossible to determine which way the deer had come
into the garden or gone out.
“I know what we ought to do,” said Joe.
“What?” asked Teddy.
“Find that man with the lasso. If he wasn’t the owner of the deer
he must have been after it. And maybe he would know how to trail
it. Let’s go find him.”
“Where’ll we look?” asked Dick.
“Start with Fatty Nolan,” suggested Teddy.
It did not take them long to reach the small farm house where the
fat boy lived. Fatty, who had just driven the cows to pasture after
they had been milked, hurried toward the three boys.
“Hello!” he called with a good-natured grin. “Did you find that deer
yet? I guess you didn’t. I didn’t either. I guess deers are hard to
catch. I never chased one, but maybe that man with the lasso got
him. Did you see him—whose deer was it—come on in, will you? I
can go with you if you like and help look for the deer. He was a big
one, wasn’t he?”
Fatty Nolan had to stop and take a breath after all this talk. He
had a habit of running his words and sentences together in his
73. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com