Mobile Corner

Windows Phone Dev 101: A Get-Started Guide for Pros

Since the initial release of Windows Phone, Microsoft has been working to remove the obstacles to building applications for the platform. Recently, there's been a lot of focus on widening the base, with resources designed to make it easier for both inexperienced mobile developers (for example, the Windows Phone App Studio ) and for developers building for other platforms (such as the documentation for Porting Your App to Windows Phone). However, after reading some of the initial Getting Started guides and perhaps building some simple applications, many developers often wonder what to do next, or how to improve the quality of the applications they build. In this article you'll learn some of the tools, technologies and techniques to know if you want to develop Windows Phone applications for a living.

The starting point for all Windows Phone developers, new and experienced, is the Windows Phone Dev Center. The Dev Center has links to download the SDK, which includes all the tools needed to get started designing and developing for Windows Phone. It also contains the dashboard through which developers submit their applications for certification and publishing. Lastly, it contains links to further training material, code samples and partner resources.

Windows Phone Project Templates
When starting a new project in Visual Studio, you'll be given the option to pick from a number of different project templates. If you're new to the Windows Phone platform, it's worth reviewing these templates as a way to familiarize yourself with some of the core controls. For example, the Windows Phone Panorama App project template, highlighted in Figure 1, shows how to use the Panorama control.

[Click on image for larger view.] Figure 1. Windows Phone Project Templates

When starting development, you should use the Windows Phone App. This helps ensure there's no redundant code remaining in your application that was included in the project template. Even using the Windows Phone App template, there is some clean-up work to do before commencing development. Figure 2 shows the solution structure of a newly-created application.

[Click on image for larger view.] Figure 2. A Typical Windows Phone Project

Here's a list of some files you may want to remove to clean up your solution:

FlipCycleTileLarge.png By default, the primary tile doesn't support the wide tile. You can remove this file, or you can enable support for a wide tile in the WPAppManifest.xml.

IconicTileMediumLarge.png IconicTileSmall.png By default, the primary tile is set to use the flip tile template. These two files can be removed or you can switch to using the iconic file template. In this case, you can remove the FlipCycleTile*.png files.

ApplicationGrid.png This file can be used to overlay grid alignment squares over your application. This file can be removed. Alternatively, you can uncomment the Image element in the MainPage.xaml that references this file to see the overlay.

AppResources.resx LocalizedStrings.cs These two files provide support for multi-lingual applications. These files, and the in-code reference to them, can be removed if you don't wish to support multiple languages.

While you're tidying up, you might also want to consider moving MainPage.xaml and MainPage.xaml.cs out of the root folder. You can create a sub-folder called Pages or Views (depending on your naming preferences), and move these files into this folder. Since Windows Phone navigates between pages using their relative URIs, you'll need to update your application's starting page. While it's relatively trivial to do this in the WPAppManifest.xml file using the manifest editor (simply double-click the WMAppManifest.xml file), an alternative is to use a UriMapper to re-route page navigations. For example, the following UriMapper, defined in the App.xaml file, redirects page navigations to the corresponding page in the Pages folder:

<Application.Resources>
  <uriMapper:UriMapper x:Key="UriMapper">
    <uriMapper:UriMapping Uri="/{page}.xaml"
                          MappedUri="/Pages/{page}.xaml" />
  </uriMapper:UriMapper>
</Application.Resources>

You'll also need to assign this to the UriMapper property on the PhoneApplicationFrame created in the App.xaml.cs file:

RootFrame = new PhoneApplicationFrame{UriMapper = Resources["UriMapper"] as UriMapper};

This way, if you ever decide to restructure the solution, for example using Views instead of Pages as the folder name, you can change the UriMapper in one location, instead of in the URI of every page navigation.

Windows Phone Themes
Windows Phone users have a choice between a dark theme, where the background is black and the text is white, and a light theme, which is the reverse. They can also select a single accent color. As a developer, you need to be aware of this because it affects nearly every one of the built-in styles and templates. The default styles make use of colors and brushes defined by the operating system when an application launches, and are calculated based on the theme and accent color selected. For example, the PhoneBackgroundBrush is black in the dark theme and white in the light theme.

One requirement for Windows Phone store certification is functionality with all text visible in both dark and light themes, and with any accent color selected. This doesn't mean an application has to adapt to the different themes. In fact, there are a number of applications, particularly those that have a strong brand identity, where having to switch color schemes to support two different themes adds significantly to the cost of development; or worse, leads to a compromised design.

There are two options when it comes to trying to lock down an application's theme (you may even decide to combine these options). The first is to use the ThemeManager from Jeff Wilcocks via NuGet. After downloading the ThemeManager, you can lock down a particular theme on application startup by calling ToDarkTheme or ToLightTheme.

An alternative is to take a copy of all the standard colors, brushes, styles and templates contained in System.Windows.xaml and ThemeResources.xaml, located in the Design subfolder of the SDK. You'll need to rename these resources (for example, do a search for the word "Phone" and replace with the word "Default") so that they don't conflict with the actual standard resources injected by the platform at runtime. In your designs, make sure you use resources that start with Default instead of Phone.

Windows Phone Architecture
A lot of Windows Phone applications are relatively simple, composed of only a handful of pages. However, as the number of pages increases, it becomes more important to think about application architecture. For example, with a simple, two-page application, you might get away with interacting directly with the elements on the screen. This would become unwieldy on a project with 10 or more pages. Interacting directly with elements on the page also makes it harder to use the visual designer in either Visual Studio or Blend to design the page.

Figure 3 illustrates at a high level how to use data binding to separate the UI layer from the logic. The pattern Model-View-ViewModel (MVVM) is often used to describe the relationship between the UI layer, referred to as the View, and the logic and data.

[Click on image for larger view.] Figure 3. MVVM

The core element of MVVM is that attributes on elements that make up the View are data-bound to properties on the corresponding View Model. This sounds very complex, but it really isn't -- a View Model is simply a class that exposes properties that can be used to define what's presented on the View. For example, you might have a property called Contacts, which exposes a list of Contact entities. This can be data bound to a ListBox in order to present a list of contacts on the page.

Quite often, the distinction between the View Model, which you can think of as the current state of the View, and the Model is blurred as parts of the data model (e.g., entities retrieved from a service or used to persist data to a database) are data-bound to elements on the screen.

Figure 3 also shows that each View Model is associated with a Repository and a Navigation object. While MVVM outlines the use of data binding in order to control screen presentation, it provides no guidance as to where this data comes from. The Repository pattern provides a mechanism through which each of the View Models can retrieve and/or save data. You can think of it providing a level of abstraction away from making file system or service calls. As the Repository would typically be a singleton across the application, it can also provide a good mechanism for caching data in memory for use across multiple View Models.

One of the reasons MVVM works so well is that it provides a separation between an application's UI layer and its logic, including UI logic. This separation makes it possible to test a larger proportion of the logic -- for example, using a unit test. The downside is that there's no mechanism for code written in a View Model to navigate the user between pages. A simple way to overcome this limitation is to provide the View Model with an object which can facilitate the navigation. The following code defines an INavigation interface; each View Model, which will derive from BaseViewModel, has a property which will hold a reference to an implementation of the INavigation interface, permitting it to navigate to a new page. Then there's an implementation of the INavigation interface, which would be instantiated when the application starts and subsequently passed to each View Model that is created.

public interface INavigation
{
  void Navigate<TViewModel>();
}

public class BaseViewModel
{
  public INavigation Navigation { get; set; }   
}

public class Navigator:INavigation
{
  public void Navigate<TViewModel>()
  {
    var vmtype = typeof (TViewModel);
    var pagePath = "/" + vmtype.Name.Replace("ViewModel", "Page.xaml");
    (Application.Current.RootVisual as Frame).Navigate(new Uri(pagePath,UriKind.Relative));
  }
}

The last thing to point out is after separating your View from your Model and View Model classes, you can go one step further and place these classes in a separate class library. Furthermore, if you are looking to support multiple platforms -- for example, Windows Phone 7, Windows Phone 8, Windows 8, iOS or Android -- you can move these classes out to a Portable Class Library.

Windows Phone Project Management
Any developer who's worked on a project with multiple people will have most likely used a source code repository. While source control is a starting point, with the current advent of peer-to-peer code repositories, it appears that developers have forgotten that this isn't the end game. Good project management requires more than simply tracking what code has been written or the ability to roll back to a previous version. There's plenty of scope for countless articles on the different aspects of software development that can be assisted through the use of application lifecycle management (ALM) tools. If you aren't using a cloud-hosted source control system, which is able to associate work items/tasks/bugs with check-ins and is able to assist with planning out an iterative development schedule, you need to consider changing how you and/or your team operates.

If you're interested in learning more, check out the latest incarnation of Team Foundation Server (TFS). If you've had a prior bad experience with TFS, this is the right time to give it another go and sign up for free (at the time of writing). For the Git-inspired, you can now use Git as the source repository and still take advantage of all the features TFS has to offer.

Third-Party Frameworks and Libraries
The use of third-party frameworks and libraries often causes divides between developers that can't live without them and those who won't touch them. There are some great third-party frameworks such as MVVMLite and CaliburnMicro that countless developers use.

Even if you aren't partial to using a framework, you should consider using one or more third-party control libraries. One of the most heavily-used libraries is the Windows Phone Toolkit, available in both binary and source form via NuGet. It includes TiltEffect, which you should be using on tappable elements other than buttons, and the set of standard page transitions.

A side note on using page transitions in the Windows Phone Toolkit: Often, developers will add the transitions to each page within an application. While this is OK, it's a lot of duplicate XAML to add to each page. An alternative is to define a style, such as in the following code, at the Application level (e.g., as a Resource in App.xaml) and then reference it on each page (e.g., Style="{StaticResource TransitionPageStyle}"). You'll notice that a number of other properties are included in this style, simplifying the XAML used to define each page:

<Style x:Key="TransitionPageStyle"
           TargetType="phone:PhoneApplicationPage">
        <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilyNormal}" />
        <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeNormal}" />
        <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}" />
        <Setter Property="shell:SystemTray.IsVisible" Value="True" />
        <Setter Property="shell:SystemTray.Opacity" Value="0" />
        <Setter Property="SupportedOrientations" Value="Portrait" />
        <Setter Property="toolkit:TransitionService.NavigationInTransition">
            <Setter.Value>
                <toolkit:NavigationInTransition>
                    <toolkit:NavigationInTransition.Backward>
                        <toolkit:TurnstileTransition Mode="BackwardIn" />
                    </toolkit:NavigationInTransition.Backward>
                    <toolkit:NavigationInTransition.Forward>
                        <toolkit:TurnstileTransition Mode="ForwardIn" />
                    </toolkit:NavigationInTransition.Forward>
                </toolkit:NavigationInTransition>
            </Setter.Value>
        </Setter>
        <Setter Property="toolkit:TransitionService.NavigationOutTransition">
            <Setter.Value>
                <toolkit:NavigationOutTransition>
                    <toolkit:NavigationOutTransition.Backward>
                        <toolkit:TurnstileTransition Mode="BackwardOut" />
                    </toolkit:NavigationOutTransition.Backward>
                    <toolkit:NavigationOutTransition.Forward>
                        <toolkit:TurnstileTransition Mode="ForwardOut" />
                    </toolkit:NavigationOutTransition.Forward>
                </toolkit:NavigationOutTransition>
            </Setter.Value>
        </Setter>
    </Style>

There are a number of control libraries produced by Infragistics, Telerik, ComponentOne and SyncFusion, to name a few. The quality of the controls are continuing to increase, and it's worth looking at these options before reinventing the wheel by creating your own custom control.

Windows Phone Debugging
The Visual Studio debugging experience is best of breed. You can set breakpoints, add conditions, step through code and inspect variables, just like you would in building for the Web or a legacy desktop-style application. However, there are some aspects that can be a challenge, like inspecting the contents of Isolated Storage or running a performance analysis on your application. Luckily, there are tools that can assist with this. One such tool is the Windows Phone Power Tools, shown in Figure 4. Here you can see the results of running the profiler over an instance of an application. This can be used to isolate parts of an application that aren't running smoothly.

[Click on image for larger view.] Figure 4. Windows Phone Power Tools

With the Power Tools you can also inspect and even interact with the contents of Isolated Storage. Best of all, Power Tools works across both real devices, connected via USB, and the emulator.

Windows Phone Testing
Visual Studio 2012 now includes a Windows Phone Unit Test App project template. You can use this to create and run unit tests to test aspects of your application on either the emulator or a real device.

Currently, there is no support for running these test cases as part of the automated build via TFS in the cloud. However, if you separate your View Models into a portable class library, you can use a Unit Test Project to author test cases that can be invoked as part of a build. The results will automatically be collated by TFS, and are viewable alongside the build output.

Windows Phone Analytics
Built into the Windows Phone Store dashboard is the ability to view basic statistics about your application. This includes crash reports to isolate issues with your application.

In most cases you'll want to go beyond this and look at getting more granular analytics on application usage. To do this, consider using one of the many cloud-based analytics providers such as Omniture, Google Analytics and Flurry. All these providers have libraries for Windows Phone, making it easy to get up and running.

One word of advice: make sure you have a way to distinguish between development/testing accounts and your production data. This will help ensure you don't pollute your analytics data during development and testing.

Windows Phone Push Notifications
The concept of push notifications is relatively simple, and most developers have no issue understanding that there are three parties involved: the application running on a device, Microsoft-hosted push notification services and, of course, the sender of the notifications. As such, it's very easy for a developer to register the application for push notifications and establish the channel between the device and Microsoft. However, in order for the sender to be able to issue a notification, they first need to acquire the channel URI (a.k.a., the application identifier). At this point, most developers decide that push notifications are too much work and look for other mechanisms to update their live tiles or notify the user.

Luckily, there are a number of third-party offerings which can assist with tracking application instances and their corresponding channel URIs, and provide a mechanism through which the sender can either target individual devices or send out bulk messages. These providers include Windows Azure (Mobile Services and Notification Hubs), Buddy, Urban Airship and PushIO.

Windows Phone Authentication
When it comes to authentication , there's nothing a user hates more than having to create a new account and having to not only enter profile information, but also to come up with another unique password. Luckily, most application developers have started to use one of a number of existing credential providers such as Facebook, Twitter, Microsoft and Google. To use these providers within your application, you can either do the integration work yourself (most currently use some form of OAuth), use a third-party library (for example, the Facebook SDK) or use a cloud-based service (for example, Windows Azure Mobile Services provides authentication across multiple providers out of the box).

I hope this article whetted your appetite to learn more about becoming a professional Windows Phone developer. To learn more about any specific area, the best place to start is the Windows Phone Dev Center: Follow the links to the reference materials that can be accessed from there.

About the Author

Nick Randolph runs Built to Roam, a consulting company that specializes in training, mentoring and assisting other companies build mobile applications. With a heritage in rich client applications for both the desktop and a variety of mobile platforms, Nick currently presents, writes and educates on the Windows Phone platform.

comments powered by Disqus

Featured

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube