Exercise 1: Creating Windows Phone Applications with Microsoft Visual Studio 2010 Express for Windows Phone

In this exercise, you will create, test, deploy and run your first Windows Phone application. You will learn how to use the Windows Phone Developer Tools including the free Microsoft Visual Studio 2010 Express for Windows Phone IDE, and the Windows Phone Emulator.

The tasks include creating a new Silverlight for Windows Phone project, designing the start page of the application, and providing some basic error handling. You will also run the application on your workstation using the Windows Phone Emulator.

Note:
The steps in this hands-on lab illustrate procedures using Microsoft Visual Studio 2010 Express for Windows Phone, but they are equally applicable to Microsoft Visual Studio 2010 with the Windows Phone Developer Tools. Instructions that refer generically to Visual Studio apply to both products.

Task 1 – Creating a Windows Phone Application Project in Visual Studio

In this task, you use a predefined template in Microsoft Visual Studio 2010 Express for Windows Phone to create a Silverlight for Windows Phone Application project that you can use as the starting point for your first application.

  1. Open Microsoft Visual Studio 2010 Express for Windows Phone from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Studio 2010 Express for Windows Phone. Alternatively, if you are using Visual Studio 2010, open Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
  2. In the File menu, choose New Project.
  3. In the New Project dialog, select the Silverlight for Windows Phone category in the list of installed templates, and there the Windows Phone Application template. Set the name to WindowsPhonePuzzle and the location to Ex1-CreatingWP7Apps in the Source folder of the lab. Change the solution name to Begin, and then click OK.

    Note:
    If you completed the Hello Phone lab in the training kit, you will already be familiar with the following material and may wish to go directly to Task 3 in this exercise after creating the begin solution.

  4. In Solution Explorer, review the structure of the solution generated by the Windows Phone Application template. Any Visual Studio solution is a container for related projects; in this case, it contains a single Silverlight for Windows Phone project named WindowsPhonePuzzle.

    Figure 1

    Solution Explorer showing the WindowsPhonePuzzle application

    The WindowsPhonePuzzle project contains the following items:

    Item

    Description

    App.xaml / App.xaml.cs

    Defines the entry point of the application, initializes application-scoped resources, and displays the application user interface

    MainPage.xaml/MainPage.xaml.cs

    Defines a page with the user interface of the application

    ApplicationIcon.png

    An image file with an icon that represents the application icon in the phone’s application list

    Background.png

    An image file with an icon that represents the application icon in the start screen

    SplashScreenImage.jpg

    This is the image that will first be displayed when the application launches. The splash screen gives the user immediate feedback that the application is launching and will remain displayed until the navigation to the first page has been completed. Your splash screen can look similar to your first page in order to give the appearance that the application is loading quickly.

    Properties\AppManifest.xml

    An application manifest file required to generate the application package

    Properties\AssemblyInfo.cs

    Contains the name and version metadata that is embedded into the generated assembly

    Properties\WMAppManifest.xml

    A manifest file that includes specific metadata related to a Windows Phone Silverlight application, including specific features available only for Silverlight for Windows Phone

    References folder

    List of libraries (assemblies) that provide services and functionality that the application requires to work

  5. First, right-click App.xaml in Solution Explorer and choose View Designer. Notice that the file contains XAML markup with an Application root element and inside it an Application.Resources section. Herein you can define application-level resources such as colors, brushes and style objects used throughout the application.

    The XAML code also initializes the ApplicationLifetimeObjects property of the Application to create a PhoneApplicationService object. The PhoneApplicationService class provides access to various aspects of the application’s lifetime. This includes management of the application’s idle behavior and management of the application’s state when it becomes active or inactive.

    Figure 2

    Default App.xaml file generated by the Windows Phone application template

    Note:
    The App.xaml file, together with its code-behind file App.xaml.cs, defines an instance of the Application class. This class encapsulates a Silverlight for Windows Phone application and provides its entry point.

  6. Now, right-click App.xaml in Solution Explorer and choose View Code to open its code-behind file. Notice that, in its constructor, this Application-derived class already subscribes a handler for the UnhandledException event. Later in the lab, you will update the template-generated handler to navigate to an error page and display information about the exception.

    The RootFrame property in the Application class identifies the starting page of the application. All Windows Phone applications have a single top-level container element whose data type is PhoneApplicationFrame. The frame hosts one or more PhoneApplicationPage elements that present content for the application. It also handles navigation between pages.

    Note:
    The Application class, generated by the Silverlight for Windows Phone application template, also includes handlers for the Launching and Closing events, among others.
  7. The generated project includes a default document that contains XAML markup that defines the main UI of the application. To view this file in the designer, double-click MainPage.xaml in Solution Explorer.

    Figure 3

    XAML designer showing the main user interface of the application

    Note:
    Extensible Application Markup Language (XAML) is a declarative language. You can create visible UI elements in the declarative XAML markup. You can then use a separate code-behind file to respond to events and manipulate the objects you declared in XAML. An XML-based declarative language is very intuitive for creating interfaces from prototype to production, especially for people with a background in Web design and technologies.
  8. A Windows Phone application typically takes advantage of services provided by the underlying platform or by other libraries. To use this functionality, the application needs to reference the corresponding assemblies that implement these services. To display the assemblies referenced by the project, expand the References node in Solution Explorer and examine the list. It contains regular Silverlight assemblies as well as assemblies specific to the Windows Phone platform.
  9. The project’s Properties window is the only way to edit the WP manifest file, as shown in the following figure. To open this window, right-click the WindowsPhonePuzzle project in Solution Explorer and select Properties.

    Figure 4

    Project properties window

    Note:
    The Windows Phone project properties window allows you to modify some phone-specific properties. These properties relate to the deployment and appearance of the application on the device. The parameters are stored in the WMAppManifest.xml file. Even if you try to change the XML file manually, your changes will be overwritten each time you change and save your project settings via this dialog.

Task 2 – Building and Testing the Application in the Windows Phone Emulator

At the moment, the application does not do much, but it is ready for its first test run. In this task, you build the application, deploy it to the Windows Phone Emulator, and then execute it to understand the typical development cycle.

  1. In the Debug menu, point to Windows and select Output or press CTRL + W, O to open the Output window.
  2. Select Build Solution in the Debug menu.

    Note:
    Visual Studio 2010 Express for Windows Phone: Press the SHIFT + F6 key combination to compile the projects in the solution.

    Visual Studio 2010: Press CTRL + SHIFT + B to compile the projects in the solution.

  3. Observe the Output window and review any trace messages generated during the build process, including the final message with its outcome.

    Figure 5

    Building the application in Visual Studio

  4. You should not observe any errors at this stage; but, if the project were to contain compilation errors, these would appear in the Output window. To deal with these kinds of errors, you can take advantage of the Error List window.
  5. Verify that the target of the deployment is the Windows Phone Emulator. To do this, ensure that Windows Phone 7 Emulator is selected in the Select Target drop down next to the Start Debugging button on the toolbar.

    Figure 6

    Choosing the target device to deploy the application

    Note:
    When you deploy your application from Visual Studio, you have the option to deploy it to a real device or to the Windows Phone Emulator.

  6. Press F5 to launch the application in the Windows Phone Emulator. Notice that a device emulator window appears and there is a pause while Visual Studio sets up the emulator environment and deploys the application image.

    Figure 7

    Deploying an application image to the Windows Phone Emulator

  7. Once it is ready, the emulator shows the Start page and shortly thereafter, your application appears in the emulator window.

    Figure 8

    Running the application in the Windows Phone Emulator

  8. Until you create the user interface and program the application logic, there is very little that you can do with the application. Press SHIFT + F5 or click the Stop button in the toolbar to detach the debugger and end the debugging session. Do not close the emulator window.
    Note:
    Tip: When you start a debugging session, it takes a perceptible amount of time to set up the emulator environment and launch the application. To streamline your debugging experience, avoid closing the emulator while you work with the source code in Visual Studio. Once the emulator is running, it takes very little time to stop the current session, edit the source code, and then build and deploy a new image of your application to start a new debugging session.

Task 3 – Creating the UI for the Home Page

In this task, you create the user interface for the home page of the application. The page displays a splash screen. It contains an image that represents the application and a button that dismisses the splash screen and navigates to the game page.

  1. First, create a folder in the project to contain the images used by the application. In Solution Explorer, right-click the WindowsPhonePuzzle project node, point to Add and select New Folder. Change the name of the folder to Assets.

    Figure 9

    Solution Explorer showing the new Assets folder

  2. Now, add the images used by the application to the project. In Solution Explorer, right-click Assets, point to Add and select Existing Item. In the Add Existing Item dialog, browse to Assets in the Source folder of the lab, then, while holding down the CTRL key, click SplashImage.jpg and Puzzle.jpg to select both files and click Add.

    Note:
    In Visual Studio, you can add resource files to your Silverlight for Windows Phone project and then configure them for deployment by setting their Build Action values. Each added image is included in the project with a build action set to Resource, which will embed the file in the project assembly.

  3. Open in Solution Explorer, the file MainPage.xaml, this is the main page of the application.
  4. In the Design view, select the TextBlock named ApplicationTitle and press F4. In the Properties window, change the value of the Text property—located under Common when sorting properties by category—to the string ‘WINDOWS PHONE PUZZLE’.

    Figure 10

    Configuring UI elements in the Properties window

  5. Next, select the TextBlock named PageTitle and replace its Text property with the string ‘start.
  6. In the XAML markup generated by the default Windows Phone application template, find the Grid container element named LayoutRoot. Its purpose is to arrange the elements on the page. Notice that the root Grid element contains other nested elements with each one assigned to a different row of the outer grid by defining a Grid.Row property. Locate the Grid element named ContentPanel assigned to row1, and insert the following XAML markup inside it.

    XAML

    <Grid x:Name="LayoutRoot" Background="Transparent"> ... <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height=".8*" /> <RowDefinition Height=".2*" /> </Grid.RowDefinitions> <Image Source="Assets/SplashImage.jpg" VerticalAlignment="Center" HorizontalAlignment="Center" Width="471" Height="492" /> <Button Content="START!" Name="StartButton" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" /> </Grid> </Grid>

  7. Switch the editor mode to Design view. To change to Design view and maximize the viewing area, double-click the Design tab () on the right edge of the designer window.
  8. Create an event handler for the button. To do this, double-click the button labeled START on the designer surface. This action creates a subscription to the Click event handler and opens the code-behind file with the cursor positioned on the StartButton_Click event handler method. Paste the following (highlighted) code into the body of this method.

    C#

    private void StartButton_Click(object sender, RoutedEventArgs e) { // navigate this.NavigationService.Navigate(new Uri("/PuzzlePage.xaml", UriKind.Relative)); }

    Note:
    The PhoneApplicationPage class provides methods and properties to navigate to pages through its NavigationService property. You can call the Navigate method of the NavigationService and pass the URI for the page as a parameter.

Task 4 – Managing Errors in the Application

In this task, you update the application to display an error page whenever an unhandled exception occurs. To manage unhandled exceptions, you first add a new page to the application to display information about the error. Then, you create an event handler for the UnhandledException event. This event is raised whenever an exception in the application is not caught. In the handler, you navigate to the error page passing it information about the exception.

Note:
Regardless of the presence of an unhandled exception handler, your application should include proper handling for any exceptions that you can deal with.

  1. First, add a new page to the project. In Solution Explorer, right-click the WindowsPhonePuzzle project node, point to Add and select New Item. In the Add New Item dialog, select Windows Phone Portrait Page from the list of templates, set the name to ErrorPage.xaml and then click Add.
  2. In ErrorPage.xaml, locate the LayoutRootGrid element and replace its child controls with the blue-highlighted XAML markup. This XAML defines an application title and a page title, both named error. It also defines a TextBlock object designated as x:Name="ErrorText" that will hold the error text from any future exceptions.

    XAML

    <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="WINDOWS PHONE PUZZLE" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="error" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1"> <Border BorderBrush="White"> <TextBlock x:Name="ErrorText" Style="{StaticResource PhoneTextSmallStyle}" TextWrapping="Wrap" /> </Border> </Grid> </Grid>

  3. Now, press F7 to open the code-behind file of the new page or, alternatively, right-click ErrorPage.xaml in Solution Explorer and select View Code. Insert the following namespace directive at the top of the file.

    C#

    using System.Windows.Navigation;

  4. Then, insert the following code snippet into the ErrorPage class at the highlighted location. This sets up an Exception object that is hooked up to the ErrorText.Text upon navigating to the page.

    C#

    public partial class ErrorPage : PhoneApplicationPage { public ErrorPage() { InitializeComponent(); } public static Exception Exception; // Executes when the user navigates to this page. protected override void OnNavigatedTo(NavigationEventArgs e) { ErrorText.Text = Exception.ToString(); } }

  5. In Solution Explorer, right-click App.xaml and select View Code to open the code-behind class of the Application class.
  6. In the App class, locate the Application_UnhandledException event handler and replace the body of this method with the following (highlighted) code.

    C#

    // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break in the debugger System.Diagnostics.Debugger.Break(); } e.Handled = true; ErrorPage.Exception = e.ExceptionObject; (RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source = new Uri("/ErrorPage.xaml", UriKind.Relative); }

    Note:
    The Application_UnhandledException is a safety net where all unhandled exceptions of your application end up. The event handler above sets the Handled property to true to prevent additional processing of the exception after the UnhandledException handler completes. It then saves the information about the unhandled exception in a static member of the ErrorPage class and sets the Source property of the frame to show the error page. Whenever you set the Source property to a value that is different from the displayed content, the frame navigates to the new content. When you navigate to the error page, it retrieves the exception object’s text value (Exception.ToString()) and displays it on the page. This will be very useful once you start debugging your application on a real device.

Task 5 – Verifying

In this task, you build the application, deploy it to the Windows Phone Emulator, and then execute it to verify that you performed the previous steps correctly.

  1. In Visual Studio, press CTRL +F5 to deploy the application to the Windows Phone Emulator and run it without debugging. Wait for the application to launch and show its main page. It should display the splash screen.

    Figure 11

    Splash screen for the application running in the emulator

  2. Click the START button. Notice that the application shows the unhandled exception error page that you defined earlier. Bear in mind that this is expected because the handler for the button navigates to the PuzzlePage.xaml page, which is currently undefined. You will define this page later in the lab.

    Figure 12

    Unhandled Exception error page

  3. Press the Back button twice to navigate back to phone main page. There is very little that you can do at this time until you add some more functionality to the application. Do not close the emulator window.