Deconstructing a “Windows Phone Application” Visual Studio Project

0
187

When you create a new “Windows Phone Application” project in Visual Studio, you get a complete app that you can instantly compile into a .xap file and deploy to the emulator or a physical phone. The app doesn’t actually do anything other than display some text on the screen, but it sets up a lot of infrastructure that would be difficult and tedious to
create from scratch. Before creating the Tally app, let’s understand the main pieces of any new “Windows Phone Application” project:

  • The application manifest
  • Images
  • XAML code: MainPage.xaml and App.xaml
  • C# code: MainPage.xaml.cs, App.xaml.cs, and AssemblyInfo.cs

Visual Studio provides a few types of Windows Phone projects for more complex applications, based on the control that populates the main screen: a databound (list) application, a panorama application, and a pivot application. Almost all of the applications in this book were created from the basic “Windows Phone Application” project, as it’s relatively easy to manually add a databound list, a panorama control, or a pivot control to a project without having to start with a specialized project type.

The Application Manifest

The file called WMAppManifest.xml (where WM oddly stands for the outdated “Windows Mobile” term) is an application manifest. It describes your app to the operating system—its name, what it looks like, how it starts, what it’s allowed to do, and more. Listing 1.1 shows what Visual Studio generates inside this file when you create a new project and name it “Tally.” You can find this file in your project’s “Properties” folder.

.xap Files
.xap files, introduced by Silverlight but also used by XNA apps for Windows Phone, are just .zip files. If you rename a .xap file and give it a .zip extension, you can inspect its contents just like any .zip file.A .xap file for a Windows Phone app contains several files: compiled DLL(s), manifests, images, and potentially other assets used by your app that aren’t embedded into a DLL, such as videos or data files.

LISTING 1.1 WMAppManifest.xml—The Initial Application Manifest for the Tally Project

[code]

<?xml version=”1.0” encoding=”utf-8”?>
<Deployment xmlns=”http://schemas.microsoft.com/windowsphone/2009/deployment”
AppPlatformVersion=”7.0”>
<App xmlns=”” ProductID=”{2f711986-cfb4-40d3-9b7d-64aa37faf338}” Title=”Tally”
RuntimeType=”Silverlight” Version=”1.0.0.0” Genre=”apps.normal”
Author=”Tally author” Description=”Sample description” Publisher=”Tally”>
<IconPath IsRelative=”true” IsResource=”false”>ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name=”ID_CAP_GAMERSERVICES”/>
<Capability Name=”ID_CAP_IDENTITY_DEVICE”/>
<Capability Name=”ID_CAP_IDENTITY_USER”/>
<Capability Name=”ID_CAP_LOCATION”/>
<Capability Name=”ID_CAP_MEDIALIB”/>
<Capability Name=”ID_CAP_MICROPHONE”/>
<Capability Name=”ID_CAP_NETWORKING”/>
<Capability Name=”ID_CAP_PHONEDIALER”/>
<Capability Name=”ID_CAP_PUSH_NOTIFICATION”/>
<Capability Name=”ID_CAP_SENSORS”/>
<Capability Name=”ID_CAP_WEBBROWSERCOMPONENT”/>
</Capabilities>
<Tasks>
<DefaultTask Name =”_default” NavigationPage=”MainPage.xaml”/>
</Tasks>
<Tokens>
<PrimaryToken TokenID=”TallyToken” TaskName=”_default”>
<TemplateType5>
<BackgroundImageURI IsRelative=”true” IsResource=”false”>
Background.png
</BackgroundImageURI>
<Count>0</Count>
<Title>Tally</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
</App>
</Deployment>

[/code]

The application manifest is a strange file, because most of it gets overwritten by the Windows Phone Marketplace certification process. Therefore, the application manifest inside your app that can be downloaded from the marketplace will be different than the manifest inside your private copy of your app that you manually deploy.

The App element contains a ProductID Globally Unique Identifier (GUID) that uniquely identifies your app, and a RuntimeType value that indicates this is a Silverlight app rather than an XNA app. The value for Title is displayed with your installed app (either in the normal app list or the Games hub). The other four attributes are only applicable for listing your app in the marketplace, but these values (as well as Title) get overwritten by the data you enter on the marketplace website (the App Hub).

The Genre value affects where your app gets installed on the phone. If you use apps.normal, it gets placed in the normal app list. If you instead use apps.games, it gets placed inside the Games hub. (Yes, Silverlight apps can do this; the Games hub is not limited to apps created with XNA.) You must choose one of the two locations; your app cannot be installed in both. Leaving this as apps.normal is much more convenient at development-time, because the emulator does not expose
the Games hub. When submitting an app to the marketplace, this value also gets overwritten by the category you choose on the website.

The text overlaid on a tile is defined by the Title element inside the PrimaryToken element.This means that you can use something different than your app name. Although it is best to use your app name to avoid user confusion, shortening it is a good idea when your app name is too long for the tile.

You can leave the title element empty to produce a text-free tile (as done by the Facebook app), although the marketplace might reject such a submission unless you provide justification.The marketplace wants to ensure that users are not confused about which tile belongs to which app.

The IconPath element points to your icon image file, the Tasks element points to the main Silverlight page where your app begins running, and the Tokens element contains information about your tile (seen by users who pin
your app to their start screen). These parts are rarely changed, but these values are preserved when your app is published in the marketplace.

The Other Manifest
Visual Studio projects contain a second manifest in the “Properties” folder called AppManifest.xml.This is needed by Silverlight infrastructure, but you do not need to touch this file.

Capabilities

The most interesting part of WMAppManifest.xml is the list of capabilities inside the Capabilities element. These are special permissions for actions that users might not want certain apps to perform, whether for privacy concerns or concerns about data usage charges. The Visual Studio-generated manifest requests all available capabilities. You can
restrict this list to test what happens when your app tries to perform an action for which it does not have permission, but that’s a moot point. With one exception described later, the marketplace certification process automatically detects what capabilities your app needs and overwrites your list in the application manifest with the minimal set of required capabilities.

Once your app is running, you do not need to check if you’ve been granted any of your requested  capabilities. (There’s not even an API to do so!) If your app is running, then all requested capabilities have
been granted.They cannot be revoked.

In the marketplace, users are told what capabilities your app will be granted before they decide whether to download it. Each capability has a user-friendly name, so ID_CAP_LOCATION in Listing 1.1 is called “location services” in the marketplace, and ID_CAP_NETWORKING is called “data connection.” The user approval is an implicit part of the action of downloading your app. The location services capability, however, requires explicit consent by the user. The marketplace prompts users to agree to the sending of location data before they download the app.

ID_CAP_NETWORKING is the one capability you must manually request!
There’s one huge exception to the idea that you can let the marketplace certification process worry about the capabilities list for you. Although it can figure out everything else, marketplace certification cannot reliably figure out whether your app needs the phone’s networking capability. If ID_CAP_NETWORKING is present in your manifest, it will be granted even if you don’t need it, and if it is not present, it might not be granted even if you do need it!

The key point is that there’s no need for your app to obtain permission from the user for any capability, nor do you have
to worry about whether your app has been granted certain capabilities. Just remember:

  • If your app is running, it has been granted all the capabilities listed in its manifest.
  • If your app has been downloaded from the marketplace, its manifest automatically lists all the capabilities it needs and no more (except for ID_CAP_NETWORKING, as described in the warning sidebar).

You want to restrict the set of capabilities requested by your app, because it is a competitive advantage. For example, users might decide not to buy your Tip Calculator app if it wants permission to use the phone’s data connection! Therefore, be sure to remove the ID_CAP_NETWORKING capability if you don’t need it.Otherwise, your marketplace listing will say that your app “requires access to your data connection.”

Although ID_CAP_NETWORKING is currently the only capability to be careful about, the best practice is to use the Windows Phone Capability Detection Tool that ships with the Windows Phone Developer Tools starting with the October 2010 release.This runs the same automatic capability detection done by the marketplace certification process and then tells you what to put in your manifest. Before submitting your app to the marketplace, you should replace your requested capabilities with this minimal set (and, if appropriate, ignore the ID_CAP_NETWORKING capability that is usually falsely reported by the tool).

 

Why can I no longer debug my app on a physical phone after updating its capabilities?
That pesky ID_CAP_NETWORKING capability is to blame. Without ID_CAP_NETWORKING, the debugger is unable to communicate with the attached phone. So keep it there during development, but be sure to remember to remove this capability before submitting your app to the marketplace if your app does not require it!

 

How can I write a game that uses Xbox LIVE features?
Some capabilities are for specific developers such as mobile operators and phone manufacturers; not for mere mortals like you and me. ID_CAP_GAMERSERVICES is one such capability that does not work for everyone. It grants access to Xbox LIVE APIs, but only to games approved by Microsoft.You can peruse the Xbox LIVE functionality by looking at the Microsoft.Xna. Framework.GamerServices assembly with Visual Studio’s Object Browser, if you want to know what you’re missing.Most of the functionality inside throws a NotSupportedException unless you are a registered Xbox LIVE developer and have gone through a specific process to enable your game for Xbox LIVE.

If you believe you’ve developed a game worthy of the ID_CAP_GAMERSERVICES capability (so you can integrate with Xbox LIVE achievements, leaderboards, and more), you can email [email protected] for more information. Just keep in mind that the standards are very high! Look at the current set of Xbox LIVE games in the marketplace to get an idea of the kind of games that have been approved.

Of course, anybody can write a great game for Windows Phone without the ID_CAP_GAMERSERVICES capability, and they can do so in XNA or Silverlight.Volume II of this book series shows plenty of examples of Silverlight games.You’ll even see how to take advantage of Xbox LIVE avatar images without needing any kind of special access or arrangement with Microsoft.

 

Images

The project generated by Visual Studio includes three images, shown in Figure 1.1:

  • ApplicationIcon.png—The main icon, used wherever the app is installed. For normal apps (placed in the phone’s app list), the icon should be 62×62 pixels to avoid scaling. For games (placed in the Games hub), the icon should instead be 173×173 pixels.
  • Background.png—The tile icon (173×173) used when the user pins the application to the phone’s start screen, whether the app came from the app list or the Games hub. This poorly named file is named as such because it’s technically the background for the tile. The Title in the application manifest is automatically overlaid on the
    tile’s bottom-left corner, so care must be taken in the image to leave room for the text.
  • SplashScreenImage.jpg—The splash screen (480×800) shown while the application is loading.
The three standard images included in a Visual Studio “Windows Phone Application” project.
FIGURE 1.1 The three standard images included in a Visual Studio “Windows Phone Application” project.

You can change the name and location of the first two images, and they can be either JPEG or PNG files. Just remember to update your application manifest accordingly.

To create an icon that fits in with the Windows Phone built-in apps, it should usually have a transparent background and the drawing inside should:

  • be completely white
  • be composed of simple geometric shapes
  • reuse iconography already used by the phone if possible
  • use an understandable real-world metaphor

The drawing for the 62×62 icon should generally have a 12-pixel margin around all sides. (In other words, the actual content should fit in a 38×38 box centered in the image.) The drawing for the 173×173 icon should generally fit in a 73×73 almost-centered box. It should be nudged 3 pixels higher than center, giving a 47-pixel margin on top, 53-pixel margin on bottom, and 50-pixel margin on the sides.

For drawings significantly longer in one dimension, you may want to leave less of a margin. In  most cases, the drawing inside Background.png should be the same as the one inApplicationIcon.png, just larger. As with all user interface guidelines, games are generally exempt from these guidelines.

Creating these types of images requires some practice and patience.You’ll want to use tools such as PAINT.NET, mentioned in this book’s “Introduction” section. A few of the characters from the Wingdings and Webdings fonts can even be used to help create a decent icon!

These are not strict guidelines or even official guidelines from Microsoft, nor does it match what the initial image files contain; it just tends to look right for most cases.Of course, apps with their own strong branding (such as the Facebook, eBay, and iMDb apps) usually do not follow these guidelines, as being consistent with their own identity outweighs being consistent with Windows Phone. In addition, it often makes sense to deviate from this style if you want your app to stand out in the marketplace.

 

How can my icon get the user’s theme accent color as its background, as with the built-in apps?

Each tile icon is rendered on top of an accent-colored square when pinned to Start, so using a transparent background color in your PNG file is all you need to do.Unfortunately, each thirdparty app icon in the app list is always rendered on top of a dark grey square, so there’s no way to get the same effect in the app list. Nothing prevents you from using one of the standard theme colors as a hard-coded background inside your image file, but you shouldn’t do this unless it happens to be a color associated with your brand.That’s because it will never change and therefore look out-of-place to users who switch their accent color.

 

Icons for your marketplace listing have different guidelines than your app’s real icons!

Whereas using a transparent background is encouraged for your tile icon, it should be avoided for the separate set of icons you upload to the marketplace.The phone’s Marketplace app renders icons on black squares, which looks odd under the dark theme when the icon has transparency. Even worse, the marketplace section of the Zune program leaves its default white background underneath the icon. For typical Windows Phone app icons, the result is a completely invisible icon due to the white-on-white effect!

To avoid this, you must choose a background color for your marketplace icons. It’s a good idea to use this same background for your app icon, even if your tile icon uses transparency to fit in with the user’s theme.

 

Leveraging the built-in splash screen support by supplying the SplashScreenImage.jpg file can be useful for boosting the perceived load time of your app. A desirable approach is to make the image look like what your app will look like once fully loaded, perhaps with disabled-looking controls and without text.This gives the appearance of your app being instantly “there,” but not fully loaded.The text is normally omitted from the image because even if you localize your app for multiple languages, you can still only have the single image file per app. Unfortunately, due to the single-file nature of the splash screen support, it’s only worthwhile for
apps that use hard-coded colors and support only a single orientation.That’s because a typical Windows Phone app looks radically different under the dark versus light theme (or in a portrait versus landscape orientation), so no single image can provide a seamless experience for one case without being jarring for the other cases. In addition, I’m a big believer in making apps feel the same as the built-in apps unless there’s a good reason not to, and none of the built-in apps use a perceivable splash screen.

The good news is that the phone already produces a built-in animated “Loading…” or “Resuming…” user interface when an app is launched or reactivated. If yours is not fast to load, I’d recommend addressing the core issue (such as delaying computationally expensive work) rather than using a sub-standard splash screen. In this book, none of the apps use a splash screen.To remove the splash screen from your app, simply remove SplashScreenImage.jpg from your project.

Many apps in the marketplace (such as the Facebook and Twitter apps) do use a splash screen, but not to improve the perceived loading time.They simply use it to help customize the loading process with their own branding.

 

 

The icon and splash screen images must have a build action set to Content!

If you replace any of the three image files with your own, be sure to set each file’s Build Action in Visual Studio to Content, rather than the default Resource, as shown in Figure 1.2.This correctly places the files directly inside your .xap file rather than embedded inside your DLL. Note that the value of Copy to Output Directory does not matter. Even if the file is not copied to the output directory, it still gets copied to the correct place inside the resultant .xap file.

The three image files discussed in this section must be given a build action of Content in Visual Studio’s Properties window.
FIGURE 1.2 The three image files discussed in this section must be given a build action of Content in Visual Studio’s Properties window.

 

MainPage.xaml

Every app consists of one or more pages. New projects are given a single page called MainPage. This page defines what the user sees once your app has loaded. It is implemented across two files: MainPage.xaml contains the user interface, and MainPage.xaml.cs contains the logic, often called the code-behind. Listing 1.2 shows the initial contents of MainPage.xaml, and Figure 1.3 shows what this XAML produces when you run the app.

Remember that MainPage.xaml is referenced in WMAppManifest.xml!
If you want to rename this file, you must also change its name inside your application manifest; otherwise your app will stop working.

LISTING 1.2 MainPage.xaml—The Initial Markup for the App’s Main Page

[code]

<phone:PhoneApplicationPage
x:Class=”Tally.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:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
FontFamily=”{StaticResource PhoneFontFamilyNormal}”
FontSize=”{StaticResource PhoneFontSizeNormal}”
Foreground=”{StaticResource PhoneForegroundBrush}”
SupportedOrientations=”Portrait” Orientation=”Portrait”
mc:Ignorable=”d” d:DesignWidth=”480” d:DesignHeight=”768”
shell:SystemTray.IsVisible=”True”>
<!–LayoutRoot contains the root grid where all other page content is placed–>
<Grid x:Name=”LayoutRoot” Background=”Transparent”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto”/>
<RowDefinition Height=”*”/>
</Grid.RowDefinitions>
<!–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=”MY APPLICATION”
Style=”{StaticResource PhoneTextNormalStyle}”/>
<TextBlock x:Name=”PageTitle” Text=”page name” Margin=”-3,-8,0,0”
Style=”{StaticResource PhoneTextTitle1Style}”/>
</StackPanel>
<!–ContentPanel – place additional content here–>
<Grid x:Name=”ContentGrid” Grid.Row=”1”>
</Grid>
</Grid>
<!– Sample code showing usage of ApplicationBar

–>
</phone:PhoneApplicationPage>

[/code]

At a quick glance, this file tells us:

  • This is a class called MainPage (in the Tally namespace) that derives from the PhoneApplicationPage control.
  • It is marked to only support the portrait (vertical) orientation.
  • It contains two text blocks with boilerplate text that are meant to be the application name and an appropriate page title.
  • The page leverages Grid and StackPanel controls to arrange the current text blocks, and additional content is meant to be placed in the grid named ContentGrid.
  • For such a simple page, there are a lot of things in here!

We’ll examine the following two aspects of this file more deeply:

  • The XML namespaces used at the top of the file
  • Phone theme resources, referenced as “{StaticResource XXX}”
The initial MainPage.xaml.
FIGURE 1.3 The initial MainPage.xaml.

XML Namespaces

MainPage.xaml contains most of the XML namespaces you’ll see in this book. Table 1.1 explains them. Although some look like URLs that you can view in a Web browser, they are not. They all map to .NET namespaces in specific assemblies.

The Common Namespaces in Windows Phone XAML Files
TABLE 1.1 The Common Namespaces in Windows Phone XAML Files
Continued
TABLE 1.1 Continued

The first three namespaces are almost always used in Windows Phone apps. The shell namespace is only needed when a page uses an application bar via the ApplicationBar class, or when it enables the status bar by setting  SystemTray.IsVisible to True. The status bar is the top area of the phone that displays the time and, based on various
factors, signal strength, battery charge, and more. As a developer, you can’t do anything with the status bar other than show or hide it.

Phone Theme Resources

Rather than hardcoding fonts, font sizes, and colors, MainPage.xaml makes use of several phone-specific resources using
StaticResource syntax. Windows Phone defines several resources to make it easy for apps to get a look-and-feel consistent with guidelines and with the user’s chosen theme. Appendix C, “Theme Resources Reference,” lists them all and demonstrates what they look like for both user themes (light and dark). These resources not only contain individual colors, brushes, fonts, font sizes, and thicknesses (for borders and margins/padding) but also contain a bunch of styles for text blocks that package individual resources together.

The resources used by this initial page are

  • PhoneFontFamilyNormal—Segoe WP
  • PhoneFontSizeNormal—20 px (15 pt)
  • PhoneForegroundBrush—A solid color brush that is white in the dark theme and black in the light theme
  • PhoneTextNormalStyle—The previous three resources combined: a FontFamily of PhoneFontFamilyNormal, FontSize of PhoneFontSizeNormal, and Foreground of PhoneForegroundBrush
  • PhoneTextTitle1Style—A FontFamily of PhoneFontFamilySemiLight (Segoe WP Semilight), FontSize of  PhoneFontSizeExtraExtraLarge (72 px, which is 54 pt), and Foreground of PhoneForegroundBrush.
The initial MainPage.xaml, shown under the light theme.
FIGURE 1.4 The initial MainPage.xaml, shown
under the light theme.

This explains how Listing 1.2 produces the result from Figure 1.3 when the user’s theme is dark. Figure 1.4 shows the same page when the phone uses the light theme.

MainPage.xaml.cs

Listing 1.3 shows the initial contents of MainPage.xaml.cs, the code-behind file for MainPage.xaml. Because this app does not yet do anything, it only contains the required call to InitializeComponent that constructs the page with all the visuals defined in the XAML file. The class is marked with the partial keyword because its definition is shared with a hidden C# file that gets generated when the XAML file is compiled.

LISTING 1.3 MainPage.xaml.cs—The Initial Code-Behind for the App’s Main Page

[code]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace Tally
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
}
}

[/code]

App.xaml and App.xaml.cs

App.xaml is a special XAML file that doesn’t define any visuals, but rather defines an App class that can handle application-level tasks. Usually the only reason to touch this XAML file is to place new application-wide resources, such as custom styles, inside its Application.Resources collection.

AssemblyInfo.cs

This file is not worth showing in this book. It contains a bunch of attributes where you can put a title, description, company name, copyright, and so on, that get compiled into your assembly. But setting these is unnecessary because all of the information used by the marketplace is separately managed. Still, the AssemblyVersion and AssemblyFileVersion
attributes, typically set to the same value, can be useful for you to keep track of distinct versions of your application:

[code]

[assembly: AssemblyVersion(“1.0.0.0”)]
[assembly: AssemblyFileVersion(“1.0.0.0”)]

[/code]

By using *-syntax, such as “1.0.*”, you can even let the version number auto-increment every time you rebuild your app.