Professional Documents
Culture Documents
Love being
connected,
all over again
http://create.msdn.com
brought to you by...
#127
Get More Refcardz! Visit refcardz.com
CONTENTS INCLUDE:
n
Platform & Tools
Developing a Silverlight Application for
Windows Phone 7
n
Silverlight Project Creation ®
n
Application Navigation
n
Data Handling
n
Platform Integration
n
Design Considerations and more... By Colin Melia
• Windows® Vista® (x86 and x64) with Service Pack 2–all editions except
PLATFORM & TOOLS Starter Edition
• Windows® 7 (x86 and x64)–all editions except Starter Edition
Windows® Phone 7 is a new platform bringing together Be sure to check out the release notes for full requirements.
developers from the .NET, Silverlight, and XNA eco-systems. http://go.microsoft.com/fwlink/?LinkID=190374
This document combines reference information and tips for Before installing the RTW version of the tools, be sure to
developing and publishing a Silverlight application for the Hot uninstall any pre-release version of the toolset in one step
platform using Visual Studio. Tip by uninstalling the item named, “Microsoft Windows Phone
Developer Tools...” under Control Panel.
Hardware Specification
All initially launched Windows Phone 7 devices come with:
Silverlight Application Platform
the same operating system; the same minimum set of built-
The Windows Phone 7 platform can run applications based on
in applications and platform capabilities; and the ability to
Silverlight and XNA.
run Silverlight and XNA applications. Additionally, all devices
come with the following hardware capabilities: Silverlight is often the preferred choice for applications built
• 480x800 display with controls and events, similar to WinForms or WebForms.
• DirectX 9 hardware acceleration XNA is typically used for higher performance UI hardware
• Capacitive 4-point multi-touch rendering in 2D and 3D.
• Back, Start & Search hardware buttons (as well as a power, camera
and volume button) Silverlight applications can use non-rendering classes
• A-GPS, accelerometer, compass*, light*, proximity* provided by the XNA framework (e.g. for playing
• 5 MP+ digital camera with flash
• 256MB+ RAM
Hot overlapping sounds or accessing microphone audio) and
• 8GB+ flash storage Tip vice-versa. For choosing a development stack and calling
* not accesible from .NET API in initial release
across frameworks, see http://msdn.microsoft.com/en-
us/library/ff402528(v=VS.92).aspx.
Hardware manufacturers may differentiate their devices
by items such as: having higher RAM, flash storage or Silverlight applications run directly on the Windows Phone
camera mega-pixels; having different screen sizes (but platform in a mode similar to the out-of-browser capability of
same resolution); adding a slide-out keyboard (horizontal Silverlight 3+ on the desktop. They do not run in a browser. In
or vertical); adding a single additional theme accent color; fact, Silverlight content on Web pages will not appear in the
bundling additional built-in applications—but not removing/ phone’s Web browser, but there is a WebBrowser control to host
replacing built-in applications/UI. HTML content (from the Web, injected, or from local storage)
inside a Silverlight application.
Flash storage space should be considered as opaque file
system storage; it is not removable portable storage for The RTW Silverlight platform is based largely on Silverlight 3.
Hot transferring files. It can be extended in some devices with
Tip an additional card, but that requires a ‘factory reset’ of the
device to wipie existing data.
Developer Tools
The developer tools for Windows Phone 7 are available for free.
Go to http://go.microsoft.com/fwlink/?LinkID=189554 for the
RTW (‘Released to the Web’) tools or go to
Windodws Phone 7
Project Templates
Start building a Silverlight application for Windows Phone by
using the File -> New Project feature in Visual Studio. The RTW
tools include support for projects based on the C# language.
Support for VB.NET will be officially introduced later on.
Windows Phone Pivot Building an application that is based on an MVM design and lement: using an XML element means an object with a type named
2. E
Application* that starts with a screen showing set of views (or pivots) over the same as the element will be created at runtime.
data like the Calendar & email application on the phone.
3. A
ttribute: at runtime, the value of an attribute will be set as the value
*T
hese project templates use the Panaroma and Pivot controls on a single page and are often used to
create ‘Hub’ applications; these controls can also be added to any page in an application. of a property on the object created for the corresponding element. The
XAML parser is also able to convert text to non-text types including a
A ‘Hub’ is an application that typically starts with a numerical type, an enumerated type, multiple initial values on a type
(e.g. the different sides of a Margin), or a whole object initialized by the
Hot Panorama or Pivot control and that generally brings
attribute values (e.g. a SolidColorBrush with a specific color).
Tip together content and data under a single area of concern
esting: putting one element inside another means the created objects
4. N
(e.g., People).
form a tree whereby the nested object is assigned to a default property
(e.g., a single Child or Content property of the containing object), or it
Design Surface + XAML becomes one of several objects added to a default collection property
After choosing to create a new project based on the Windows (e.g., a Children collection property).
Phone Application template, an interface is shown that includes roperty Element: when a property of an object is too complex to
5. P
windows for the Toolbox, Solution Explorer, and Properties, declare or parse from an XML text attribute, the Property Element
along with the editor window for the initial (and perhaps only) syntax is used to declare the object fully.
However, XAML provides a more efficient way to declare visual The emulator starts automatically when a debug session is started
interfaces rather than writing procedural code that can be in Visual Studio (if the Windows Phone 7 Emulator is selected).
substantially longer. Procedural code is still used for data models
The emulator can take advantage of hardware
and accessing data. XAML is also compatible with the Expression
Blend designer tool allowing for projects to be edited in both
Hot virtualization if turned on in the PC BIOS as well as the
tools with tool UI appropriate to each user.
Tip PC’s GPU - http://msdn.microsoft.com/en-us/library/
ff402567(v=VS.92).aspx.
Adhering to the MVVM design pattern can maximize XAML
The emulator does not emulate A-GPS, light, proximity, and
Hot and minimize UI code, increasing designer-developer
accelerometer sensors. It also does not include all user
Tip workflow productivity and creating more maintainable
Settings pages.
code layers (from separation of concerns).
Use mock classes or the Reactive extensions for
Controls Hot .NET (http://msdn.microsoft.com/en-us/library/
The following controls are provided on the phone: Tip ff431792(v=VS.92).aspx) to simulate streams of data from
Category Control Class hardware that is not emulated.
Do Action Button, HyperlinkButton
To take 480x800 snapshots of the emulator for use in
Data Display Map, ProgressBar, TextBlock, WebBrowser Hot marketplace application submissions, on Windows 7, use
Data Input CheckBox, PasswordBox, RadioButton, Slider, TextBox Tip the Snipping Tool, select New -> Windows Snip and click on
Media MediaElement the emulator screen.
Drawing Ellipse, Rectangle
Debugging
Layout Border, Canvas, Grid, ListBox, ScrollViewer, StackPanel, Panorama, Pivot
Visual Studio allows debugging targeting to the Emulator or a
Many controls have a property named Content. Such controls connected device for debugging.
(e.g., Border or even Button) act as visual/object container for Regular debugging activities are available including using
rendering a single item of content which can be either: breakpoints, variable inspection, variable watch, call stack, and
• visual (derived from UIElement), e.g., another Control output window.
• an object containing data (in which case the data is visually represented
as text by calling ToString() or with other visual elements declared in a Launching a debug instance (e.g., by pressing F5) builds the
DataTemplate) project (as necessary), deploys the application to the target
device (removing any previous version,) and then launches the
Microsoft is also releasing other controls out-of-band from application.
Hot (and likely more frequently than) developer tools updates,
Tip in the Silverlight for Windows Phone Toolkit on Codeplex: To debug with a real device, all of these points must be met:
http://silverlight.codeplex.com/ 1. The
Zune (4.7+) software (free to download from http://zune.net) must
be running on the development PC.
Layout 2. The device must be connected to the PC using the provided USB cable.
The desired UI layout is achieved by setting Margin and Padding 3. T
he device must be ‘development unlocked’ (not the same as ‘network
on controls, setting their alignment in the space provided to unlocked’); this is achieved by using the Windows Phone Developer
them, and placing them in other controls (e.g., Grid, Canvas, or Registration Tool (included with the tools) and having a developer
StackPanel) that arrange one or more controls. account at http://create.msdn.com with a spare slot (out of 3 total for
paying accounts; 1 for student accounts).
Try customizing controls by providing XAML for ‘Template’ 4. The device must be on and not on the lock screen.
Hot properties. For custom child layout, derive a class from
When using the emulator, leave it running between debug
Tip the Panel class and override the MeasureOverride() and
sessions to avoid the start-up time and to keep the storage
ArrangeOverride() methods.
emulation intact and be able to launch applications
deployed/debugged since it was started.
Layout of controls on the design surface is not limited to the
physical dimensions of the device. A control can extend passed The Zune software locks the media library on the phone.
the dimensions of the design surface if the user is able to reach Hot To debug an application that accesses the media library
that UI through some means of interaction. The Panorama and Tip instead, use WPConnect.exe in the Windows Phone
Pivot controls are ‘über-layout’ controls that do exactly this. Developer Tools 2010 Update.
Emulator
The toolset includes a powerful emulator running the Windows APPLICATION NAVIGATION
Phone OS 7.0 compiled for Intel processors. It emulates a
device’s processor, RAM, display, GPU, networking, media, Frame & Page
keyboard, orientation changes, as well as application deployment Silverlight applications on the phone operate within a logicial
and debugging. The PC mouse pointer is used to emulate a ‘last-on-first-off’ (LIFO) stack of running applications. Within an
single screen touch. If the PC supports multi-touch, then this is application, there is a logical LIFO stack of pages.
passed through to the emulator.
Other pages within an application (added with the ‘Add New
Press the Pause key on the PC keyboard to toggle Item’ menu item in Visual Studio) are launched by developed
Hot keyboard input between the onscreen keyboard and code, usually in response to user actions such as clicking a
Tip the PC’s keyboard (emulating a physical keyboard button.
on a device).
private void button1_Click(object sender, RoutedEventArgs e) LINQ to XML (by adding the System.Xml.Linq reference) allows
{
NavigationService.Navigate(new Uri(“/page2.xaml?param=” + value,
parsing and transforming of XML data.
UriKind.Relative));
} public class MyPerson
{
public String Name { get; set; }
This example shows passing a parameter to the next page. public int Age { get; set; }
During page navigation, the current page’s OnNavigatedFrom() }
override is called and the destination page’s OnNavigatedTo() Code to parse XML downloaded using WebClient, into the class.
override is called.
// Do something with e.Result string
protected override void OnNavigatedTo(System.Windows.Navigation. XDocument doc = XDocument.Load(new StringReader(e.Result));
NavigationEventArgs e)
{ var results = from p in doc.Element(“People”)
var value = NavigationContext.QueryString[“param”]; .Elements(“Person”)
} select new MyPerson()
{
Name = p.Element(“Name”).Value,
In this case, the query string passed earlier is being extracted. Age = int.Parse(p.Attribute(“Age”).Value)
The user launches instances of an application using the Search or };
Start screen ‘on top’, which sit logically higher on the sack. Data Binding
If the user launches another instance of the same Data can be set on UI controls using procedural code, but this
Hot application, any previously launched instance (and any can get quite complex and is not designer-tool friendly. Setting
Tip tombstone information – see later) is effectively removed (in code or XAML) the DataContext of any UI object (inherited
from the stack. from FrameworkElement) to a ‘data’ object (e.g., of type
MyPerson) ‘binds’ that data object to the UI object and allows
Back Button
the UI object (or descendants) to display properties of the data
The phone’s Back button removes the current page and navigates
object using a simple XAML syntax.
to the previous one on the stack, calling its OnNavigatedTo()
override. It is possible to cancel this default behavior. In the public MainPage()
{
example, the modal dialog box is cancelled and prompts the user InitializeComponent();
to save unsaved data.
ContentPanel.DataContext = new MyPerson();
Check marketplace submission requirements before }
collections, pass an index parameter. Setting the DataContext of descendant UI objects to any object
properties of the data object allows a hierarchy of binding.
protected override void OnBackKeyPress(System.ComponentModel.
CancelEventArgs e)
{
Use binding converters (classes based on IValueConverter)
if (someallowedcondition) along with a resource declaration to provide for bindings
e.Cancel = true;
base.OnBackKeyPress(e); Hot between data object properties and UI object properties
}
Tip of different types or values (e.g., set a color based on a
value). Use d:DataContext in XAML to set up design-time
DATA HANDLING data in Visual Studio to preview sample data in the UI.
HttpWebRequest & Use for fine-grained control of sending an HTTP request and receiving // Store
IsolatedStorageSettings.ApplicationSettings[“mysetting”] = person;
HttpWebResponse the response.
// Retrieve - Use Try/Catch or check first with ApplicationSettings.
The typical pattern involves reacting to a user event (or timed Contains()
MyPerson person = (MyPerson)IsolatedStorageSettings.ApplicationSettings[“m
event from System.Windows.Threading.DispatcherTimer) ysetting”];
and setting up the data request by creating a class instance,
Alternatively, get a store object that allows file and directory
setting up an event handler (or delegate), and initiating the
operations. The CreateFile() and OpenFile() methods return back
asynchronous activity.
objects inherited from System.IO for use with Text, Binary, and
Some asynchronous activities provide results on a XML Writers/Readers.
Hot different thread. If the application needs to directly modify
Tip the UI on receipt of data, use Dispatcher.BeginInvoke() to IsolatedStorageFile store = IsolatedStorageFile.
GetUserStoreForApplication();
do it on the UI thread.
Isolated storage is best used for local settings, caching
LINQ to XML Hot data, offline sync queues and data entry/activity in
On the phone, LINQ allows set-based queries on in-memory Tip progress in some cases.
objects and data transformation. This can include parsing text
downloaded with WebClient and transforming it to objects.
Application Bar
PLATFORM INTEGRATION
Each page can have an Application bar with up to four icon menu
items and optionally additional pull-up text menu items (accessed
Application Lifecycle by clicking ‘…’). See the sample code at the bottom of MainPage.
While the OS maintains a history of navigation between xaml in a new project. Add a Click attribute to add a handler.
applications and pages, applications (as a rule) terminate when
the application goes into the background. Some examples of
this are when the user launches other applications including the
Start screen, a launcher/choose task is launched (see “Launchers
& Choosers”, or the screen locks. This provides the best user With Opacity of 1 the page size is reduced by the size of the bar.
experience. Applications restart them at the last shown page Opacity < 1 shows the bar over the page contents.
when the user returns to the application using the Back button.
The application developer must do the work to retain any UI or Hot Expression Blend makes it easy to add icons to App Bar
in-memory state by storing it either in isolated storage or with the Tip Buttons from the built-in resources.
‘bag’ of data that the OS provides and retains in the stack history,
known as the ‘tombstone’. App.xaml.cs includes the stub for four
application lifecycle events. Accelerometer
Add a reference to Microsoft.Devices.Sensors and access
• The Launching event fires every time the application launches. Initiate
loading any settings or cached data from Isolated Storage (and check the information from an Accelerometer object.
Internet for any new data if appropriate).
private void StartAccelerometer()
• The Deactivated event fires when the application is ‘tombstoned’, with {
~10 seconds to save data into the tombstone or Isolated Storage before accel = new Accelerometer();
the application terminates. accel.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>
(accel_ReadingChanged);
• The Activated event fires when the application is resumed via the Back accel.Start();
button. Load back data from the tombstone or Isolated Storage (and }
void accel_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
check the Internet for any new data if appropriate). {
• The Closing event fires when the application exits from the initial back via // Access e.X, e.Y, e.Z & e.Timetamp
the Back button. }
Tombstone data can be stored under the global The values of X (right), Y (top), Z (face), range from 1 when the
PhoneApplicationService.Current.State dictionary (during stated side points to the ground to -1 for the opposite side.
Deactivate/Activates events) or in the current page’s State
dictionary (during OnNavigatedFrom()/OnNavigatedTo()). Location Services
The location system talks to the Microsoft location services to
Note that the tombstone will be removed if the same application help establish a location. Usage is similar to the accelerometer
is launched again ‘on top’—the user is abandoning any ‘session’ using an add reference to Microsoft.Devices and the
data stored in the tombstone—or if the OS needs to free up Microsoft.Devices.Sensors.GeoCoordinateWatcher class,
resources. In either case, the last two events will never be called which has a StatusChanged event and PositionChanged event
on the previously running instance. (returning GPS data).
To prevent the lock screen from engaging due to Use the optional constructor parameter to request high-accuracy
user inactivity, set PhoneApplicationService.Current. data using the GPS receiver (taking longer to get a position and
UserIdleDetectionMode = IdleDetectionMode.Disabled. using more battery power). Otherwise, just available Mobile
Hot To allow an application to run under the lock phone tower and Wi-Fi information is used.
Tip screen set PhoneApplicationService.Current.
Touch
ApplicationIdleDetectionMode = IdleDetectionMode.
Disabled (which has an associated marketplace submission Use the GestureListener in the Silverlight for Windows
requirement). Be careful not to drain the battery. Hot Phone toolkit to easily add a handler for Tap, Double Tap,
Tip Drag, Flick, Hold, and Pinch/Zoom gestures on part of the UI.
Launchers & Choosers
The Microsoft.Phone.Tasks namespace includes classes used to <Grid x:Name=”LayoutRoot” Background=”#00FFFFFF”>
<tk:GestureService.GestureListener>
configure and prompt the user to perform tasks either with no <tk:GestureListener Hold=”GestureListener_Hold”
DoubleTap=”GestureListener_DoubleTap” Flick=”GestureListener_Flick”/>
resulting data returned (a Launcher) or with returned data </tk:GestureService.GestureListener>
(a Chooser), e.g. </Grid>
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
on:
dz. com
grati s
also minimizes the need to make design changes to support
CON
ABOUT CLOUD COMPUTING one time events. TEN TS
INC
s Inte -Patternvall
■
HTML LUD E:
Basics
Automated growthHTM
ref car
Microsoft Azure
Usef
ContiPatterns an
■
However, the demands and technology used on such servers faced by web applications.Structure Tools
Core
Key ■
Structur Elem
E: has changed substantially in recent years, especially with al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
CSS3
■
n
Re fca
e Work
Build
riptio
and Ant These companies Desc have a Privat
are in long deployed trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
ION d units etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
EGRAT e ine loping task-o it and Java s written in hical on of
all attribute
softwar emphasis onDeve es by
Mainl
INT these ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
OUS
Richfaces 4.0
codel chang desc
ding e code Task Level as the
www.dzone.com
REST
reposit -patter particu s cies Pay only what you consume
tagge or Amazon’s cloud
the curr you cho platform
computing becisome
heavily based moron very little fine. b></ ed insid
lained ) and anti x” the are solution duce
nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
b> is
be exp text to “fi
al Depeapplication deployment
Web ge until
nden a few years
t librari agonmen
t enviro was similar that will software
industry standard and virtualization apparen ortant, the
e HTM technology.
tterns to pro Minim packa
dard
Mo re
CI can ticular con used can rity all depe that all
targe
simp s will L t. HTM l, but r. Tags
es i-pa tend but to most phone services:
y Integ alize plans with late alloted resources,
file
ts with an and XHT lify all help or XHTML, Reg ardless L VS XH <a><
in a par hes som
etim s. Ant , they ctices,
Binar Centr temp your you prov TML b></
proces in the end bad pra enting
nt nmen
incurred cost
geme whether e a single based on
Creatsuchareresources were consumed
t enviro orthenot. Virtualization
muchallows MLaare physical othe
piece ofr hardware to be understand of HTML
approac ed with the cial, but, rily implem nden
cy Mana rties nt targe es to of the actually web cod ide a solid ing has
essa d to Depe prope into differe chang
utilized by multiple operating
function systems.simplerThis allows ing.resourcesfoundati job adm been arou
efi nec itting
associat to be ben
er
pare
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
ality be allocated nd for
n com Cloud computing asRun it’sremo
known etoday has changed this. expecte irably, that
befor
They they
etc.
(e.g. bandwidth, elem CPU) tohas
nmemory, exclusively totely
Temp
job has some time
Build
lts whe
ually,
appear effects. rm a
Privat y, contin nt team Every mov
entsinstances. ed to CSS
used
to be, HTML d. Earl
ed resu gration
The various resourcesPerfo consumed by webperio applications
dicall (e.g.
opme page system
individual operating bec Brow y exp . Whi
adverse unintend d Builds sitory Build r to devel common (HTM . ause ser HTM anded le it
ous Inte web dev manufacture L had very far mor has done
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis L or XHT
produc Continu Refcard
e Build rm an ack from extensio .) All are
e.com
the not
DZone, Inc.
s on
expand
ISBN-13: 978-1-936502-03-5
140 Preston Executive Dr. ISBN-10: 1-936502-03-8
Suite 100 50795
Cary, NC 27513
DZone communities deliver over 6 million pages each month to 888.678.0399
more than 3.3 million software developers, architects and decision 919.678.0300
makers. DZone offers something for everyone, including news,
Refcardz Feedback Welcome
$7.95
tutorials, cheat sheets, blogs, feature articles, source code and more.
refcardz@dzone.com 9 781936 502035
“DZone is a developer’s dream,” says PC Magazine.
Sponsorship Opportunities
Copyright © 2010 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a re-
trieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without sales@dzone.com Version 1.0
prior written permission of the publisher.