October 2010

Volume 25 Number 10

Mobile Apps - Getting Started with Windows Phone Development Tools

By Joshua Partlow | October 2010

Like many of you, I’ve spent the past year or so inundated by a slew of post-apocalyptic, Terminator-esque ads telling me what Droid Does. I’ve hummed along with the T-Mobile My Touch commercials. I’ve read articles about how many apps Apple has sold for the iPhone.

Unlike many of you, I’ve also spent the past year repeatedly telling friends and family that, yes, I do in fact work on a mobile phone, but no, none of those are the phone that I work on.

So it’s fair to say that I was rather excited when Steve Ballmer and Joe Belfiore announced Windows Phone 7 at Mobile World Congress (MWC) in Barcelona, Spain. It was 6 a.m. Redmond time on Feb. 15, 2010, but I was sitting in a Microsoft conference room with a few hundred coworkers, some still in pajamas, anxiously waiting to watch a live feed of Belfiore demoing our new vision for the phone. I’ll probably watch many more products launched in the years to come, but I’m sure this will remain one of the highlights. It was certainly the most exciting moment I’ve had at Microsoft to date.

In an attempt to get you equally excited about the potential for Windows Mobile app development, over the course of this article I’m going to introduce you to the Windows Phone 7 application platform. Specifically, I’ll talk about the basic components of the application platform, give you an overview of the Windows Phone Developer Tools, and walk you through the creation of a Windows Phone application that accesses a Web service.

A Break from the Past

With Windows Phone 7, Microsoft acknowledged that there’s been a change in the mobile landscape. There’s a new expectation that, beyond just allowing you to read e-mail and documents, a phone should also be an integral part of your life. Allowing you to do things like listen to music, share pictures and videos, and keep in touch with friends. Apparently, business users enjoy Facebook, too, and teenagers enjoy browsing the Web. It’s not that shocking, I know, but it really does represent an evolution of the role a phone is expected to play in our lives.

As potential customers, I hope you saw Belfiore’s demo and walked away ready to buy a phone. More importantly, as developers, I hope you came away curious about the application story. After all, creating a new OS is only part of competing in the crowded mobile market. If our premise is that users want a phone that enables them to merge their work and personal lives in new and exciting ways, then it’s going to be a combination of the OS and an ecosystem of awesome applications that makes that possible.

I won’t spend time describing the phone, because I’m sure you can find breakdowns on your favorite blog, but rather get to what I imagine are two bigger questions for you as developers: What’s the Microsoft application platform for Windows Phone 7, and how do you get started building apps?

A New World for Developers

Well, if MWC started the revelation of Windows Phone 7, then the Game Developers Conference (GDC) and MIX10 completed the story. At GDC and MIX, Microsoft announced that the Windows Phone 7 application platform is based on Silverlight and the XNA Framework. If you’ve developed for Windows Mobile in the past, then you know that this marks a fundamental divergence from previous versions of the OS.

So why change things up? Well, my opinion is that the strength of Microsoft lies in its broad suite of products, and that it’s never more successful than when it ties them together. Prior to Windows Phone 7, the mobile development story might have leveraged some Microsoft assets, but not nearly to the extent you’ll see now.

The XNA Framework was designed to allow developers to create complex and powerful 2D and 3D games that could span desktop, console and mobile spaces. It was designed around a broad set of hardware, from the graphics capabilities of the Xbox console to the sensor and touch capabilities of the Zune HD. What’s more, it was also designed with networked gameplay in mind.

Silverlight is the Microsoft desktop platform for Web-based media and productivity applications. Here’s a platform that, when combined with Expression Blend, is designed to enable the creation of compelling UIs that can work well standing alone or tied into Web services.

Both the XNA Framework and Silverlight are strong platforms in their own right. But when combined on the phone, they take things to a whole new level, allowing for the development of applications with beautiful UIs and stunning graphics that can easily leverage the capabilities of a mobile device.

As I experimented with Silverlight and XNA applications early in the Windows Phone 7 development cycle, I was quickly convinced that it was a good direction. I was new to both platforms, as well as to managed code, and the speed with which I could develop visually cool applications impressed me.

Another notable feature of the new application platform is the standardization of hardware and your programmatic access to it. Specifically, another announcement that came out of MIX was that Windows Phones would support a core set of hardware that developers could access in a consistent and reliable manner. Why is that important? Historically, it has been difficult to develop applications to run on multiple phones because you ended up having to create device-specific versions of your application. Some phones wouldn’t run your application without significant rework, or wouldn’t work at all because they didn’t support features needed by your app.

With Windows Phone 7, there won’t be a question of whether the phone your app is running on has support for location services—all of them will. There won’t be a question of whether the phone has an accelerometer and whether you can access it—all of them will, and the access will be consistent. There won’t be a question of whether your phone is touch-enabled—all of them will be, and again the access will be consistent. The list goes on, but I hope you get the idea.

With the Windows Phone 7 application platform, you’ll be able to develop a single application and know that what you test on your phone will work on all of them. There will still be differentiation of hardware on Windows Phones, but there will also be a core foundation of hardware that your applications will be able to rely upon.

For more details on the Windows Phone hardware and the architecture of the application platform, you can refer to the application platform and hardware overviews on MSDN at msdn.microsoft.com/library/ff402531(v=VS.92) and msdn.microsoft.com/library/ff637514(v=VS.92).

Getting Started

OK, now that we’ve talked briefly about the application platform, let’s talk about how you develop on it. Currently in beta, the Windows Phone Developer Tools are available for download from the Windows Phone Developer Portal (developer.windowsphone.com). If you don’t have Visual Studio, the Developer Tools come with Visual Studio 2010 Express for Windows Phone. If you have Visual Studio 2010, the tools will integrate directly with it. Either way, you’ll have everything you need to develop for Windows Phone 7.

The Developer Tools include a Windows Phone Emulator and Microsoft Expression Blend for Windows Phone. While not final, the beta is a good indication of what you’ll have at launch. It’s possible you might need to make some modifications to your code between the beta and final version of the tools, but those changes should be minor or at least well-documented.

I’ve installed the beta version of the tools, using Visual Studio 2010 Express for Windows Phone, and it’s what I’ll be using for my example. If you want a slightly simpler tutorial to start with, you can check out the Windows Phone Getting Started Guide on MSDN at msdn.microsoft.com/library/ff402529(v=VS.92).

So, what to create? Rather than do a general “hello world” or “make that flashlight” app I know you’re dying to see, I thought I’d share a portion of a fun little project I’ve been working on.

At MIX I happened to attend a session on a Microsoft Azure project: Microsoft Codename “Dallas”. Dallas is basically a marketplace for developers interested in getting data for their applications from Web services looking to sell it. Currently in its second community technology preview (CTP), you can utilize both the online portal and a number of free data sources provided as a trial to experiment with what the service has to offer. While the current list of providers isn’t huge, there’s still a bunch of stuff to play with. I personally found the image data provided by NASA on the Mars missions interesting and decided it would be cool to create a Windows Phone application that could browse through Mars rover pictures.

As a warning, the code included here and available for download is a working sample, but if you want to run it you’ll need to register for the Dallas CTP to get an account key and user ID, which I’ve left blank in my code.

Creating Your Project

The first step to creating the Mars rover image viewer is to create a Windows Phone application project. Launching the express version of Visual Studio 2010 for Windows Phone, you’re presented with a standard Visual Studio Start Page. From there, you can select New Project, which will allow you to choose from a number of different project templates. If you’ve only installed the Windows Phone Developer Tools, your list will be limited to Silverlight for 
Windows Phone and XNA Game Studio 4.0.

I selected a Windows Phone app from the Silverlight templates and named my project MarsImageViewer. From there, Visual Studio does its magic and generates a project for you.

If you’ve worked with Windows Presentation Foundation (WPF) or Silverlight before, you shouldn’t be all that surprised by what you get. You’ll see that you’re provided a design surface with a cool phone skin, a toolbox with some basic controls and a number of XAML files with their associated C# code-behind files (see Figure 1). If you care to learn about the exact differences between Silverlight and XNA on Windows and Silverlight and XNA on Windows Phone, you can reference the Windows Phone framework overview on MSDN at msdn.microsoft.com/library/ff402528(v=VS.92).

image: Your Initial Windows Phone Project in Visual Studio

Figure 1 Your Initial Windows Phone Project in Visual Studio

Understanding the XAML

As with Silverlight, the Windows Phone 
application template provides an App.xaml file and a MainPage.xaml file, which are the heart of your application. I won’t spend time going over these in detail because they function in basically the same manner as their Silverlight counterparts, but I would like to point out two key differences before moving on to creating the application.

The first point of interest is in the default App.xaml file. You’ll notice that while the majority of the auto-generated code is the same as you’d see in a desktop Silverlight project, there’s an additional section that contains a PhoneApplicationService object:

<shell:PhoneApplicationService 
  Launching="Application_Launching" Closing="Application_Closing" 
  Activated="Application_Activated" Deactivated="Application_Deactivated"/>

With the Windows Phone Developer Tools beta, there’s a new execution model that dictates the behavior of applications; this section of markup, combined with the code-behind in App.xaml.cs, is one place where that model surfaces. If you’d like to better understand the behavior of Windows Phone applications and this object, you can refer to the topic Execution Model for Windows Phone on MSDN at msdn.microsoft.com/library/ff769557(VS.92).

The second point of interest is in the MainPage.xaml file, and actually where I’ll start creating the application. If you look closely, much of the file is similar to Silverlight, but there’s a commented-out XAML section for an application bar. The application bar is a system control you can use to expose buttons and menu items. Not only does it save you the trouble of creating your own, its use lends consistency to the phone, as it appears and behaves exactly like the one used in the core phone applications. While I’ll modify this template markup to create my application bar, you can also create one for a page using C# (see msdn.microsoft.com/library/ff431786(VS.92) for details).

Steal My App Bar

The first step to creating the application bar is to find the icons you want to use. You can create your own, or you can use some of the ones included with the developer tools. By default, the included icons can be found at C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Icons\ for 64-bit Windows and C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons\ for 32-bit Windows. They’re definitely worth checking out because they match the look and feel of the phone.

Once you’ve picked the images you want, create an Images folder in your project and add the icons to it. Then set the properties for each icon: Build Action should be “Content” and Copy to Output Directory should be “Copy always,” as shown in Figure 2.

image: Adding Image Resources to the Project

Figure 2 Adding Image Resources to the Project

The next step is to uncomment the application bar markup and modify it for your application. In this case, that entails creating two buttons and their associated event handlers. Specifically, I created a button for retrieving the next photo and a button for retrieving the previous photo. I also added click events to the XAML and allowed Visual Studio to generate the event handlers. The application bar XAML should now look like the code in Figure 3.

Figure 3 Configuring the App Bar

<phone:PhoneApplicationPage.ApplicationBar>
  <shell:ApplicationBar 
    IsVisible="True" IsMenuEnabled="False">
    <shell:ApplicationBarIconButton 
      x:Name="appbar_BackButton" 
      IconUri="/Images/appbar.back.rest.png" 
      Text="Back" 
      Click="appbar_BackButton_Click">
    </shell:ApplicationBarIconButton>
    <shell:ApplicationBarIconButton 
      x:Name="appbar_ForwardButton" 
      IconUri="/Images/appbar.next.rest.png" 
      Text="Next" 
      Click="appbar_ForwardButton_Click">
    </shell:ApplicationBarIconButton>
  </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Before moving to the code-behind, I also took the time to specify an application title and page name and to add an image control to the root grid of MainPage.xaml, as shown in Figure 4. This should leave the design surface looking like Figure 5, where you’ll notice a blank app bar of four circles.

Figure 4 MainPage.xaml

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">
  <TextBlock x:Name="ApplicationTitle" 
    Text="MarsImageViewer" 
    Style="{StaticResource PhoneTextNormalStyle}"/>
  <TextBlock x:Name="PageTitle" 
    Text="Images" 
    Margin="-3,-8,0,0" 
    Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentGrid" Grid.Row="1">
  <Image Height="300" 
    HorizontalAlignment="Left" 
    Margin="36,104,0,0" 
    Name="MarsImage" 
    Stretch="Fill" 
    VerticalAlignment="Top" 
    Width="400" />
</Grid>

image: The Configured Design Surface

Figure 5 The Configured Design Surface

With the application interface defined, it’s time to get some Mars rover images. The Dallas portal is designed to be user-friendly and allows you to experiment with queries. It also gives you the appropriate Web service URL, shows you how to add parameters and provides the appropriate header information for your queries.

What I discovered through the portal is that the NASA Web service allows queries for image information based on parameters or the retrieval of a specific JPEG image through an image ID. What that implies for this program is that two operations are required. The first is to query for image information, which includes the image ID. The second is to parse the returned XML for the image IDs, which can then be used to retrieve a specific image.

Calling Houston ... I mean, Dallas

So let’s get started. In the default MainPage.xaml.cs file, I added using statements for three namespaces:

using System.Xml.Linq;
using System.IO;
using System.Windows.Media.Imaging;

Then I added a reference to the System.Xml.Linq DLL by right-clicking References in Solution Explorer, selecting Add Reference, selecting System.Xml.Linq and then clicking OK. System.Xml.Linq provides access to classes that aid in loading XML from streams and then querying that XML through LINQ. Don’t worry if you’re not familiar with LINQ; this example uses a minimal amount of LINQ to XML and you can always refer to MSDN for more information.

I also created two private variables for the page. An IEnumerable of XElement objects called entries to store the result of a LINQ to XML query, and an integer index to keep track of the picture I’m on. I then modified the MainPage constructor to initialize the index to 0 and call a getImageIDs function:

private IEnumerable<XElement> entries;
  private int index;
  // Constructor
  public MainPage() {
    InitializeComponent();
    index = 0;
    getImageIDs();
  }

The getImageIDs function is designed to start the retrieval of image information from the Web service. The function uses the Web service URL and a WebClient to start an asynchronous request for the image information:

private void getImageIDs() {
  Uri serviceUri = new Uri("https://api.sqlazureservices.com/NasaService.svc/MER/Images?missionId=1&$format=raw");
  WebClient recDownloader = new WebClient();
  recDownloader.Headers["$accountKey"] = "<Your account key>";
  recDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
  recDownloader.OpenReadCompleted += 
    new OpenReadCompletedEventHandler(recDownloader_OpenReadCompleted);
  recDownloader.OpenReadAsync(serviceUri);
}

You’ll notice that, for simplicity, I’ve hardcoded the missionId parameter to 1, which in this case represents the Opportunity mission. Ideally, this parameter and others would be dynamically defined by the user.

With any asynchronous request, you need a handler. This handler is called when the request for data completes. It then uses the returned stream along with some basic LINQ to XML to access all the “entry” tags in the returned XML; “entry” being the opening tag for each image record:

private void recDownloader_OpenReadCompleted(
  object sender, OpenReadCompletedEventArgs e) {
  if (e.Error == null) {
    Stream responseStream = e.Result;
    XNamespace ns = "https://www.w3.org/2005/Atom";
    XElement marsStuff = XElement.Load(responseStream);
    entries = marsStuff.Elements(ns + "entry");
    string imageID = 
      (string)entries.ElementAt<XElement>(index).Element(
      ns + "title").Value;
    getImage(imageID);
  }
}

The resulting collection is stored to the IEnumerable of XElement objects (entries), which I declared earlier. With a final bit of LINQ to XML, the handler then retrieves the value of the title tag for the first XElement in entries. The value of the title tag in this XML schema happens to correspond to the image ID, which is then passed into a getImage function.

The getImage function is similar to the getImageIDs function. The only difference is the Web service URL that’s used. This function asynchronously retrieves a stream to the image identified by the ID parameter. Its handler then uses that stream to set the source of the picture control I defined in MainPage.xaml (see Figure 6).

Figure 6 Retrieving the Image

private void getImage(string ID) {
  Uri serviceUri = new Uri(
    "https://api.sqlazureservices.com/NasaService.svc/MER/Images/" + 
    ID + "?$format=raw");
  WebClient imgDownloader = new WebClient();
  imgDownloader.Headers["$accountKey"] = "<Your account key>";
  imgDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
  imgDownloader.OpenReadCompleted += 
    new OpenReadCompletedEventHandler(imgDownloader_OpenReadCompleted);
  imgDownloader.OpenReadAsync(serviceUri);
}
private void imgDownloader_OpenReadCompleted(
  object sender, OpenReadCompletedEventArgs e) {
  if (e.Error == null) {
    Stream imageStream = e.Result;
    BitmapImage imgsrc = new BitmapImage();
    imgsrc.SetSource(imageStream);
    MarsImage.Source = imgsrc;
  }
}

Buttoning up Buttons

At this point, the rest of the application is pretty simple, with only the auto-generated event handlers for the application bar buttons remaining to be implemented. These are the buttons that will be used to advance forward and backward through the Mars rover pictures. As you can see, I basically just reused the getImage function and added some logic to handle changing the index of the current record in the entries collection. Here’s the handler for the back button:

private void appbar_BackButton_Click(
  object sender, EventArgs e) {
  if (index > 0) {
    index--;
    XNamespace ns = "https://www.w3.org/2005/Atom";
    string imageID = (string)entries.ElementAt<
      XElement>(index).Element(ns + "title").Value;
    getImage(imageID);
  }
}

The forward button handler is pretty much the same, except for its indexing:

The forward button handler is pretty much the same, except for its indexing:
if ((index + 1) < entries.Count<XElement>()) {
  index++;
  ...

You can now run the program by using the included Windows emulator. Select Windows Phone 7 Emulator from the target device menu on the Standard toolbar. Press F5 and the program is built and deployed to the emulator (see Figure 7).

image: Running the App in the Emulator

Figure 7 Running the App in the Emulator

Ready for Launch

This sample was relatively simple, but I hope it’s given you a rough idea of what the developer tools look like and how easy it is to pull together an application on Windows Phone. There are a lot of possibilities with Windows Phone 7, and you should take the time to explore them more.

What you’ve seen here is only a small introductory glimpse of what the application platform has to offer. As proof of that, consider the simple application I laid out. With one more button and roughly 12 lines of code, you could use the MediaLibrary class in the Microsoft.Xna.Framework.Media namespace to save a given photo to the media library (see msdn.microsoft.com/library/ff769549(v=VS.92)).

Yes, that’s right—you can use XNA APIs from within your Windows Phone Silverlight-based applications. Unfortunately, discussions about the interweaving of Silverlight and XNA APIs in apps, along with much more, will have to wait for a later date. So watch out for some deeper, more-targeted articles and check out the documentation and samples on MSDN at msdn.microsoft.com/library/ff402535(v=VS.92).


Joshua Partlow is a programming writer on the Windows Phone 7 team. He works on documenting the phone bring-up process, device driver development and application development for OEMs creating Windows Phones.

Thanks to the following technical expert for reviewing this article: Windows Phone 7 Team