Freelance Jobs

Sunday, December 12, 2010

Hello World App in Silverlight for Windows Phone 7

In this section, I will help you to write the widely used “Hello World” application for the Windows Phone. This may seem little bit silly for hard core programmers and non-programmers like. But here the situation is little bit different, we are going to create and compile app in a pc and is deploying and running it in a mobile device or at least an emulator. According to me this simple code serves two purposes, it will help to understand and how easy is to write a text on to the Windows Phone Screen and secondly, it helps us to experience the process of creating, developing, compiling and running a program without too much difficulties.

I will guide you to write the “Hello World”, in both Silverlight and XNA. In most of the cases you will be using XNA for developing games, but I wanted to show that the functionality can be achieved using both technologies.

For writing your first application you need, Windows Phone 7 Developer Tools, which includes Visual Studio 2010 for Windows Phone, the Windows Phone Emulator and it is a free download from the Microsoft Download Center

Writing the App in Silverlight

Power up Visual Studio 2010 for Windows Phone from Start Menu or from Desktop.  From the File Menu select New Project -> Visual C# -> Silverlight for Windows Phone from the installed templates. Then from the middle area, choose Window Phone Application. Enter a Name for the project and also the location, if we don’t want to create a directory for the solution, you can uncheck the Create Directory for the Solution.


After clicking Ok button and project will be created with a lot files, which I will explain latter. You will be welcomed by a large screen of windows phone in portrait mode, to be more precise 480 * 800 pixels by far largest screen to this date in phone world.  This is shown in the design view and one can add more controls by dragging and dropping them from the control toolbox. Instead of drag n drop we will write markup for creating the controls. For that we need to switch to markup view and this can be one by clicking any of the icons which may appear to the bottom of your screen.




In fact, the much touted three modes, Design, Markup and Split is also available for project targeting Windows Phone 7. You will see many files in the solution explorer under the project. One file of particular interest is the WMAppManifest.xml file. This file keeps all the setting, much like the web.config file in a web application. In the App tag near the Top there is title attribute, which displays the title of the application in Windows Phone.



   1:  <?xml version="1.0" encoding="utf-8"?>
   2:   
   3:  <Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" 
   4:              AppPlatformVersion="7.0">
   5:      <App xmlns="" ProductID="{57c40dfe-9882-4a9e-9ee4-07986afc331f}" 
   6:           Title="HelloWorld" 
   7:           RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" 
   8:           Author="HelloWorld author" Description="Sample description" 
   9:           Publisher="HelloWorld">
  10:          <IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
  11:          <Capabilities>
  12:              <Capability Name="ID_CAP_GAMERSERVICES"/>
  13:              <Capability Name="ID_CAP_IDENTITY_DEVICE"/>
  14:              <Capability Name="ID_CAP_IDENTITY_USER"/>
  15:              <Capability Name="ID_CAP_LOCATION"/>
  16:              <Capability Name="ID_CAP_MEDIALIB"/>
  17:              <Capability Name="ID_CAP_MICROPHONE"/>
  18:              <Capability Name="ID_CAP_NETWORKING"/>
  19:              <Capability Name="ID_CAP_PHONEDIALER"/>
  20:              <Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
  21:              <Capability Name="ID_CAP_SENSORS"/>
  22:              <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
  23:          </Capabilities>
  24:          <Tasks>
  25:              <DefaultTask  Name ="_default" NavigationPage="MainPage.xaml"/>
  26:          </Tasks>
  27:          <Tokens>
  28:              <PrimaryToken TokenID="HelloWorldToken" TaskName="_default">
  29:                  <TemplateType5>
  30:                      <BackgroundImageURI IsRelative="true" IsResource="false">
  31:                          Background.png</BackgroundImageURI>
  32:                      <Count>0</Count>
  33:                      <Title>HelloWorld</Title>
  34:                  </TemplateType5>
  35:              </PrimaryToken>
  36:          </Tokens>
  37:      </App>
  38:  </Deployment>
 
The project name will be defaulting here and we will give a friendlier name here.
 

   1:  <Title>Hello World</Title>

In this file we can also change application icon, which will be appearing as the icon in the installed apps in a Windows Phone.


   1:  <BackgroundImageURI IsRelative=”trueIsResource=”false>Background.png</BackgroundImageURI>

In the standard toolbar, you will see two options. Windows Phone 7 Emulator and Windows Phone 7 Device. First one is the one installed with Windows Phone Developer tools and majority of testing the application is done using this. The second one is used to deploy the application into the real device, which will be connected to the computer via USB.






If we press F5 now, our application will compile and the home screen will show in the emulator. When you first compile an application, it may seem that it’s taking too much time coz of loading the emulator. If you leave emulator running during the edit/run/debug cycles, it won’t take much time, coz Visual Studio attaches to the already running process.


















We terminate the execution either through the IDE (using the Shift + F5 or Stop Debugging from the Debug Menu) or by exiting the program using the Back or Start button in the Emulator.




Don’t quit the program using the, X button in the emulator as it will shut down the emulator completely and will cause delay in starting up the app next time when we run it from the IDE.


Now let’s go back to the editor by stopping the application. In solution explorer, you will notice four files, App.xaml and App.xaml.cs and MainPage.xaml and MainPage.xaml.cs files. The files with xaml extension are the Extensible Application Markup Language(XAML) while the files cs extension are their corresponding code behind files in C#.

Let’s look into the App.xaml.cs file in more detail.



   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Net;
   5:  using System.Windows;
   6:  using System.Windows.Controls;
   7:  using System.Windows.Documents;
   8:  using System.Windows.Input;
   9:  using System.Windows.Media;
  10:  using System.Windows.Media.Animation;
  11:  using System.Windows.Navigation;
  12:  using System.Windows.Shapes;
  13:  using Microsoft.Phone.Controls;
  14:  using Microsoft.Phone.Shell;
  15:   
  16:  namespace HelloWorld
  17:  {
  18:      public partial class App : Application
  19:      {
  20:          /// <summary>
  21:          /// Provides easy access to the root frame of the Phone Application.
  22:          /// </summary>
  23:          /// <returns>The root frame of the Phone Application.</returns>
  24:          public PhoneApplicationFrame RootFrame { get; private set; }
  25:   
  26:          /// <summary>
  27:          /// Constructor for the Application object.
  28:          /// </summary>
  29:          public App()
  30:          {
  31:              // Global handler for uncaught exceptions. 
  32:              UnhandledException += Application_UnhandledException;
  33:   
  34:              // Show graphics profiling information while debugging.
  35:              if (System.Diagnostics.Debugger.IsAttached)
  36:              {
  37:                  // Display the current frame rate counters.
  38:                  Application.Current.Host.Settings.EnableFrameRateCounter = true;
  39:   
  40:                  // Show the areas of the app that are being redrawn in each frame.
  41:                  //Application.Current.Host.Settings.EnableRedrawRegions = true;
  42:   
  43:                  // Enable non-production analysis visualization mode, 
  44:                  // which shows areas of a page that are being GPU accelerated with a colored overlay.
  45:                  //Application.Current.Host.Settings.EnableCacheVisualization = true;
  46:              }
  47:   
  48:              // Standard Silverlight initialization
  49:              InitializeComponent();
  50:   
  51:              // Phone-specific initialization
  52:              InitializePhoneApplication();
  53:          }
  54:   
  55:          // Code to execute when the application is launching (eg, from Start)
  56:          // This code will not execute when the application is reactivated
  57:          private void Application_Launching(object sender, LaunchingEventArgs e)
  58:          {
  59:          }
  60:   
  61:          // Code to execute when the application is activated (brought to foreground)
  62:          // This code will not execute when the application is first launched
  63:          private void Application_Activated(object sender, ActivatedEventArgs e)
  64:          {
  65:          }
  66:   
  67:          // Code to execute when the application is deactivated (sent to background)
  68:          // This code will not execute when the application is closing
  69:          private void Application_Deactivated(object sender, DeactivatedEventArgs e)
  70:          {
  71:          }
  72:   
  73:          // Code to execute when the application is closing (eg, user hit Back)
  74:          // This code will not execute when the application is deactivated
  75:          private void Application_Closing(object sender, ClosingEventArgs e)
  76:          {
  77:          }
  78:   
  79:          // Code to execute if a navigation fails
  80:          private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
  81:          {
  82:              if (System.Diagnostics.Debugger.IsAttached)
  83:              {
  84:                  // A navigation has failed; break into the debugger
  85:                  System.Diagnostics.Debugger.Break();
  86:              }
  87:          }
  88:   
  89:          // Code to execute on Unhandled Exceptions
  90:          private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
  91:          {
  92:              if (System.Diagnostics.Debugger.IsAttached)
  93:              {
  94:                  // An unhandled exception has occurred; break into the debugger
  95:                  System.Diagnostics.Debugger.Break();
  96:              }
  97:          }
  98:   
  99:          #region Phone application initialization
 100:   
 101:          // Avoid double-initialization
 102:          private bool phoneApplicationInitialized = false;
 103:   
 104:          // Do not add any additional code to this method
 105:          private void InitializePhoneApplication()
 106:          {
 107:              if (phoneApplicationInitialized)
 108:                  return;
 109:   
 110:              // Create the frame but don't set it as RootVisual yet; this allows the splash
 111:              // screen to remain active until the application is ready to render.
 112:              RootFrame = new PhoneApplicationFrame();
 113:              RootFrame.Navigated += CompleteInitializePhoneApplication;
 114:   
 115:              // Handle navigation failures
 116:              RootFrame.NavigationFailed += RootFrame_NavigationFailed;
 117:   
 118:              // Ensure we don't initialize again
 119:              phoneApplicationInitialized = true;
 120:          }
 121:   
 122:          // Do not add any additional code to this method
 123:          private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
 124:          {
 125:              // Set the root visual to allow the application to render
 126:              if (RootVisual != RootFrame)
 127:                  RootVisual = RootFrame;
 128:   
 129:              // Remove this handler since it is no longer needed
 130:              RootFrame.Navigated -= CompleteInitializePhoneApplication;
 131:          }
 132:   
 133:          #endregion
 134:      }
 135:  }

You will see a namespace declaration in the name of the project and a class name App that is derived from the Application class in Silverlight. As you had seen in Silverlight Applications for web, all Silverlight windows phone applications contain an App class that derives from Application, and this class is responsible for application-wide initialization, start up and shutdown chores. This class is defined as a partial class which implies that it has got additional members which will be declared somewhere else and here it’s in the App.xaml file.

The structure for an App.xaml will be like this


   1:  <Application 
   2:      x:Class="HelloWorld.App"
   3:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
   4:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   5:      xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   6:      xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
   7:   
   8:      <!--Application Resources-->
   9:      <Application.Resources>
  10:      </Application.Resources>
  11:   
  12:      <Application.ApplicationLifetimeObjects>
  13:          <!--Required object that handles lifetime events for the application-->
  14:          <shell:PhoneApplicationService 
  15:              Launching="Application_Launching"
  16:              Closing="Application_Closing" 
  17:              Activated="Application_Activated"
  18:              Deactivated="Application_Deactivated"/>
  19:      </Application.ApplicationLifetimeObjects>
  20:   
  21:  </Application>

Although its looks like XML, it’s actually XAML which is an important thing in developing Silverlight Applications. The App.xaml file Is used to store resources that are used throughout the application. These could include color schemes, gradient brushes, styles etc.  The App.xaml and App.xaml.cs are the two parts of the App Class and during compilation Visual Studio parses App.xaml and generate another code file App.g.cs in which g stands for generated and it will be generated in \obj\debug  directory.
Now let’s inspect the App.xaml file in detail.

Towards the top of the file you can see the following detail


   1:   
   2:  <Application.RootVisual>
   3:   
   4:      <phoneNavigation:PhoneApplicationFrame x:Name="RootFrame" 
   5:              Source="/MainPage.xaml"/>
   6:   
   7:  </Application.RootVisual>

This markup instantiates an object of the PhoneApplicationFrame class and assigns its source property reverencing the  MainPage.xaml. this PhoneApplicationFrame object is then set the RootVisual property of the App object.

MainPage is another Major class in the program and the in most of the smaller programs in Silverlight, much time will be spend in this class, i.e. in MainPage.xaml and MainPage.xaml.cs. The cs page contains a lot of using directives by default, barring these the file is pretty straight forward.


   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Net;
   5:  using System.Windows;
   6:  using System.Windows.Controls;
   7:  using System.Windows.Documents;
   8:  using System.Windows.Input;
   9:  using System.Windows.Media;
  10:  using System.Windows.Media.Animation;
  11:  using System.Windows.Shapes;
  12:  using Microsoft.Phone.Controls;
  13:  namespace HelloWorld
  14:  {
  15:      public partial class MainPage : PhoneApplicationPage
  16:      {
  17:          // Constructor
  18:          public MainPage()
  19:          {
  20:              InitializeComponent();
  21:          }
  22:      }
  23:  }

Again it’s a partial class and its defines a class named MainPage and it’s derived from PhoneApplicationPage class in Silverlight. Actually this is the class responsible for displaying the visual when we run the program for the first time. The other half of the main page is defined in the MainPage.xaml.


   1:  <phone:PhoneApplicationPage 
   2:      x:Class="HelloWorld.MainPage"
   3:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   4:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   5:      xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   6:      xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   7:      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   8:      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   9:      mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
  10:      FontFamily="{StaticResource PhoneFontFamilyNormal}"
  11:      FontSize="{StaticResource PhoneFontSizeNormal}"
  12:      Foreground="{StaticResource PhoneForegroundBrush}"
  13:      SupportedOrientations="Portrait" Orientation="Portrait"
  14:      shell:SystemTray.IsVisible="True">
  15:   
  16:      <!--LayoutRoot is the root grid where all page content is placed-->
  17:      <Grid x:Name="LayoutRoot" Background="Transparent">
  18:          <Grid.RowDefinitions>
  19:              <RowDefinition Height="Auto"/>
  20:              <RowDefinition Height="*"/>
  21:          </Grid.RowDefinitions>
  22:   
  23:          <!--TitlePanel contains the name of the application and page title-->
  24:          <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
  25:              <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" 
  26:                         Style="{StaticResource PhoneTextNormalStyle}"/>
  27:              <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" 
  28:                         Style="{StaticResource PhoneTextTitle1Style}"/>
  29:          </StackPanel>
  30:   
  31:          <!--ContentPanel - place additional content here-->
  32:          <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
  33:      </Grid>
  34:   
  35:      <!--Sample code showing usage of ApplicationBar-->
  36:      <!--<phone:PhoneApplicationPage.ApplicationBar>
  37:          <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
  38:              <shell:ApplicationBarIconButton 
  39:      IconUri="/Images/appbar_button1.png" 
  40:      Text="Button 1"/>
  41:              <shell:ApplicationBarIconButton 
  42:      IconUri="/Images/appbar_button2.png" 
  43:      Text="Button 2"/>
  44:              <shell:ApplicationBar.MenuItems>
  45:                  <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
  46:                  <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
  47:              </shell:ApplicationBar.MenuItems>
  48:          </shell:ApplicationBar>
  49:      </phone:PhoneApplicationPage.ApplicationBar>-->
  50:   
  51:  </phone:PhoneApplicationPage>

The compilation process generates a file named MainPageg.cs,as in the case of App.xaml. As per theory App.g.cs and MainPage.g.cs are solely for internal use by the compiler and can be ignored by the programmer. The MainPage.xaml contains a Grid definition and couple of TextBlocks by default. This defines the visual tree of elements that we saw during the execution of the program, i.e. the “MY APPLICATION” and “page title” headings we saw in the designer and the emulator.

The Grid class derives from the Panel and is one among the many layout elements in Silverlight.  Panels can be thought of as a container which can hold and organize user interface elements in the screen. The TextBlock class derives from the FrameworkElement class and is used for displaying blocks of text. Another important element that derives from the Framework Element class is Control, from which Button, Slider, ListBox and other derive. So enough with the theory and lets go ahead and create our application.

We will now place a TextBlock element inside the Grid tags to display our message “Hello World”. So let’s set the Text property with our message and since text block can display short blocks of text, we can give the HorizontalAlignment and VerticalAlignment properties to have a nice look and feel to the text.


   1:  <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
   2:              <TextBlock Text="Hello World!"
   3:                         HorizontalAlignment="Center" VerticalAlignment="Center" >
   4:              </TextBlock>
   5:          </Grid>

Likewise we will change the title and application name so that it will match with our desired intent.
One point to note here is that, when use Silverlight to build applications for web, usually the background is White and text will be Black. But when developing for Windows Phone 7, it will be a nice idea to keep background as dark and text is lighter. For setting foreground for a root element, we can give as given below.



   1:  Foreground="{StaticResource PhoneForegroundBrush}"

I will discuss about the StaticResource mechanism in the coming posts. I think it’s time to compile our HelloWorld Application. Upon running we can see that our Application Frame occupies the entire visual display and the Main Page occupies the entire area of the frame. The outermost grid occupies the entire area of the page and its split into two. A title area on top and content area under that. Our new TextBlock element appear centrally aligned in this area.


















To summarize, by creating our HelloWorld application we had gone through some basic concepts including dynamic layout. We had also found out that various elements were capable of arranging themselves dynamically and also by setting HorizontalAlignment and VerticalAlignment properties we can put an element in the center of another element, or in along one of the edges or in one of the corners. Also by using buttons,




we can tilt the phone sideways, and by tilting we can see the content of the page shuffles to match the new orientation automatically.

1 comment: