ITS
Getting Started with Windows Phone 7
This chapter covers the basics of developing for Windows Phone 7 — how to acquire the tooling and basic design patterns, and preparing to distribute your application to the marketplace. During this chapter you are expected to confi gure your development machine to run Windows, install Visual Studio and the Windows Phone 7 SDK, and go over the examples from the Derby App. This chapter also covers the specifi c situations in which Windows Phone 7 breaks away from other smartphone platforms.
NEW KID ON THE BLOCK Although the Windows Mobile 6.5 design was signifi cantly different from the last major version (6.1), it had been lambasted by critics as change for change’s sake. It used design elements from the Zune UI at that time. It was never part of Microsoft’s mobile platform blueprints, and was released as a stopgap until the release of Windows Phone 7. It has now been superseded by Windows Embedded Handheld 6.5 for Enterprise Handheld Devices.
Windows Phone 7 is not the next iteration of the Windows Mobile platform, but is its successor. It has been built specifi cally for the Qualcomm Snapdragon processor family. Since being launched in November 2010 it has had two major revisions. The fi rst, NoDo, primarily added copy-and-paste functionality. The second, Mango, added an update to the included mobile browser and multitasking for third-party developed apps. Whereas iOS and Android have a passive or reactive dashboard for their applications, Windows Phone 7 embraces a proactive approach with constantly updating tiles for application- and context-specifi c information.
Because Windows Phone 7 was launched three and a half years after the iPhone, it has benefi tted from the lessons learned by older revisions of iOS. Windows Phone 7 is still a young platform but it is opening a new channel for .NET developers to provide applications, and its success or failure is a long way off.
8
c08.indd 229c08.indd 229 28/07/12 6:04 PM28/07/12 6:04 PM
230 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
Metro Metro is a design language that Microsoft developed around the Segoe font family to be applied to its entire software stack.
It is patterned on International Typographic Style, with content organized into logical groups. Menus are replaced with panes of content, which are grouped into hubs.
The current versions of the Xbox 360 Dashboard Interface and website, the next version of the Windows operating system, and the next version of Visual Studio all implement the Metro style.
With Metro, Microsoft took a drastically different approach to mobile interfaces than it had done in the past. It is obvious Microsoft took an approach to be innovative, by not following in the UI footsteps that Apple and Android had recently set. The interface puts a strong emphasis on typography, something that had not stood out in past Microsoft software, and it uses its signature Metro font for much of the interface and navigational elements. It uses more text and images for navigating the interface, as opposed to iconography. It uses a freer-fl owing, horizontal scrolling layout for most of its apps, as opposed to set screens where you navigate from one to another.
The strong design and interface standpoint that Microsoft took is commendable, and attention to typography in particular is much appreciated by designers. But judging from its market share, the risk has not paid off — at least not yet. The drastically different interface of Metro can be a deterrent when looking to transfer an existing iPhone or Android app to Windows Phone 7.
Though themes and accent color customizations are not specifi c to Metro, I think now is the time to discuss it. Users can choose either a light or dark theme for their device, and can choose from 10 different accent colors. When editing UI elements and setting their default colors, note that in certain circumstances text may be diffi cult to read or effectively invisible. When using the Light theme, text defaults to a dark color, and when using the Dark theme, text defaults to a light color. You also can leverage built-in system resources to bind specifi c accents and default color values to your UI elements.
The benefi t of this is shown in Figure 8-1. By using a default style in the Derby App (shown later), when you update the theme on your device, the application automatically updates the styles respective to that theme. The left half of the image is from running the application with the Dark theme, and the right is running the application with the Light theme. I did not have to change a line of code. You can fi nd more information on working with these resources on the MSDN library at http://msdn .microsoft.com/en-us/library/ff769552(v=vs.92).aspx.
Application Bar The Application Bar is Windows Phone 7’s answer to iOS’s UITabBar and Android’s TabHost. It can contain icon items (maximum four) and/or menu items.
FIGURE 8!1: Two themes with no extra code
c08.indd 230c08.indd 230 28/07/12 6:04 PM28/07/12 6:04 PM
New Kid on the Block ! 231
Some common uses for items in the Application Bar are to pin the current view to the main tile bar (loads your app in a preset state), or to add functionality to the application that cannot be handled with the standard set of touch events.
You can create a global App Bar in XAML (stored in your application’s App.xaml fi le), or in code in your application page, which will show on all pages. Figure 8-2 shows the default view of an Application Bar.
In the XAML for any page you want the global created bar you must add a reference to it as a resource in the PhoneApplicationPage element.
MAINAPP.XAML PAGE ELEMENT
<phone:PhoneApplicationPage x:Class=”GravityWorks.DerbyApp.WP7.MainPage” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:phone=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone” xmlns:shell=”clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone” xmlns:controls=”clr-namespace:Microsoft.Phone.Controls; assembly=Microsoft.Phone.Controls” xmlns:d=”http://schemas.microsoft.com/expression/blend/2008” xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable=”d” d:DesignWidth=”480” d:DesignHeight=”800” FontFamily=”{StaticResource PhoneFontFamilyNormal}” FontSize=”{StaticResource PhoneFontSizeNormal}” Foreground=”{StaticResource PhoneForegroundBrush}” SupportedOrientations=”Portrait” Orientation=”Portrait” shell:SystemTray.IsVisible=”False” ApplicationBar=”{StaticResource MyGlobalAppBar}”>
APP.XAML RESOURCES
<!--Application Resources--> <Application.Resources> <shell:ApplicationBar x:Key=”MyGlobalAppBar” IsVisible=”True” IsMenuEnabled=”True”> <shell:ApplicationBarIconButton IconUri=”/appbar.map.direction.rest.png” Text=”Vixens” Click=”ApplicationBarIconButton_Click” /> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text=”Menu Item” /> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </Application.Resources>
If you want to have a page-specifi c Application Bar you can create one in your page’s constructor. Figure 8-3 shows the icon and menu item. The Application Bar starts minimized and expands when you click the ellipsis. The click event for both items in the fi gure pop up a message box with the text “Alert.” Page- specifi c Application Bars are good for context-sensitive functions such as non- discoverable UI functions (double-click events) or events that have no direct touch event associated with them. The following code shows how to render the Application Bar shown in Figure 8-3.
FIGURE 8!2: Global Appli cation Bar
FIGURE 8!3: Page- specifi c Application Bar
c08.indd 231c08.indd 231 28/07/12 6:04 PM28/07/12 6:04 PM
232 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
public MainPage() { InitializeComponent(); LoadApplicationBar(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); }
private void LoadApplicationBar() { ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Minimized; ApplicationBar.Opacity = 1.0; ApplicationBar.IsVisible = true; ApplicationBar.IsMenuEnabled = true;
ApplicationBarIconButton button1 = new ApplicationBarIconButton(); button1.IconUri = new Uri(“/images/blankicon.png”, UriKind.Relative); button1.Text = “button 1”; ApplicationBar.Buttons.Add(button1); button1.Click += event_Click;
ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem(); menuItem1.Text = “menu item 1”; ApplicationBar.MenuItems.Add(menuItem1); menuItem1.Click += event_Click; }
private void event_Click(object sender, EventArgs e) { MessageBox.Show(“Alert”); }
Tiles Tiles are the UI elements in Windows Phone 7 that render in the main menu when pinned. Think of pinning as adding a shortcut to your phone’s menu to an application. If you don’t confi gure any secondary app tiles programmatically, when the application is pinned it will show the App Icon and the Tile Title from the Project Properties as shown in Figure 8-4. This is known as the Application Tile.
private static void LoadTileInfo() { StandardTileData data = new StandardTileData { Title = “Derby Names Tile”, Count = 42,
BackTitle = “Gravity Works”, BackContent = “Derby Names App” }; ShellTile.ActiveTiles.First().Update(data); } FIGURE 8!4: Default tile
c08.indd 232c08.indd 232 28/07/12 6:04 PM28/07/12 6:04 PM
New Kid on the Block ! 233
When you create a tile for your application you can update it programmatically. These Active Tiles add additional interactivity to your app while it is tombstoned, or between application loads (tombstoning is explained in more detail in the next section). You can confi gure the title for the front and back sides (as of Windows Phone 7.1; before that it was only one-sided), a badge count on the front (Figure 8-5), and text content on the back (Figure 8-6). You can also confi gure backgrounds for both faces. Resolution of these tiles is 173 ! 173 pixels and images will be stretched to that size. You can use .png or .jpg, but only .png will allow transparency.
You can use the ShellTile APIs (http://msdn.microsoft .com/en-us/library/hh202948(v=vs.92).aspx) to update the application tile, or create, update, or delete active tiles from user interaction. Push Notifi cations with the correct XML format will update the tile. You can also schedule a set of updates to your tiles using ShellTileSchedule APIs. Inside your schedule you can set interval, links to remote content for your update, start time, and recurrence limits.
Your application can also have secondary tiles. These tiles link to specifi c functionality or views in your app. They are added using the same APIs, but are created as the result of user interaction versus the application tile that will always be there when the app is pinned.
Tombstoning Tombstoning is Windows Phone 7’s answer to multitasking. iOS (as of version 4.x) and Android handle multitasking by putting applications in the background but not freeing up the memory used by the application. When events fi re that would put the app in the background (in a multitasking OS), Windows Phone 7 dumps the application out of memory, and the developer can catch the event and save the state of the application. Then when an event is fi red to bring the application into the foreground it effectively relaunches the app, this time fi ring an activated event instead of a launched event. This enables the developer to pass back in the state and get the user right back to where he was. This allows the application to be “multitasked” without persisting the application in memory.
What does this mean for you as a developer?
To save your application and last running page’s state dictionary when being tombstoned, all data in these dictionaries must be serializable.
You have two primary ways of storing this data on the device:
" The System.IO.IsolatedStorage namespace contains the IsolatedStorageSettings class, which contains an ApplicationSettings dictionary of key-value pairs. This can persist whether the app was tombstoned or closed.
" The Microsoft.Phone.Shell namespace contains the PhoneApplicationService.State dictionary. It works between activation and deactivations, but is removed from memory when the application closes.
FIGURE 8!5: App Tile front
FIGURE 8!6: App Tile back
c08.indd 233c08.indd 233 28/07/12 6:04 PM28/07/12 6:04 PM
234 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
Now that you understand the idiosyncrasies of Windows Phone 7, you can learn how to get the tools for development.
GETTING THE TOOLS YOU NEED To develop software for Windows Phone 7 you need a machine running Windows (Vista or Windows 7), Visual Studio 2010, and the Phone SDK, as well as a Windows Phone 7 device to test with.
Hardware HTC, Nokia, and Samsung are currently manufacturing Windows Phone 7 devices. Device resolutions are 800 ! 480 pixels, and most are outfi tted with both front- and rear-facing cameras, and screens from 4.3 to 4.7 inches. They are primarily found on GSM carriers.
Visual Studio and Windows Phone SDK Code for the Windows Phone is written in the .NET Framework, either with XNA (Microsoft’s run time for game development), or a custom version of Silverlight (Microsoft’s Rich Internet Application framework). User interfaces are created with XAML (eXtensible Application Markup Language).
The Windows Phone SDK works with Visual Studio Express, and will install it if you don’t already have it installed. If you have another version of Visual Studio 2010 on your machine it will add the functionality to that install. The SDK also installs a specialized version of Expression Blend set up to work specifi cally for Windows Phone 7 development. Expression Blend is a tool developed by Microsoft for working with XAML. It provides similar functionality to Visual Studio, though its layout is designed to be more user friendly to designers.
Installation Microsoft’s App Hub (http://create.msdn.com/) is the download site for the Windows Phone SDK.
The Windows Phone SDK installer includes:
" Visual Studio 2010 Express for Windows Phone (if you do not have another version of Visual Studio 2010 installed)
" Windows Phone Emulator
" Windows Phone SDK Assemblies
" Silverlight 4 SDK
" Phone SDK 7.1 Extensions for XNA Game Studio
" Expression Blend for Windows Phone 7
" WCF Data Services Client for Windows Phone
" Microsoft Advertising SDK
c08.indd 234c08.indd 234 28/07/12 6:04 PM28/07/12 6:04 PM
Getting the Tools You Need ! 235
To install the Windows Phone SDK you need:
" Vista (x86 or x64) or Windows 7 (x86 or x64)
" 4 GB of free disk space
" 3 GB of RAM
" DirectX 10 or above capable graphics card with a WDDM 1.1 driver
Getting to Know Visual Studio Visual Studio is the integrated development environment from Microsoft for the .NET Framework. Visual Studio Express for Windows phones is a trimmed-down version of Microsoft’s full retail products. It provides developers with everything they need to develop Windows Phone 7 apps. Though the interface may seem daunting to the uninitiated, it has a relatively simple learning curve. You are afforded both a WYSIWYG and text-based editor, as shown in Figure 8-7.
FIGURE 8!7: Visual Studio 2010
Getting to Know Expression Blend Expression Blend is a user interface design tool developed by Microsoft, with emphasis on a WYSIWYG design for XAML-based projects (Silverlight and WPF). Figure 8-8 shows the Blend UI with the standard tools displayed in a Windows Phone 7 Pivot application.
c08.indd 235c08.indd 235 28/07/12 6:04 PM28/07/12 6:04 PM
236 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
WINDOWS PHONE 7 PROJECT Ultimately, a Windows Phone 7 project is similar to a Silverlight project, which is technically a subset of WPF. This section goes over the ins and outs of the Windows Phone 7 project structure, and gives you some resources for adding to the stock controls in the SDK.
Silverlight vs. Windows Phone 7 Silverlight contains a subset of APIs from the .NET Framework, all optimized to run in a browser host so that it can be run cross-platform. The Windows Phone 7 SDK is a subset of that. When porting third-party Silverlight libraries you have to make sure they build against the WP7 version of Silverlight because some of the APIs don’t transfer.
Windows Phone 7 contains a fair amount of controls for your application, but they are not all- inclusive. Multiple control toolkits have been released on CodePlex; see http://silverlight .codeplex.com/ (Microsoft) and http://coding4fun.codeplex.com/ (independent developer).
Most of the companies that produce control packages for WPF and Silverlight have created Windows Phone 7 control packages as well. Telerik (http://www.telerik.com/products/windows-phone .aspx), ComponentOne (http://www.componentone.com/SuperProducts/StudioWindowsPhone/), and Infragistics (http://www.infragistics.com/dotnet/netadvantage/windows-phone .aspx#Overview) all have prebuilt and skinnable control packs for Windows Phone 7 ranging in price from roughly $100 to $1,500.
FIGURE 8!8: Expression Blend for Visual Studio
c08.indd 236c08.indd 236 28/07/12 6:04 PM28/07/12 6:04 PM
Windows Phone 7 Project ! 237
Anatomy of a Windows Phone 7 App This section covers the basic design elements used in Windows Phone 7 application development, and how you can leverage the tools you have at hand to implement them.
Storyboards Storyboards are Silverlight’s control type for managing animations in code. They are defi ned in a given page’s XAML and leveraged using code behind. Uses for these animations are limited only by the transform operations you are allowed to perform on objects. Anytime you want to provide the user with a custom transition between your pages or element updates, you should consider creating an animation to smooth the user experience.
Because storyboards are held in XAML you can either edit them manually or use Expression Blend’s WYSIWYG editor.
In Blend, in the Objects and Timelines Pane at the left, click the (+) icon to create a storyboard (see Figure 8-9).
FIGURE 8!9: Storyboards in Blend
Once you have a storyboard, you can add key frames on your time line for each individual element you would like to perform a transformation on. This can include moving objects and changing properties (like color or opacity). After setting up your time line, you can start the storyboard in code.
The name you created for your storyboard will be accessible in code behind.
c08.indd 237c08.indd 237 28/07/12 6:04 PM28/07/12 6:04 PM
238 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
Pivot vs. Panorama Both the Pivot and Panorama controls are used to delineate categories and subsets of data. With the Pivot control you get strict isolation of these groupings (see Figure 8-10), with the menu providing discoverable UI to show the other categories. With the Panorama control (Figure 8-11) you get transitions between the groupings with discoverable content on the window boundaries.
FIGURE 8!10: Pivot control FIGURE 8!11: Panorama control
The Windows Phone 7 Emulator The Windows Phone 7 emulator (see Figure 8-12) is a very powerful tool. Not just a simulator, the emulator runs a completely sandboxed virtual machine in order to better mimic the actual device. It also comes with some customization and runtime tools to manipulate sensors that are being emulated on the device, including GPS and accelerometer, as well as provide a way to capture screenshots while testing and developing applications.
Debugging Code I fi nd the debugging experience inside of Visual Studio to be supremely superior to the ones in Eclipse and the third-party frameworks. The load time of the Emulator is quite fast. It acts responsively, and the step-through just works. FIGURE 8!12: The Windows
Phone emulator
c08.indd 238c08.indd 238 28/07/12 6:04 PM28/07/12 6:04 PM
Building the Derby App in Windows Phone 7 ! 239
BUILDING THE DERBY APP IN WINDOWS PHONE 7 In this section you implement the features of the Derby Names project using Microsoft Visual Studio, while also taking time to learn Windows Phone 7–specifi c technologies.
Creating the Project Open Visual Studio and create a new Windows Phone project. For this application, choose Panorama because it offers a UI in which you can share your data. Figure 8-13 shows the New Project window.
FIGURE 8!13: Creating a Panorama project
Once you have created the application, we will step through the Solution (Figure 8-14). In a Panorama application the application is created with the default Panorama background. Visual Studio will create SampleData and ViewModels for your application. Ultimately, you will be able to remove these from your application when you implement your service communications.
c08.indd 239c08.indd 239 28/07/12 6:04 PM28/07/12 6:04 PM
240 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
App.xaml is the entry point for your application and MainPage.xaml is the page that loads by default. ApplicationIcon.png is the default icon that is shown when pinned, and it is shown attached to toast notifi cations. SplashScreenImage.jpg is the default image that shows when your app is loading, and PanoramaBackground.jpg is a default background created for Panorama apps.
User Interface The default Panorama application defi nes its DataContext in XAML. The DataContext has fi rst item’s binding associated by default as shown in Figure 8-15. The Panorama control can be likened to any collection-based UI element (UITableView in iOS or the ListView in Android), and the PanoramaItems are the respective rows in that collection element.
When you feel familiar enough to start working with the data you will need to create a service reference to the OData feed. For testing purposes I created a local instance of the service on my machine, but this will work on remote services as well, as long as they support public consumption (see Chapter 3).
FIGURE 8!14: Solution Explorer
FIGURE 8!15: Basic Panorama
c08.indd 240c08.indd 240 28/07/12 6:04 PM28/07/12 6:04 PM
Building the Derby App in Windows Phone 7 ! 241
Prior to Windows Phone SDK version 7.1, a manual process using the svcutil command- line tool was required to create the service entities. As of 7.1, to reference an OData feed you need only to right-click your project, choose Add Service Reference, enter in the URL of your service (as shown in Figure 8-16), and click Go. After it has found the service it should enumerate the models. You are then allowed to update the namespace and create this reference.
Once you create the service you can start working with the Panorama control to bind the data available from these entities.
After you have made this service, be sure to reference this entity context when your page needs to make calls to the service:
readonly DerbyNamesEntities context = new DerbyNamesEntities(new Uri(“http://localhost:1132/DerbyNames.svc/”));
Derby Names To bind data to your Panorama item you need to set the ItemsSource and TextBlock bindings.
Each individual entry in the DerbyNames entity in OData (Figure 8-16) contains properties for Name and League, which you will bind to the TextBlocks in your Panorama item.
ODATA
<entry> <id>http://localhost:1132/DerbyNames.svc/DerbyNames(29530)</id> <title type=”text”></title> <updated>2012-04-17T01:11:56Z</updated> <author> <name /> </author> <link rel=”edit” title=”DerbyName” href=”DerbyNames(29530)” /> <category term=”DerbyNamesModel.DerbyName” scheme= “http://schemas.microsoft.com/ado/2007/08/dataservices/scheme” /> <content type=”application/xml”> <m:properties> <d:DerbyNameId m:type=”Edm.Int32”>29530</d:DerbyNameId> <d:Name>$Yd Vicious$</d:Name> <d:Number>5150</d:Number> <d:DateAdded m:type=”Edm.DateTime”>2010-01-15T00:00:00</d:DateAdded>
FIGURE 8!16: Service reference for OData
c08.indd 241c08.indd 241 28/07/12 6:04 PM28/07/12 6:04 PM
242 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
<d:League>TBD (delete 5/10/11)</d:League> </m:properties> </content> </entry>
In Figure 8-17 you see that the ItemsSource for the ListBox has been marked as the binding container, and the two TextBlocks in the Data Template have the bindings to the League and Name properties. Please remember that casing is important.
PANORAMA ITEM
<controls:Panorama Title=”derby girls”> <controls:PanoramaItem Header=”names”> <ListBox x:Name=”DerbyNamesList” Margin=”0,0,-12,0” ItemsSource=”{Binding}”> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin=”0,0,0,17” Width=”432”> <TextBlock Text=”{Binding Name}” TextWrapping=”Wrap” Margin=”12,-6,12,0” Style=”{StaticResource PhoneTextExtraLargeStyle}” /> <TextBlock Text=”{Binding League}” TextWrapping=”Wrap” Margin=”12,-6,12,0” Style=”{StaticResource PhoneTextSmallStyle}” /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </controls:PanoramaItem>
WHEN WILL THEN BE NOW?
The Panorama Item has the reference to the StaticResource of PhoneText ExtraLargeStyle. This is what I was mentioning earlier in the “Metro” section. This is a system property that I am leveraging to get the instant UI update when the system theme is changed.
Now that you have the ListBox ready to be bound to you can load content from the service.
In the WCF Data Services namespaces you receive access to specialized collections for working from remote data. The DataServiceCollection<T> object holds the dynamic entities bound from the web service.
Because you are only querying the base set of data and not passing any parameters to the query, the data binding method is very simple. You fi rst create a collection of type DerbyName to hold the data. Bind that collection to the ItemsSource property of the list you want the data bound to. Assign a callback to the LoadCompleted event on the collection (this is a great place for exception handling), and set your query (in this case /DerbyNames because you want all the names on the system). Then you bind the collection asynchronously with the web service by running your query.
c08.indd 242c08.indd 242 28/07/12 6:04 PM28/07/12 6:04 PM
Building the Derby App in Windows Phone 7 ! 243
DATABINDING FUNCTION private void LoadDerbyNames() { var derbyNamesCollection = new DataServiceCollection<DerbyName>(context); DerbyNamesList.ItemsSource = derbyNamesCollection; derbyNamesCollection.LoadCompleted += coll_LoadCompleted; var DerbyNamesQuery = “/DerbyNames”; derbyNamesCollection.LoadAsync(new Uri(DerbyNamesQuery, UriKind.Relative)); }
Calling the LoadDerbyNames function from your page’s Load function results in the UI depicted in Figure 8-17.
Leagues Each derby team belongs to a league. The entity for League is similar to the DerbyNames entity, and will make it easy to bind from. The following code block shows an example of a single entity of the Leagues type.
<entry> <id>http://localhost:1132/DerbyNames.svc/Leagues(1)</id> <title type=”text”></title> <updated>2012-04-17T20:00:29Z</updated> <author> <name /> </author> <link rel=”edit” title=”League” href=”Leagues(1)” /> <category term=”DerbyNamesModel.League” scheme= “http://schemas.microsoft.com/ado/2007/08/dataservices/scheme” /> <content type=”application/xml”> <m:properties> <d:LeagueId m:type=”Edm.Int32”>1</d:LeagueId> <d:LeagueName>5 Cities Roller Kitties</d:LeagueName> <d:URL m:null=”true” /> <d:StateProvince m:null=”true” /> <d:CountryCode m:null=”true” /> </m:properties> </content> </entry>
This time you will be using the LeagueName property only.
<controls:PanoramaItem Header=”leagues”> <ListBox x:Name=”DerbyLeaguesList” Margin=”0,0,-12,0” ItemsSource=”{Binding}”> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin=”0,0,0,17” Width=”432”> <TextBlock Text=”{Binding LeagueName}” TextWrapping=”Wrap” Margin=”12,-6,12,0” Style=”{StaticResource PhoneTextExtraLargeStyle}” />
FIGURE 8!17: Panorama Item
c08.indd 243c08.indd 243 28/07/12 6:04 PM28/07/12 6:04 PM
244 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
</StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </controls:PanoramaItem>
Using effectively the same function for pulling leagues instead of derby names, you bind to the DerbyLeaguesList ListBox.
private void LoadLeagues() { var derbyLeagueCollection = new DataServiceCollection<League>(context); DerbyLeaguesList.ItemsSource = derbyLeagueCollection; derbyLeagueCollection.LoadCompleted += coll_LoadCompleted; var DerbyLeaguesQuery = “/Leagues”; derbyLeagueCollection.LoadAsync(new Uri(DerbyLeaguesQuery, UriKind.Relative)); }
Calling the LoadLeagues function from your page’s Load function results in the following UI being displayed in the second panorama item (Figure 8-18).
DISTRIBUTION To distribute applications in the App Hub you must create a developer account at https://users.create.msdn.com/Register. Registration costs $99 per year and allows you to:
" Make free, paid, or ad-funded apps and games.
" Submit unlimited paid apps to Windows Phone Marketplace.
" Submit up to 100 free apps to Windows Phone Marketplace; additional submissions are $19.99 USD per submission.
" Expand your reach with worldwide distribution and trial options.
Additionally, all apps are content and code-certifi ed.
Figure 8-19 shows the site for creating a Microsoft Developer account. Note that the Student account type has specifi c requirements.
Microsoft DreamSpark (http://www.dreamspark.com/Product/Product.aspx?productid=26) is a program for students, and gives them a free App Hub account.
Submitting your application to the App Hub is a fi ve-step process. First, you upload your compiled application XAP fi le. The XAP fi le is the binary for your application that will be pushed to the phone. To do this you must have a unique name for your application, you must select whether this application is being released to the public or simply being distributed to the App Hub for a private beta test, and you need to specify a version for your app. Next, you must provide an application description (this includes category of app, keywords, detailed description, languages supported, and art assets). Third, you set up your price and select what markets you want to distribute your application in. Next, you provide test information so that the developer in charge of approving your app understands the use cases.
FIGURE 8!18: Binding to leagues
c08.indd 244c08.indd 244 28/07/12 6:04 PM28/07/12 6:04 PM
Other Useful Windows Phone Things ! 245
Finally, you choose your publishing options (as soon as approved, as soon as approved but hidden, manual publish). You then submit your application for certifi cation.
OTHER USEFUL WINDOWS PHONE THINGS This section covers persisting data locally, the different types of notifi cations you can use to interact with your users, the usage of the sensors of the device, and using external resources to improve the quality of your application.
O" ine Storage Windows Phone 7 has the System.IO.IsolatedStorage namespace to handle persisting data between application runs. Isolated storage is application-specifi c storage on the device fi lesystem.
The simplest means of implementing an isolated storage solution in Windows Phone is to leverage your PhoneApplicationService’s state-based events. Launching and Activated handle application load and resume from tombstone, respectively; Closing and Deactivated handle application exit and tombstoning, respectively. Making sure that your application loads your isolated storage instance on Launch and Activate, and saves on Close and Deactivate, gives you tremendous capability with little effort.
FIGURE 8!19: App Hub registration
c08.indd 245c08.indd 245 28/07/12 6:04 PM28/07/12 6:04 PM
246 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
The following code persists a unique identifi er to be passed to a web service as part of an authentication token. You fi rst need to declare the property for the unique identifi er in your App.xaml.cs (your application’s code behind fi le):
public partial class App : Application { public Guid UserAuthToken { set; get; } }
Then you need to add calls in your events to the respective Load and Save functions:
private void Application_Launching(object sender, LaunchingEventArgs e) { BindPersistantDataFromIsolatedStorage(); }
private void Application_Activated(object sender, ActivatedEventArgs e) { BindPersistantDataFromIsolatedStorage(); }
private void Application_Deactivated(object sender, DeactivatedEventArgs e) { SavePersistantDataToIsolatedStorage(); }
private void Application_Closing(object sender, ClosingEventArgs e) { SavePersistantDataToIsolatedStorage(); }
You then need to use isolated storage in the respective Load and Save functions:
private void BindPersistantDataFromIsolatedStorage() { IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; Guid authToken;
if (settings.TryGetValue<Guid>(“authtoken”, out authToken)) { UserAuthToken = new Guid(authToken); } } private void SavePersistantDataToIsolatedStorage() { IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; if (UserAuthToken is Guid) { appSettings[“authtoken”] = (UserAuthToken as Guid).ToString(); appSettings.Save(); } }
c08.indd 246c08.indd 246 28/07/12 6:04 PM28/07/12 6:04 PM
Other Useful Windows Phone Things ! 247
Windows Phone 7 Isolated Storage Explorer Available on CodePlex, the Isolated Storage Explorer includes a WPF desktop application and a Visual Studio plug-in to allow developers to manage data held in isolated storage on the device. By adding a reference to the Isolated Storage Explorer Assembly and adding a command in your application launching event you get a per-app instance treating your isolated storage like a folder in Windows.
Notifi cations Setting up notifi cations for Windows Phone 7 is a multistage process. First you must build up a push channel to receive communications within your app. Creating that push channel provides you with a Service URI to post data to. Posting data in specifi c formats determines what type of message will be displayed to the client app.
private void EnablePushNotifications() { HttpNotificationChannel pushChannel = HttpNotificationChannel.Find(channelName);
if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName);
pushChannel.ChannelUriUpdated += PushChannel_ChannelUriUpdated; pushChannel.ErrorOccurred += PushChannel_ErrorOccurred; pushChannel.ShellToastNotificationReceived += PushChannel_ShellToastNotificationReceived; pushChannel.HttpNotificationReceived += PushChannel_HttpNotificationReceived; pushChannel.Open();
pushChannel.BindToShellToast(); pushChannel.BindToShellTile(); } else { pushChannel.ChannelUriUpdated += PushChannel_ChannelUriUpdated; pushChannel.ErrorOccurred += PushChannel_ErrorOccurred; pushChannel.ShellToastNotificationReceived += PushChannel_ShellToastNotificationReceived; pushChannel.HttpNotificationReceived += PushChannel_HttpNotificationReceived; } System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString()); }
You can use three types of notifi cations. The fi rst and simplest is the toast notifi cation. With a toast notifi cation you can pass a title, a string of content, and a parameter. The title will be boldfaced when displayed, the content will follow nonboldfaced, and the parameter will not be shown, but it is what is sent to your application when the user taps on the toast message. This can contain
c08.indd 247c08.indd 247 28/07/12 6:04 PM28/07/12 6:04 PM
248 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
parameters to load on the default page, or a relative link to the page you want loaded when the app loads as a result of the tap.
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { StringBuilder message = new StringBuilder(); string relativeUri = string.Empty;
message.AppendFormat(“Received Toast {0}:\n”, DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message. foreach (string key in e.Collection.Keys) { message.AppendFormat(“{0}: {1}\n”, key, e.Collection[key]);
if (string.Compare( key, “wp:Param”, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.CompareOptions.IgnoreCase) == 0){ relativeUri = e.Collection[key]; } }
Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString())); }
The second and more complex notifi cation is the tile notifi cation. With the tile notifi cation you can update the application tile content. The XML data that you post contains fi elds for the title on the front of the tile, front of the tile background image, the count for the badge, the title for the back of the tile, the back of the tile background image, and string of content for the back of the tile.
The images for the background of the tiles must be local resource URIs. The count for the badge cannot exceed 99.
The third and most developer-centric notifi cation type is raw. With the raw notifi cation type you can pass data directly to the app. It will not be delivered if the application is not running.
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e) { string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body)) { message = reader.ReadToEnd(); }
Dispatcher.BeginInvoke(() =>
c08.indd 248c08.indd 248 28/07/12 6:04 PM28/07/12 6:04 PM
Other Useful Windows Phone Things ! 249
MessageBox.Show(String.Format(“Received Notification {0}:\n{1}”, DateTime.Now.ToShortTimeString(), message)) ); }
GPS Windows Phone 7 has built-in functionality for leveraging the geolocation sensors in your device. Using the System.Device.Location namespace and tracking the PositionChanged event of a GeocoordinateWatcher adds a button to your application bar that will tell you the device’s distance from our local derby team, the Lansing Derby Vixens.
The Windows Phone emulator has a great interface for mocking GPS location changes while developing and debugging your app, as shown in Figure 8-20.
GeoCoordinate DerbyVixensLocation = new GeoCoordinate(42.7337, -84.5469); GeoCoordinateWatcher _GeoCoordinateWatcher;
private void DistanceToVixens() { try { _GeoCoordinateWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High) { MovementThreshold = 10 /* 10 meters. */ }; _GeoCoordinateWatcher.PositionChanged += GeoCoordinateWatcherPositionChanged; _GeoCoordinateWatcher.Start(); }
catch { } }
private void GeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { _GeoCoordinateWatcher.PositionChanged -= GeoCoordinateWatcherPositionChanged;
GeoCoordinate current = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude); var metersFromVixens = current.GetDistanceTo(DerbyVixensLocation); MessageBox.Show(string.Format(“{0:0.00} meters from the Lansing Derby Vixens”, metersFromVixens)); _GeoCoordinateWatcher.Stop(); _GeoCoordinateWatcher.Dispose(); _GeoCoordinateWatcher = null; }
c08.indd 249c08.indd 249 28/07/12 6:04 PM28/07/12 6:04 PM
250 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
Accelerometer In addition to GPS, Windows Phone 7 devices are outfi tted with an accelerometer. The emulator provides a 3-D interface for simulating accelerometer change events, as shown in Figure 8-21.
You can track the movement of the device by capturing the ReadingChanged event on the accelerometer. However, you need to have a delegate to call back to the UI thread if you want to display anything special based on the event. If the application can access the UI thread, the ReadingChanged event handler will call the delegate function; otherwise, it will dispatch the event on the UI thread. You must also make sure that when you are done capturing this data, you stop the accelerometer to preserve battery life.
private void LoadAccelerometer() { acc = new Accelerometer(); acc.ReadingChanged += OnAccelerometerReadingChanged; acc.Start(); }
delegate void AccelerometerUITextUpdateDelegate(TextBlock accText, string text); void AccelerometerUITextUpdate (TextBlock accText, string text) {
FIGURE 8!20: Location pane
c08.indd 250c08.indd 250 28/07/12 6:04 PM28/07/12 6:04 PM
Other Useful Windows Phone Things ! 251
accText.Text = text; }
void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e) { string accelOutput = String.Format(“X:{0} \n Y:{1} \n Z:{2}”, e.X, args.Y, args.Z); if (accText.CheckAccess()) { AccelerometerUITextUpdate (accText, accelOutput); }
else { accText.Dispatcher.BeginInvoke( new AccelerometerUITextUpdateDelegate (AccelerometerUITextUpdate), accText, accelOutput); } }
private void AccelerometerDataComplete(){ acc.Stop(); }
FIGURE 8!21: Accelerometer panes
c08.indd 251c08.indd 251 28/07/12 6:04 PM28/07/12 6:04 PM
252 ! CHAPTER 8 GETTING STARTED WITH WINDOWS PHONE 7
Web Services The Derby application is an example of leveraging data over the web to add value to your application. If you don’t want to be the central repository for all data exposed to your users, you can leverage web services that exist from other vendors.
As of spring 2011, the Windows Azure Marketplace has more than 16 categories of free and premium data sets that you can consume with content ranging from real estate and mortgage information, to demographics from the UN, to indicators from the World Bank. The data market is available at https://datamarket.azure.com/.
SUMMARY Although the newcomer to the space, the Windows Phone 7 platform has been working hard to implement all of the features expected by a smartphone user, without giving up the Metro design philosophy. Hopefully, you now feel comfortable in the Windows Phone 7 tooling, and can see the parallels between iOS, Android, and Windows Phone 7 when doing UI and back-end development. This chapter covered using sensors, implementing Metro-specifi c design patterns (such as tiles), calling out to web services, and getting your application submitted for approval to the Marketplace.
This chapter also covered getting the tools you need to develop applications for Windows Phone 7. It covered the UI design patterns found in these applications and discussed how to build your demo application using the .NET Framework and your existing web service. You learned how to leverage the sensors on the device, as well as the framework-specifi c implementations of offl ine storage. Finally, you learned the process for getting a developer account and how to prepare to distribute your application.
c08.indd 252c08.indd 252 28/07/12 6:04 PM28/07/12 6:04 PM