You are on page 1of 249

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 1


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 2

Copyright

This is a preliminary document and may be changed substantially. The information
contained in this document represents the current view of the author as of the date of
publication. This EBook is for informational purposes only. WE MAKE NO WARRANTIES,
EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT.
Complying with all applicable copyright laws is the responsibility of the user. Without
limiting the rights under copyright, no part of this document may be reproduced, stor ed in,
or introduced into a retrieval system, or transmitted in any form or by any means
(electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without
the express written permission of its author.

Unless otherwise noted, the example companies, organizations, products, domain names, e-
mail addresses, logos, people, places, and events depicted in this document are fictitious,
and no association with any real company, organization, product, domain name, e-mail
address, logo, person, place, or event is intended or should be inferred.

2012 Karthikeyan Anbarasan, (www.F5debug.Net) All rights reserved.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 3





I dedicate this eBook to my Parents and my Wife, who make it all
worthwhile.
Karthikeyan Anbarasan, Microsoft MVP www.f5debug.net

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 4

ABOUT THE AUTHOR



Karthikeyan Anbarasan, Microsoft MVP (Most Valuable Professional) in ASP.NET/IIS
Architecture and founder of the blog www.f5debug.net, has over 6 years experience on
Microsoft Technologies (Windows Phone, Windows Azure, SQL Azure, Public and Private
Cloud, ASP.Net, C#.net, VB.Net, ADO.Net, Ajax, SQL Server, SSIS, SSRS, SSAS, Biztalk Server,
IBM MQ Server, WCF, WPF and some tools like Telerik, Infragisitcs, Syncfusion, etc..) and he
is a Mindcracker and DNF Most Valuable Professional.

Karthik works for 8KMiles Software Services as a Technical Cloud Architect and in his free
time used to write articles on any of the Microsoft technology and products which he is
familiar with. He has been certified by Microsoft in few of the technologies and has been
awarded by the largest community groups like Mindcracker MVP, Dotnetfunda MVP.

Certifications:
Microsoft Certified Professional.
Microsoft Certified Application Developer.
Microsoft Certified Solution Developer.
Microsoft Certified Technology Specialist in Web & Windows Application.
Microsoft Certified Technology Specialist in BizTalk Server.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 5


ACKNOWLEDGEMENT

I would like to express my heartful thanks to Mahesh Chand (Founder of Mindcracker
Networks) and Pinal Dave (Founder of Blogs.SQLAuthority.com), for constant motivation in
publishing this second eBook of mine.
I have always been a big believer in advocating free knowledge and education for all. To
continue this belief, I have personally begun writing free distributable books for the
community. Please feel free to share this book with your friends and co-workers.
Also, do not forget to share your knowledge and spread the word around about the blog
www.F5Debug.net. I should also mention about my website www.f5debug.net, which has
always inspired me to write more on .NET and related technologies.
Thanks to Daniel and Mahesh Chand for reviewing and checking the technical accuracy of
the Book. A special thanks to my wife who complied and formatted this book.




DISCLAIMER

The publisher and the author make no representations or warranties with respect to the
accuracy or completeness of the contents of this eBook. The strategies contained herein
may not be suitable for every situation. Neither the publisher nor the author shall be liable
for damages arising here from. Further, readers should be aware that Internet Web sites
listed in this work may have changed or disappeared between when this work was written
and when it is read.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 6

TABLE OF CONTENTS

Windows Phone Overview ............................................................................................................. 8
Hello World Silverlight Application.............................................................................................. 15
Working with Alarms/Reminders ................................................................................................ 38
Working with Contacts ................................................................................................................. 47
Working with Calendar ................................................................................................................. 51
Working with Camera ................................................................................................................... 56
Working with Panorama Control ................................................................................................. 63
Working with Pivot Control .......................................................................................................... 70
Working with Media ..................................................................................................................... 75
Working with Toast Notifications ................................................................................................ 81
Working with Tile Notifications ................................................................................................... 93
Working with Raw Notifications ................................................................................................ 107
Working with Tiles ...................................................................................................................... 119
Working with Launchers............................................................................................................. 127
Working with Choosers .............................................................................................................. 132
Working with Navigation............................................................................................................ 138
Working with Web Browser Control ......................................................................................... 145
Working with Screen Orientation .............................................................................................. 152
Working with BING Map Control ............................................................................................... 158
Working with Device Information ............................................................................................. 167
Working with Themes ................................................................................................................ 176
Working with Isolated Storage .................................................................................................. 182
Working with Files and Folders.................................................................................................. 190
Creating a Local Database .......................................................................................................... 199
Consuming an ODATA Service ................................................................................................... 215
Consuming a WCF Service .......................................................................................................... 224
Encrypting Data for Security ...................................................................................................... 230
WP7 Tool kit for Silverlight......................................................................................................... 235
Deploying Application to Marketplace ...................................................................................... 241
F5debug - Windows Phone Apps ............................................................................................... 248

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 7
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 8
Windows Phone Overview

Introduction
In this chapter we are going to see what Windows Phone 7 is and what are the hardware and
software requirements for developing a Windows Phone 7 Application and we are also going to see
the software development kit used to develop the application with Visual Studio 2010 IDE.

Windows Phone 7 applications are built on existing tools from Microsoft like the Visual Studio 2010
IDE, Expression Blend, Silverlight and XAML code. Windows Phone 7 provides 2 types of frameworks
upon which we can develop the applications and the types are as follows
Silverlight Framework With this framework we can develop event based XAML
applications for enterprise and consumer based application development.
XNA Games Framework As the name suggests, with this framework we can develop rich
games (2D and 3D) targeting the entertainment category.

With Windows Phone 7 we can develop applications accessing the framework internally, though we
have restrictions over developing applications targeting the native application development which is
a bit disappointment. We can develop native applications with Windows Phone 7 using VC++ but
with some restrictions over using multi-tasking and its features. We can also make use of the .Net
Compact framework which has support over Windows Phone 7 Development.

Before we start developing Windows Phone 7 applications, we need to have a look at the
requirements to set up the development environment. Microsoft has suggested the software and
hardware requirements which need to be considered when we start developing the application. The
hardware requirements are mainly for the device manufactures to certify the hardware required to
have better performance for the application that runs on the devices. As far as the software
development is concerned we need to have the latest updates running so that we can make use of
the framework more effectively and to have a better application developed using the latest features.

Initially it was Windows Mobile (6.0, 6.5) where Microsoft provided developers, the ability to play
around with the development of applications for mobile. We need to first know that Windows
Mobile and Windows Phone 7 are 2 different platforms even though both run on top of the CE
Kernel as far as the APIs are concerned. Windows Mobile and Windows Phone 7 do not have support
to run applications between the different platforms.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 9

Hardware Requirements
Below are some of the hardware requirements the device manufactures needed to take care of
while designing the device. These are the minimum requirements that should be considered and can
have variations to have a better performing device. As a developer we will not have much control
over these requirements, but developers can target the application development based on the
device with the hardware requirements specified. When considering Windows Mobile we can say
Windows Phone 7 has a higher configuration for device manufactures as below.
Multi Touch (4 Ways) Capacitive screen
DirectX 9 Acceleration
Accelerometer
Global Positioning System(GPS)
5 megapixel camera with flash
8 Gig Bytes Storage
256 MB of RAM
Button Controls

The items mentioned above are the minimum requirements, so a device can have a maximum
capacity to perform better. When we consider setting up the development environment for the
Windows Phone 7 Software Development Kit, we need to consider the requirements below to setup
the software. The Windows Phone 7 SDK is supported with one of the below OSs with all the
versions except the express version i.e. the Starter Versions
Windows Vista (All Editions)
Windows Phone 7 (All Editions)

Some of the OS which are not supported with the Windows Phone 7 SDK installations are as below.
Windows XP
Windows 8
Windows Server
Windows Virtual Machines

Also we need to have the below hardware requirements for the development environment
Minimum 4GB Hard disk Space
Minimum 3GB Ram
DirectX 10 or above capable graphics card with a WDDM 1.1 driver


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 10
Software Requirements
Once we are ready with the hardware setup of the environment we need to install the required
software to start with the development of Windows Phone 7 Applications. To start with, Microsoft
has provided all of the required and supported software with the SDK, which we can just download
from the link Windows Phone SDK 7.1
This SDK will install the development environment, providing options for the developers to develop
applications and games on both Windows Phone 7.0 and Windows Phone 7.5. The above Windows
Phone SDK 7.1 installs a list of products, which are in the list below.
Microsoft Visual Studio 2010 Express for Windows Phone
Windows Phone Emulator
Windows Phone SDK 7.1 Assemblies
Silverlight 4 SDK and DRT
Windows Phone SDK 7.1 Extensions for XNA Game Studio 4.0
Microsoft Expression Blend SDK for Windows Phone 7
Microsoft Expression Blend SDK for Windows Phone OS 7.1
WCF Data Services Client for Window Phone
Microsoft Advertising SDK for Windows Phone
Once the installation of the Windows Phone 7.1 SDK is complete, we can see new templates are
added to the Visual Studio 2010 IDE (Silverlight for Windows Phone 7 and XNA Games Studio). We
are set to start with the application development.

Windows Phone 7 Architecture
The architecture of Windows Phone 7 is made on top of 4 main components, where each
component, internally has many items to be seen in depth, which we will see in our upcoming
chapters. Taking a quick look at the below figure will give us some idea on the architecture.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 11


The 4 main components on which the Windows Phone 7 Architecture is built are as follows
Runtimes Silverlight and XNA frameworks provide us with an excellent environment for
the developers to build an optimized application.
Tools Visual Studio IDE, Expression Blend and the tools provide the developers with
flexibility to design and develop user rich applications.
Cloud Services Windows & SQL Azure, Notification Services, and Location Services provide
developers with usage of data across the frameworks with support over other 3rd party
services as well.
Portal Services Windows Phone Market Place provides developers with upload and
certifying the application to the market.

Where Silverlight Framework fits in Windows Phone 7?

Silverlight is basically used for light weight business applications and normal 2D game development
using XAML (Extensible Application Markup Language) Programming. Developers will have flexibility
in using this framework along with most used UI tools like Microsoft Blend, Adobe Photoshop etc. to
create a vector based process that can be easily transported to XAML.

This is really not a new topic compared to the XNA development since Silverlight is already in market
for developing rich browser applications and it provides an option of creating applications with
XAML which is highly advantageous for creating a vector based applications. So it gives the
developers full control of the layout, design, structure and also the data binding components.
Silverlight application development for Enterprise or Consumers looks like the image below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 12


Where XNA Framework fits in Windows Phone 7?

XNA is basically used for developing rich games where the framework comes with a game engine
(with 3D) which helps game developers to provide rich 3D games. Unlike Silverlight, XNA is not much
known across the developers since it has been used to develop Xbox games using Managed code.
Why Microsoft provided the XNA engine with the windows phone 7 is mainly because of integration
of Xbox live integration with Windows Phone 7. The XNA engine provides the rich user experience
that every developer can take advantage in providing next generation games with 2D and 3D game
loop engines. XNA Game Studio application development for entertainment or for the enterprise
looks like the image below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 13


How Windows Azure Cloud fits in Windows Phone 7?

When we create an application with Windows Phone 7, we need to save some data for future
retrieval which is going to be a bit tougher here. Windows Phone 7 doesnt provide direct
connectivity with a database to save the data. To overcome this we need to use AZURE. Windows
Azure provides the platform of Cloud Computing for storing and retrieving data from different
locations using Windows Phone 7.

For example, say today we create a small application in Windows Phone 7 using Silverlight. Day to-
day when the development increases and we finally get an excellent product, then the number of
user visit gets increased which eventually requires an enterprise database to save the details. So in
this case we can use the Azure availability of extending the size of the database as per the need
since it is maintained in the cloud.

Microsoft has provided us with an additional advantage of using Bing Maps which is given free of
cost, only for Windows Phone 7. Additionally Push notification services are also provided in the
cloud using which we can send notifications to the mobile, such as Text which is eventually a better
process for the business needs.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 14

Windows Phone 7 Development Life Cycle
As developers of Windows Phone 7 applications, we need to register with App hub using the below
link http://create.msdn.com/en-US/ by giving our Windows Live credentials which act like a single
sign on for all the process which Microsoft provides. The main idea behind registering with App hub
is, once we register and develop an application in Windows Phone 7 we can use our registered
handset as a physical device to test our application. App Hub provides developers with up to 3
devices that can be registered and tested it in real-time. Now let us understand the steps involved in
setting up our account.

Steps to Register with the APP HUB Market Place:
Step 1 Register with App Hub.
As mentioned above, App hub is the Microsoft place where we need to register and use for testing
our application in real-time. Please follow the steps below to register in App Hub.

Step 2 Market Place Certification Procedures.
Once we are registered with App Hub, before proceeding with the development, consider reading
the certification process document in order to avoid rejection of the product at the market level.
Please refer to the below link for the Application Certification process checklist and validation.
http://go.microsoft.com/?linkid=9730558

Once the development is completed and the validation process is checked and passed by the
Market, then the application will be available online for downloads.
Microsoft reserves the rights to give 5 free applications downloads and unlimited number of paid
application downloads. Microsoft charges an amount of $99 for the market place registration to
submit the developed application. For each download, Microsoft takes 30% of the fees paid and the
developer will get 70% for his development.

Summary
We have seen in this chapter a complete overview on what Windows Phone 7 development is and
the hardware and software requirements for developing a Windows Phone 7 Application in detail. In
our upcoming chapters, we will see some of the interesting features of Windows Phone 7
development.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 15
Hello World Silverlight Application

Introduction
In this chapter we are going to see how to create a Silverlight Windows Phone 7 Application using
the Visual Studio IDE. In our earlier chapter we have seen the software and the hardware
requirement in order to develop a Windows Phone application. Here in this chapter we will create a
Hello World Application and try to run it in the Windows Phone 7 Emulator to check the working
model of the application. Let us see the steps involved in designing the Hello World application using
the Visual Studio 2010 IDE.

Steps
As we discussed in our earlier chapter, after installing the Windows Phone 7 SDK, we can see the
new template options available with the Visual Studio 2010. The new templates are for creating
Silverlight for Windows Phone Application and the other one is for XNA Game Studio 4.0, which will
help us to develop the respective application as per the requirement as shown in the screen below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 16
In this book we are going to concentrate more on the Silverlight for Windows Phone application
development for enterprise and commercial application builders. Also we will see how to create a
XNA Game studio application as well so that it will give us some idea on the difference between the
two projects. Let us create a Silverlight for Windows Phone 7 Hello world application. To start with,
select the Windows Phone Application and provide a name for the project as shown in the screen
below.



Clicking on OK will create the application; we can see a popup window asking us to select the version
of Windows Phone 7 OS. We will go with selecting the latest platform, Windows Phone OS 7.1 as
shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 17
Clicking on OK will open the project in Visual Studio. We can see the Windows Phone 7 interface in
the designer view and the XAML code below.



Now drag and drop controls from the toolbox to get some user input and show the output Hello
World. Alternatively, we can write the XAML code to get the controls based on the requirement.
Once we have the controls on the designer, our screen looks like below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 18
The XAML code for the above design is given in the code block below. Give it a look to get an idea on
the type of controls used and the properties assigned for each control to get a better user interface.
We can copy and paste this below XAML code to any Windows Phone 7 Page to get the design. Here
we have added 4 Text blocks, 2 text boxes for inputs and a button control to trigger some event.
Also, if you have noticed we have changed the header message to F5DEBUG APPLICATION, in upper
case, which is the standard we should consider while developing our applications.

XAML Code:
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG APPLICATION" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="F5Debug" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="25,106,0,0" Name="textBlock1"
Text="First Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="140,84,0,0" Name="textBox1" Text=""
VerticalAlignment="Top" Width="310" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="25,167,0,0" Name="textBlock2"
Text="Last Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="140,145,0,0" Name="textBox2" Text=""
VerticalAlignment="Top" Width="310" />
<Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="39,241,0,0"
Name="SUBMIT" VerticalAlignment="Top" Width="377" Click="SUBMIT_Click" />
<TextBlock Height="51" HorizontalAlignment="Left" Margin="25,354,0,0" Name="textBlock3"
Text="" VerticalAlignment="Top" Width="413" />
<TextBlock Height="50" HorizontalAlignment="Left" Margin="159,28,0,0" Name="textBlock4"
Text="HELLO WORLD" VerticalAlignment="Top" Width="173" />
</Grid>

Now that we are done with the design, we need to go to the code behind Submit button Event and
write the code belo, which get the user input from the 2 text boxes (First Name and Last Name ) to
provide a welcome message to the user.

C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 19
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 F5debugWp7HelloWorld
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void SUBMIT_Click(object sender, RoutedEventArgs e)
{
string strFname = textBox1.Text.ToString();
string strLname = textBox2.Text.ToString();

textBlock3.Text = "Welcome " + strFname.ToString() + " " + strLname.ToString();
}
}
}




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 20
Now build the application and execute the project. Check the output by pressing F5 from the
keyboard directly or by pressing the play button from the IDE tool bar and we can see the output in
the Windows Phone 7 Emulator as shown in the screen below.

Note We need to check if the target to run the application is pointing to Windows Phone Emulator
and not Windows Phone Device.



Now we can enter the test inputs and click on the Submit button to get the welcome message as
shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 21

Summary
In this chapter we have seen the steps involved in creating a Hello World application in Windows
Phone 7 with Silverlight.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 22
Using Expression Blend

Introduction
In this chapter we are going to see how to design the user interface of a Windows Phone 7
Application using Expression Blend. Expression Blend is one of the products of the Expression Suite
of applications, which is used to design rich user interface for a XAML based application. Basically we
can design any Silverlight or WP7 application which are XAML based and now we can use this
product to design the Windows Phone 7 Application as well.

Expression Studio is a licensed version, but for developing Windows Phone 7 applications,
Expression Blend is available for free with the Windows Phone 7 SDK we initially downloaded when
we made the development environment ready (Check my first chapter on Overview of Windows
Phone 7 Development). Let us see the steps involved in using Expression Blend to make rich user
experienced designs for Windows Phone 7 Applications.

Steps
Let us take the sample which we used in the last chapter. Open Visual Studio 2010 and open the
project and we can see the application like below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 23

Now we will design this page using Expression Blend. To start with, first locate the page in the
Solution Explorer of Visual Studio 2010 and then right click and select Open in Expression Blend as
shown in the screen below.



Clicking on Open in Expression Blend will load the Expression Blend IDE and we can see the page
opened as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 24


Now we need to select the button (SUBMIT) from the Object and Timeline pane on the left side and
right click to select the Edit template option to create an empty template as shown in the screen
below.



Now we can see a pop up window, which has the option to create the empty Control template
resource for the button. Just click on OK to proceed further without changing any options.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 25



Now select the GRID from the Objects and Timeline pane and right click to change the layout. From
the list of layouts, select Border as shown in the screen below.



Now we need to customize the design of the button. Go to the Appearance section and change the
border thickness and corner radius as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 26

Now change the background color by selecting the Brushes section. Change the color as per the
requirement and also we have option to customize by providing the color code directly as shown in
the screen below.


Similarly we need to change the setting for the Border Brush by selecting from the color pallet or by
providing the color code as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 27


Now we need to switch to the Assets panel and select the text block tool from the controls pane
under the Border element of the template, as shown in the screen below.



Now we need to customize the design for the text block by selecting the appearance and layout
sections on the right side panel and changing the alignments, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 28


Now this step is very important. To change the content of the text property, select the Common
Property category and click on the Advanced Property option to change the template binding to
Content, as shown in the screen below.



Now we are done with our design and the user interface. We can see the button customized and
looks like a rich user interface, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 29


Now go back to the Visual Studio IDE and load the project, we can see a alert window that some of
the resources are changed outside Visual Studio and if we need to restore those changes. Click on
Yes to All and proceed further as shown in the screen below.



Now build and execute the application by pressing F5 button from the keyboard or by directly
selecting the Build solution. We can see the application loaded on to the Windows Phone 7 Emulator
and we can see the output as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 30


Summary
In this chapter we have seen the steps involved in using Expression Blend to design a rich user
interface for a Windows Phone 7 Application and load it into the Windows Phone Emulator.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 31
Working with Application Bar

Introduction

In this chapter we are going to see how to use Application Bar effectively for Windows Phone 7
Application development. In our earlier chapters, we have seen how to create an application using
Visual Studio 2010 and do some rich user interface design changes with Microsoft Expression Blend.
In this chapter we will also create a new application and configure the application bar to make
effective use of it.

The Application Bar is a set of Icons that can be configured at the bottom of an application for each
page or for multiple pages. These buttons can be used to navigate to frequently used pages across
the application, which makes navigation for users quick and easy. It automatically adjusts its icons
and buttons as the screen orientation changes.

The text based menu items are displayed as a list rather than the icons being shown on the screen.
To access the menu items, we can directly click the ellipsis at the right corner of the application bar.
The menu items are by default taken in lower case to have a consistent end user experience. Now let
us see the steps involved in adding an Application Bar to a new project and configuring the
application bar with icons and menu items.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application named
F5debugWp7ApplicationBar, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 32


We can now see the project is created and ready to start with our development task. As we follow
some standards, we can change the page header and make some small modifications so that the
page looks unique. Once we are done with the changes, to add the application bar, go to the XAML
Page and we can see a commented section, as shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 33
We just need to uncomment this section to have the application bar ready with some default
buttons and menus, which we can configure as per our requirements. Once we uncomment this
section we can see that we have 2 application bar icons added and 2 menu items added with the
default values. Now we will change it to 3 Application bar icons and 3 Menu items. Before we start
adding the code for it, we need to have the Application bar icons ready. By default when we install
the Windows Phone 7 SDK, we have the icons installed to the local development machine which will
be available in the below locations.

DriveName\Program Files\Microsoft SDKs\Windows Phone\v7.1\Icons\dark
DriveName\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Icons\dark

We can see the list of ICONS available below.



Now in the uncommitted application bar code, add the code for 3 buttons and 3 menu items as
shown in the screen below. Before that, add the icons that are required to use in the application bar
to a new Images folder.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 34

Now we need to build the application icons. To do that, go to the properties of the each image and
change the Build Action from Content from Resources. Do the same for all the icons which have
been added to the images folder.



Once we are done with the above step, go to the XAML code and make the changes for each button
by adding the appropriate icon and the button text, as shown in the below XAML code.

<shell:ApplicationBarIconButton IconUri="/Images/appbar.next.rest.png" Text="Back";
<shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add";
<shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="Front";

Now do the same for the menu items by adding the menu details, as specified in the code below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 35
<code><shell:ApplicationBarMenuItem Text="Home"/>
<shell:ApplicationBarMenuItem Text="Submit"/>
<shell:ApplicationBarMenuItem Text="Help"/></code>

Once we are done with the above 2 code changes, our final application bar code will look like below.
<code><phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/appbar.next.rest.png" Text="Back"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add"/>
<shell:ApplicationBarIconButton IconUri="/appbar.back.rest.png" Text="Front"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="Home"/>
<shell:ApplicationBarMenuItem Text="Submit"/>
<shell:ApplicationBarMenuItem Text="Help"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar></code>

Now we can run the application to see if the application bar is configured correctly and the icons are
visible. To build and execute the application, just press F5 or select the build solution option from
the tool box. We can see the application is loaded into the Windows Phone 7 Emulator below.


Now we need to have an event handler to trigger each button event. To do that, add the event
handler code in the XAML and add the event triggering code to the code behind, as shown in the
code below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 36
XAML Code:
<code><phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar.next.rest.png" Text="Back"
Click="NextButton_Click"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add"
Click="AddButton_Click"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="Front"
Click="BackButton_Click"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="Home" Click="HomeMenuutton_Click"/>
<shell:ApplicationBarMenuItem Text="Submit" Click="SubmitMenuButton_Click"/>
<shell:ApplicationBarMenuItem Text="Help" Click="HelpMenuButton_Click"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar></code>

C# Code:
<code>private void NextButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Next Application Bar Is Clicked!!!");
}</code>

private void AddButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Add Application Bar Is Clicked!!!");
}

private void BackButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Back Application Bar Is Clicked!!!");
}

private void HomeMenuutton_Click(object sender, EventArgs e)
{
MessageBox.Show("Home Menu Is Clicked!!!");
}

private void SubmitMenuButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Submit Menu Is Clicked!!!");
}

private void HelpMenuButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Help Menu Is Clicked!!!");
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 37
We have just added code to trigger a Message Box stating which button is clicked. Once we are done
with the above code, press F5 to build and execute the application and click on the Application Bar
button to see the expected output, as shown in the screen below.



Summary
In this chapter we have seen how to use the Application Bar and the steps to configure the
application bar with menu items. The Application Bar can be of use in different scenarios and used
across the pages. We can also use Application Bar globally.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 38
Working with Alarms/Reminders

Introduction
In this chapter we are going to how to use the Alarms and Reminders notifications in a Windows
Phone 7 Application. A notification is a message that pops up on the screen to the end users at a
specified time, scheduled initially. We can make the pop up with some customized message for user
friendly requirements. Basically we can make 2 types of notifications, an Alarm and a Reminder.

An Alarm is used to play a music file when a notification is launched, as scheduled by the end users.
A Reminder notification is similar to the Alarm notification, expect we can have some text
information to show the end user and also we can provide a navigation URI of a page to be opened
by clicking on the reminder UI. We can also include some query string parameters to pass
information that should be used within the page or the application to which the navigation is
pointing to. Microsoft has a limitation of using 50 Alarm or Reminder notifications within a single
application.

Alarms and Reminders use the Alarm Class and Reminder Class respectively. We will see in this
chapter how to use these classes to create alarms and reminders that can be used in real time. We
will create a new Windows Phone 7 project and provide options to add an alarm and reminder. Let
us see the steps involved in adding alarm and reminder notifications.

Steps
To create an Alarm application, Open Visual Studio 2010 and create a new Windows Phone for
Silverlight application with a valid project name and location to which the project should be saved,
as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 39


Now let us add 2 pages, one for adding an alarm content page and other for adding a reminder
content page. Once we added 2 pages in the main page, we need to add 2 buttons in the main page
from which the 2 new pages will be triggered as shown in the screen below..



We have added 2 pages, AddAlarm.XAML and AddReminder.XAML. On the button click event, we
need to navigate to these 2 pages, as shown in the code behind.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 40

XAML Code
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="F5DEBUG" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Alarm" Height="161" HorizontalAlignment="Left" Margin="65,108,0,0"
Name="btnAlarm" VerticalAlignment="Top" Width="330" Click="btnAlarm_Click"/>
<Button Content="Reminder" Height="161" HorizontalAlignment="Left" Margin="65,306,0,0"
Name="btnReminder" VerticalAlignment="Top" Width="330" Click="btnReminder_Click"/>
</Grid>
</Grid>


C# Code
private void btnAlarm_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/AddAlarm.xaml", UriKind.Relative));
}

private void btnReminder_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/AddReminder.xaml", UriKind.Relative));
}


ALARM Page:
Now we need to add the content to the AddAlarm.XAML page. To add an alarm, we need to make
use of the Alarm class which is inherited from the ScheduledNotification class. Now add the controls
to the AddAlarm.XAML Page, as shown in the screen below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 41
XAML Code:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="26,94,0,0" Name="ttName"
Text="Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="126,68,0,0" Name="txtName" Text=""
VerticalAlignment="Top" Width="306" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="26,172,0,0" Name="ttContent"
Text="Content" VerticalAlignment="Top" />
<TextBox Height="132" HorizontalAlignment="Left" Margin="126,146,0,0" Name="txtContent"
Text="" VerticalAlignment="Top" Width="306" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="26,310,0,0" Name="ttBegintime"
Text="Begin Time" VerticalAlignment="Top" />
<toolkit:DatePicker Name="datePicker1" Height="67" Margin="126,286,145,254" />
<Button Content="Add" Height="72" HorizontalAlignment="Left" Margin="54,470,0,0"
Name="btnAdd" VerticalAlignment="Top" Width="160" Click="btnAdd_Click" />
<Button Content="Clear" Height="72" HorizontalAlignment="Left" Margin="220,470,0,0"
Name="btnClear" VerticalAlignment="Top" Width="160" Click="btnClear_Click" />
<toolkit:TimePicker HorizontalAlignment="Left" Margin="317,286,0,0" Name="timePicker1"
VerticalAlignment="Top" Width="115" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="26,383,0,0" Name="textBlock1"
Text="Expiration" VerticalAlignment="Top" />
<toolkit:DatePicker Height="67" Margin="126,359,145,181" Name="datePicker2" />
<toolkit:TimePicker HorizontalAlignment="Left" Margin="317,359,0,0" Name="timePicker2"
VerticalAlignment="Top" Width="115" />
</Grid>





Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 42

C# Code:
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
AddAlaram();
}

void AddAlaram()
{
Alarm alarm = new Alarm(txtName.Text.ToString());
alarm.Content = txtContent.ToString();

DateTime date = (DateTime)datePicker1.Value;
DateTime time = (DateTime)timePicker1.Value;
DateTime beginTime = date + time.TimeOfDay;
alarm.BeginTime = beginTime;

DateTime date1 = (DateTime)datePicker1.Value;
DateTime time1 = (DateTime)timePicker1.Value;
DateTime exptime = date1 + time1.TimeOfDay;
alarm.ExpirationTime = exptime;

alarm.RecurrenceType = RecurrenceInterval.Daily;

ScheduledActionService.Add(alarm);
}


In the above code, we have some properties which are to be considered before we write our
requirement on top of it. The properties are as follows
Name Unique Name for the Alarm.
Title This is default name, and we cannot set this property manually.
Content This property is to set some content for the alarm.
Begin Time Beginning of the alarm.
Expiration Time Expiration time of the alarm.
Recurrence Type Recurrence type of the alarm.
Sound Sound file to play for the alarm.
Now run the application and see the alarm configuration, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 43


REMINDER Page:

Now let us start with designing the Reminder page. Before that we will add a new page called
AddReminder.XAML. The use of this page is to create a reminder trigger which will have the option
to navigate to a URI with passing some parameters. We will pass values to the pages from the
Reminder page. We will see how to do that with this page. Add contents from the tool box for the
Reminder page, as shown in the screen below and the code.


XAML Code:

Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="21,32,0,0" Name="ttName"
Text="Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="121,6,0,0" Name="txtName" Text=""
VerticalAlignment="Top" Width="306" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="21,178,0,0" Name="ttContent"
Text="Content" VerticalAlignment="Top" />
<TextBox Height="132" HorizontalAlignment="Left" Margin="121,152,0,0" Name="txtContent"
Text="" VerticalAlignment="Top" Width="306" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="21,316,0,0" Name="ttBegintime"
Text="Begin Time" VerticalAlignment="Top" />
<toolkit:DatePicker Height="67" Margin="121,292,150,248" Name="datePicker1" />
<Button Content="Add" Height="72" HorizontalAlignment="Left" Margin="49,476,0,0"
Name="btnAdd" VerticalAlignment="Top" Width="160" />
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 44
<Button Content="Clear" Height="72" HorizontalAlignment="Left" Margin="215,476,0,0"
Name="btnClear" VerticalAlignment="Top" Width="160" />
<toolkit:TimePicker HorizontalAlignment="Left" Margin="312,292,0,0" Name="timePicker1"
VerticalAlignment="Top" Width="115" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="21,389,0,0" Name="textBlock1"
Text="Expiration" VerticalAlignment="Top" />
<toolkit:DatePicker Height="67" Margin="121,365,150,175" Name="datePicker2" />
<toolkit:TimePicker HorizontalAlignment="Left" Margin="312,365,0,0" Name="timePicker2"
VerticalAlignment="Top" Width="115" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="21,100,0,0" Name="ttTitle"
Text="Title" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="121,74,0,0" Name="txtTitle" Text=""
VerticalAlignment="Top" Width="306" />
</Grid>



C# Code:
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
AddReminder();
}

void AddReminder()
{
Reminder reminder = new Reminder(txtName.Text.ToString());

reminder.Title = txtTitle.Text.ToString();
reminder.Content = txtContent.Text.ToString();

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 45
DateTime date = (DateTime)datePicker1.Value;
DateTime time = (DateTime)timePicker1.Value;
DateTime beginTime = date + time.TimeOfDay;
reminder.BeginTime = beginTime;

DateTime date1 = (DateTime)datePicker1.Value;
DateTime time1 = (DateTime)timePicker1.Value;
DateTime exptime = date1 + time1.TimeOfDay;
// reminder.ExpirationTime = exptime;

reminder.RecurrenceType = RecurrenceInterval.Daily;

string struri = "?param=Reminder App Passed";
Uri navigationUri = new Uri("/ReminderAppPage.xaml" + struri, UriKind.Relative);
reminder.NavigationUri = navigationUri;

ScheduledActionService.Add(reminder);
}

In the above code, we have some properties which are to be considered before we write our
requirement on top of the reminder properties. Some of the main properties are as follows
Name Unique Name for the Reminder.
Title This is default name, and we cannot set this property manually.
Content This property is to set some content for the reminder.
Begin Time Beginning of the Reminder.
Expiration Time Expiration time of the Reminder.
Recurrence Type Recurrence type of the Reminder.
Navigation URI User will be navigated to this page when clicking on the Reminder
application.
We have added a parameter to be passed with the navigation URI as a query string. To get the query
string value, we need to write the code below in the new page (AddReminder.XAML), as shown in
the screen below.

C# Code:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);

string paramValue = "";
NavigationContext.QueryString.TryGetValue("param", out paramValue);

textBlock1.Text = paramValue;
}

Now we can run the application and see the Reminder configuration as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 46



Summary
In this chapter we have seen how to make use of the inbuilt Scheduled Notification mechanism to
build applications which notifies end users with some custom messages. Alarms and Reminders play
a major role for notifications to end users, as per the requirements.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 47
Working with Contacts

Introduction
In this chapter we are going to see how to work with inbuilt contacts data and use it across our
requirement to manipulate the data. Windows Phone 7.1 provides a read only access to the data
available locally across the device. We can query the data and select the users based on the search
filters and also we can do multiple manipulations in order to perform some operation with the users
contact information.
Let us see the steps involved in using contacts for querying data. To launch the contacts, we need to
use the AddressChooserTask which is used to select contacts. The queried result can be collected in
the AddressResult object and can be used to list it, as per the requirements. Let us start with
creating a new application and start using the AddressChooserTask.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project and provide a
valid project name, as shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 48
Now we will add a button which triggers an event to query the data and get the contacts in a list.
Add the below XAML code, or we can directly drag and drop the controls, as shown in the screen
below.

XAML Code:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Get Contacts" Height="83" HorizontalAlignment="Left" Margin="30,16,0,0"
Name="btnContacts" VerticalAlignment="Top" Width="402" Click="btnContacts_Click" />
<ListBox Name="lstcontacts" ItemsSource="{Binding}" Margin="47,188,36,52" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="txtResults" Text="{Binding Path=DisplayName, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="41" HorizontalAlignment="Left" Margin="47,118,0,0" Name="txtResults"
Text="List of Contacts" VerticalAlignment="Top" Width="373" />
</Grid>




Now we will add some code in the code behind page for querying the data from the contacts
database. To do that, go to the button click event and write the code below. Basically, the Windows
Phone 7 Emulator has some default contacts which can be tested by pulling the list in this chapter.
We need to add the namespace in order to access the data.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 49

using Microsoft.Phone.UserData;

Now in the button click event add the code below. From the code we can see the Contact class been
used to query the details. Here we will be using the SearchAsyc method to do the search with the
object and provide the result set to the list, as shown in the code below.

C# Code:

private void btnContacts_Click(object sender, RoutedEventArgs e)
{
Contacts cContacts = new Contacts();
cContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(ContactsSearch);
cContacts.SearchAsync(String.Empty, FilterKind.DisplayName, null);
}
void ContactsSearch(object sender, ContactsSearchEventArgs e)
{
try
{
lstcontacts.DataContext = e.Results;
}
catch (System.Exception)
{
txtResults.Text = "No Results Available";
}

if (lstcontacts.Items.Any())
{
txtResults.Text = "Below is the List of Contacts";
}
else
{
txtResults.Text = "No Results Available";
}
}


In the above code, we are querying the contacts class object and bind it to the list box using the data
context and do some small user information with the message. In the SearchAsync method, we
provide different filters that can be used to access the data. Below is the list of filters that can be
provided, based on the requirement.
Search All Contacts SearchAsync(String.Empty, FilterKind.None, null)
Get Pinned Contacts SearchAsync(String.Empty, FilterKind.PinnedToStart, null)
Search by Display Name SearchAsync(Karthik, FilterKind.DisplayName, null)
Search by Email ID SearchAsync(Karthik@f5debug.net, FilterKind.EmailAddress, null)
Search by Phone No SearchAsync(123-456-7890, FilterKind.PhoneNumber, null)
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 50
Now we are done with the application. In the IDE, press F5 or click on Build and execute the solution.
We can see the end result by pressing the button once the application is loaded as shown below.



The list of contacts which are shown in the above screen is the default contacts available with the
Emulator for testing purposes. We can use these contacts to do the testing or delete them based on
the requirement.

Summary
In this chapter we have seen how to perform a contact data search using the AddressChooserTask
and play around with the contact selected to list or to manipulate the contact.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 51
Working with Calendar

Introduction

In this chapter, we are going to see how to use the Calendar application to access the calendar data
and use it across the development as and when needed. In our earlier chapters, we have seen how
to use the contact and access contact data; we are going to use the same process for accessing the
calendar objects.

In order to use the calendar object, we are going to use a reference of the Appointments object and
do an Async search to get the results and show it on a collection of Appointment objects. The end
result in the appointments object can be used in different ways, as per the requirement, by binding
to different controls. The Appointment class is to interact with user appointment data and is
inherited from the Microsoft.Phone.UserData namespace. Let us see the steps involved in using
calendar objects and listing the appointments.


Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 52

Now in order to fetch the details of the calendar appointments and show it to the end users, we will
add controls from the toolbox, as shown in the screen below. We can just drag and drop the controls
from the tool box, write XAML code or copy paste XAML code.

XAML Code:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="calendar" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Get Appointment" Height="83" HorizontalAlignment="Left" Margin="30,16,0,0"
Name="btnAppointment" VerticalAlignment="Top" Width="402" Click="btnAppointment_Click" />
<ListBox Name="lstAppointment" ItemsSource="{Binding}" Margin="47,188,36,52" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="txtResults" Text="{Binding Path=DisplayName, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="41" HorizontalAlignment="Left" Margin="47,118,0,0" Name="txtAppointments"
Text="List of Appointments" VerticalAlignment="Top" Width="373" />
</Grid></Grid>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 53



Now we need to add code to list the calendar appointments in the list view. First add the following
namespace.

using Microsoft.Phone.UserData;

Now add the button click event code. Here we are going to create an object of the Appointment
class and do an AsyncSearch. We need to provide the start time and end time to fetch the
appointment details and also should provide the maximum count. Copy and paste the code below to
the code behind for the button click event.

C# Code:
private void btnAppointment_Click(object sender, RoutedEventArgs e)
{

Appointments aAppointment = new Appointments();

aAppointment.SearchCompleted += new
EventHandler<AppointmentsSearchEventArgs>(GetAppointments);

DateTime starttime = DateTime.Now;
DateTime endtime = starttime.AddDays(10);
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 54
int maxAppointment = 20;

aAppointment.SearchAsync(starttime, endtime, maxAppointment, null);
}

void GetAppointments(object sender, AppointmentsSearchEventArgs e)
{
try
{
lstAppointment.DataContext = e.Results;
}
catch (System.Exception)
{
txtAppointments.Text = "No Appointments Found!!!";
}

if (lstAppointment.Items.Any())
{
txtAppointments.Text = "Below is the List of Appointments";
}
else
{
txtAppointments.Text = "No Appointments Found!!!";
}
}

The above code will pull the information from the appointments object and bind it to the data
context of the list box. If there are no appointments available, we can see an empty result as well. To
check the application just run the application by pressing F5 directly from the keyboard or by
selecting build and execute solution from the tool bar. We can see the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 55

Since we are in the emulator and we dont have any appointments, saved list is empty. If any
appointments are saved in the physical device we will get the complete list of appointments for the
next 10 days here in the list box.


Summary
In this chapter we have seen how to use the calendar object to fetch appointment details and list
them out. We can customize the appointments object to bind with different data binding options, as
per the requirements.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 56
Working with Camera

Introduction
In this chapter, we are going to see how to use the Camera options in developing applications with
Windows Phone 7. In order to access the camera features, we are going to use the Launchers and
Choosers which have the inbuilt APIs to perform each task based on the requirement. To
manipulate the camera photos and storage with the device, we are going to use the
CameraCaptureTask. This task is used to launch the default camera application to take some snap
shot for any third party application which is trying to use the camera to save images locally or to
isolated storage (Isolated storage enables managed applications to create and maintain local
storage. Isolated storage in Windows Phone is similar to isolated storage in Silverlight.)

Here in this chapter we will see how to take a picture using the camera and save it locally. We need
to have some understanding of the Launchers and Choosers task since we need to select the task
based on our requirement. Let us use the CameraCaptureTask and complete the process step by
step using Visual Studio for Windows Phone 7.

Steps
Let us Open Visual Studio 2010 and create a new Silverlight for Windows Phone project with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 57

Now to invoke the CameraCapture task and save the image locally, we add 2 controls: a button and
an image viewer control. The button control is to invoke the CameraCapture task and get the camera
image. The image viewer control is to display the image which we took using the camera
application. Drag and drop the images from the toolbox or write the XAML code, as shown below.

XAML Code:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Invoke Camera" Height="72" HorizontalAlignment="Left" Margin="36,30,0,0"
Name="btnCamera" VerticalAlignment="Top" Width="389" Click="btnCamera_Click" />
<Image Height="377" HorizontalAlignment="Left" Margin="36,187,0,0" Name="imgCaptured"
Stretch="Fill" VerticalAlignment="Top" Width="389" />
<TextBlock Height="39" HorizontalAlignment="Left" Margin="36,129,0,0" Name="txtResult" Text=""
VerticalAlignment="Top" Width="389" />
</Grid>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 58


Now we are done with our design, our next task is to invoke the camera application and capture an
image. Once captured, we are going to assign the image to the Image Viewer control. To invoke the
CameraCaptureTask, we need to include the below two namespaces

using Microsoft.Phone.Tasks;
using Microsoft.Phone;

Now let us add the code behind with the required code. First, we add class level variables which are
used to invoke the camera task. Add the below class level variables within the class scope. We are
creating an object of the CameraCaptureTask, using the code below.

C# Code:
private CameraCaptureTask ccTask;

Now we need to invoke the Camera on the button click event. To do that, let us first complete the
object creation in the MainPage constructor and in the button event handler, invoke the camera, as
shown in the code below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 59
C# Code:
public MainPage()
{
InitializeComponent();

ccTask = new CameraCaptureTask();
}

private void btnCamera_Click(object sender, RoutedEventArgs e)
{
ccTask.Show();
}


Now practically the camera application is invoked and with the inbuilt options we can capture the
picture. To save the picture, we need to have a mechanism which can be done with the help of
CameraCaptureTask Completed args. To do that, first let us write some code to get the captured
image and assign it to the image viewer control and then we will see when to trigger this option.
Write the code below in a separate method which gets the PhotoResult and decodes it to a byte
array to be shown on the image viewer control.

C# Code:
private void ccTaskCompleted(object sender, PhotoResult pr)
{
byte[] imgLocal;
if (pr.ChosenPhoto != null)
{
imgLocal = new byte[(int)pr.ChosenPhoto.Length];
pr.ChosenPhoto.Read(imgLocal, 0, imgLocal.Length);
pr.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);

var bitmapImage = PictureDecoder.DecodeJpeg(pr.ChosenPhoto);
this.imgCaptured.Source = bitmapImage;

}
}


Now we are done with our code to show the captured image in the ImageViewer control
(imgCaptured). Now to trigger this code so that the image captured can be retrieved, we need to do
this at the CameraCapturedTask completed event. To do that, we need to go back to the MainPage
constructor at the top and add the code below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 60
C# Code:
public MainPage()
{
InitializeComponent();

ccTask = new CameraCaptureTask();
ccTask.Completed += ccTaskCompleted;
}


So the CameraCaptureTask completed will trigger the method to do the necessary steps to show the
image in the image control. Now we are ready to build and check the output of the application. To
do that, press F5 directly from the keyboard or by pressing the build and execute option from the
Visual Studio Tool Bar. Once the application is built and executed successfully, we can see the output
in the Windows Phone 7 Emulator as shown below.


Now to invoke the camera, click on the InvokeCamera button and we can see the Camera
Application is invoked. We will see an empty screen with the camera buttons, as shown in the screen
below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 61

Now click on the button at the top right corner so that we can capture some image using the
Windows Phone 7 emulator. Since we are using the emulator, we will see a white screen with a
rectangle in it. We can click on the Accept button at the bottom to capture the image, as shown in
the screen below. If we want to take a new image, we can click on Retake to capture again.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 62

Now click on the Accept button and we can see the image captured is assigned to the image viewer
control on the main page, as shown in the screen below. We can see a dull image since we are using
the Windows Phone 7 emulator; if we deploy the application on to the real device we can get a very
good resolution of the picture.




Summary
In this chapter we have seen how to use a Camera Application to capture images and use them in
the development of our application, as per the requirements. Also, we have seen the Launchers and
Choosers CameraCaptureTask to build the application to capture the picture.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 63
Working with Panorama Control

Introduction
In this chapter, we are going to see the very interesting Panorama Control in Windows Phone 7.
Panorama controls are used to slide through big content without having to completely hide the
previous content. We can consider sliding through a horizontal page with different contents and
blocks. We can use this Panorama control to show a rich user interface by dividing the contents to
different blocks and assigning different items horizontally.
Panorama controls are used to browse back and forth the page items within the specified content
block to get a rich user experience. The Panorama control is the base, which can contain
PanoramaItem controls, which will host individual contents. Basically, we will have only one
Panorama control within which we can have multiple PanoramaItem, to have contents blocked out
one by one.

The Panorama control can be added and configured directly from the XAML code or we can do it
programmatically. The control is layered into 4 layers as shown below.
Background This is the base layer, the background of the panorama control.
Title This is the top layer used to display the title of the page.
Header This layer is used to display the Panorama Item block title.
Content This layer will be used to show the Panorama Item content.

Ok its time for the demo, let us see steps involved in creating a Panorama control based application
and add some content to see the rich user interface experience it offers.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 64


Now we can see a beautiful interface with the default design and the background, shown below. We
will customize the application design in our next steps.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 65
First let us delete the default values and add the PanoramaItems and the data bindings one by one.
Go to the XAML code and select the tag <controls:PanoramaItem>. We can see 2 items, just select
the complete code and delete it. We can now see the screen looks empty, as shown in the screen
below.



Now change the Panorama control Title and background. To do that, go to the XAML code and
change the Title to F5Debug and to change the background, let us add a new background to the
project solution and map the path to the ImageBrush tag, as shown in the code below. Once we are
done with the above 2 changes, we can see our screen looks like below.

XAML Code:
<controls:Panorama Title="f5debug wp7 tutorials">
<controls:Panorama.Background>
<ImageBrush ImageSource="Bcg1.jpg"/>
</controls:Panorama.Background>
</controls:Panorama>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 66


Now we need to add the PanoramaItems to the control. To do that, we need to add the code below,
containing the listing of data, as per the requirements. Here we have added 3 PanoramaItems
(Posts, Ebook and Comments) and a default grid on which we will be adding our controls to show to
the end user. Once we added the 3 items we can see our screen looks like below and the code will
appear as shown in the below listing.

XAML Code:
<controls:Panorama Title="f5debug wp7 tutorials">
<controls:Panorama.Background>
<ImageBrush ImageSource="Bcg1.jpg"/>
</controls:Panorama.Background>

<controls:PanoramaItem Header="Posts">
<Grid/>
</controls:PanoramaItem>

<controls:PanoramaItem Header="Ebook">
<Grid/>
</controls:PanoramaItem>

<controls:PanoramaItem Header="Comments">
<Grid/>
</controls:PanoramaItem>
</controls:Panorama>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 67


Now we need to add some controls to each of the items to show some information to the end users.
To add the controls, we can just drag and drop from the toolbox or by directly writing to the XAML
Code. Let us do some customization to get a good user experience with controls as shown in the
XAML Code below. Once we are done with our code we can see the screen looks like below.

XAML Code:
<controls:Panorama Title="f5debug wp7 tutorials">
<controls:Panorama.Background>
<ImageBrush ImageSource="Bcg1.jpg"/>
</controls:Panorama.Background>
<controls:PanoramaItem Header="Posts">
<Grid>
<Image Height="174" Source="f5Image.jpg" HorizontalAlignment="Left" Margin="78,47,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="254" />
<TextBlock Height="164" HorizontalAlignment="Left" Margin="22,275,0,0" TextWrapping="Wrap"
Name="textBlock1" Text="This is the F5debug blog posts sections, You can get the latest post
updates here!!!" VerticalAlignment="Top" Width="369" />
</Grid>
</controls:PanoramaItem>

<controls:PanoramaItem Header="Ebook">
<Grid>
<Image Height="310" Source="ssis-cover-page.jpg" HorizontalAlignment="Left" Margin="79,25,0,0"
Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="258" />
<TextBlock Height="92" HorizontalAlignment="Left" Margin="28,367,0,0" TextWrapping="Wrap"
Name="textBlock2" Text="SQL Server Integration Services (SSIS) Step by Step Tutorial Version 2.0"
VerticalAlignment="Top" Width="351" />
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 68
</Grid>
</controls:PanoramaItem>

<controls:PanoramaItem Header="Comments">
<Grid>
<TextBlock Height="206" FontSize="40" HorizontalAlignment="Left" Margin="82,121,0,0"
TextWrapping="Wrap" Name="textBlock3" Text="F5debug Comments Section"
VerticalAlignment="Top" Width="273" />
</Grid>
</controls:PanoramaItem>

</controls:Panorama>



Now we are done with our design and the coding section. To test our application, press F5 directly
from the keyboard or Build and Execute from the Visual Studio IDE toolbar. We can see the
application loaded into the Windows Phone 7 Emulator, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 69

Now scroll the screen horizontally and we can see the second Panorama items displayed to the user,
this basically avoids the loading of multiple pages which require single user interaction as shown in
the screen below.


Summary
In this chapter we have seen how to use the Panorama Control and to design a rich user interface by
adding items and changing the background to have a unique interface.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 70
Working with Pivot Control

Introduction

In this chapter, we are going to see how to use the Pivot Control in a Windows Phone 7 Application.
In our previous chapter, we have used the Panorama control to build a rich user interface. Using the
Pivot control we can easily maintain pages or data views without having the need of loading multiple
pages. We can easily filter large data sets into multiple pages. With this control, we can slide back
and forth and provide the end user with related data in a much easier view using any of the available
controls.

The Pivot control is the base application control and inside that we will have a Pivotitem control
where we can have multiple items inside a Pivot control. It is recommended to have one pivot
control within a page, which in turn can have multiple Pivotitems. The Pivot Control is layered into 2
layers; with each layer contains a Grid inside, as the layout root
Pivot Headers This layer is for showing the header title.
Pivot Items This layer is for showing a single Pivotitem to display data.

Let us see the steps involved in creating a Pivot control application for Windows Phone 7 using Visual
Studio 2010.


Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 71


We can see the Windows Phone 7 interface with the Pivot Control added in the screen below. Also,
we can see the default pivot items listed in the page which we can edit, as per the requirement




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 72
If we can see the XAML code, the pivot control is added by default with default pivot items. We can
delete the pivot items inside the pivot control and we can see the empty Pivot control. We will
customize it by adding our own PivotItems, let us do the same design which we did for the
Panorama sample. One difference, we do not have an option to change the background. Once we
add the default Pivot Items, we can see the screen looks like below.



Now we need to add some controls to each of the items to show some information to the end users.
To add the controls, just drag and drop from the toolbox or by directly writing XAML Code. Let us do
some customization to get a good user experience with the controls, as shown in the XAML Code
below. Once we are done with our code we can see the screen as shown below.

XAML Code:
<controls:Pivot Title="F5DEBUG WP7 TUTORIALS">

<controls:PivotItem Header="Post">
<Grid>
<Image Height="174" Source="f5.jpg" HorizontalAlignment="Left" Margin="78,47,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="254" />
<TextBlock Height="164" HorizontalAlignment="Left" Margin="29,301,0,0" TextWrapping="Wrap"
Name="textBlock1" Text="This is the F5debug blog posts sections, You can get the latest post
updates here!!!" VerticalAlignment="Top" Width="369" />
</Grid>
</controls:PivotItem>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 73

<controls:PivotItem Header="Ebook">
<Grid>
<Image Height="310" Source="ssis-cover-page.jpg" HorizontalAlignment="Left" Margin="79,25,0,0"
Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="258" />
<TextBlock Height="120" TextWrapping="Wrap" HorizontalAlignment="Left" Margin="31,409,0,0"
Name="textBlock2" Text="SQL Server Integration Services (SSIS) Step by Step Tutorial Version 2.0"
VerticalAlignment="Top" Width="372" />
</Grid>
</controls:PivotItem>

<controls:PivotItem Header="Comments">
<Grid>
<TextBlock Height="206" FontSize="40" HorizontalAlignment="Left" Margin="82,121,0,0"
TextWrapping="Wrap" Name="textBlock3" Text="F5debug Comments Section"
VerticalAlignment="Top" Width="273" />
</Grid>
</controls:PivotItem>

</controls:Pivot>




Now we are done with our design and the coding section. To test our application, press F5 directly
from the keyboard or Build and Execute from the Visual Studio IDE toolbar and we can see the pivot
control application loaded into the Windows Phone 7 Emulator as shown below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 74


Now we can directly click on the header title or scroll it horizontally to navigate to the second pivot
item, as shown in the screen below.


Summary
In this chapter, we have seen how to use the pivot control from scratch and design a good user
interface that looks similar to the Panorama control but with some differences which we have seen
in the output.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 75
Working with Media

Introduction
In this chapter, we are going to see how to use the media framework, which helps application
developers to stream video and audio files and to use the integrated Music and Video Hubs to select
media files. In our previous chapters, we have seen the different controls to design a rich user
interface application and in this topic we will see much more interesting aspects on handling media
files which will be very effective for using a Mobile device.

Media in Windows Phone 7 uses the MediaElement API to incorporate the audio and video files
using the inbuilt device media player in Silverlight for Windows Phone 7. In this chapter we will see
how to play a video file using the MediaElement API.

Let us see the steps involved in Media development in Windows Phone 7 applications using the
MediaElement API.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application project by
providing a valid project name, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 76

Now let us customize the Mainpage.xaml by adding a button control and a MediaElement to play the
video file, as shown in the screen below. Also we have customized the header grid to have a unique
design for the chapters in this book.

XAML Code:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Play Video" Height="72" HorizontalAlignment="Left" Margin="12,30,0,0"
Name="button1" VerticalAlignment="Top" Width="427" />
<MediaElement Height="356" HorizontalAlignment="Left" Margin="34,144,0,0"
Name="mediaElement1" VerticalAlignment="Top" Width="386" />
</Grid>



Now let us add a sample video file to the project, which we will load on the click of a button. We
have added a sample .WMV file to the root folder of the project. Once we have added the file, go to
the button click event (Play Video button) and write the code below to stream the video file, as
shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 77
XAML Code:
<phone:PhoneApplicationPage
x:Class="F5debugWp7Media.MainPage"
xmlns="<a
href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.micros
oft.com/winfx/2006/xaml/presentation"</a>
xmlns:x="<a
href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winf
x/2006/xaml"</a>
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="<a
href="http://schemas.microsoft.com/expression/blend/2008&quot;">http://schemas.microsoft.com
/expression/blend/2008"</a>
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-
compatibility/2006&quot;">http://schemas.openxmlformats.org/markup-compatibility/2006"</a>
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all 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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="video player" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Play Video" Height="72" HorizontalAlignment="Left" Margin="12,30,0,0"
Name="button1" VerticalAlignment="Top" Width="427" Click="button1_Click" />
<MediaElement Height="356" HorizontalAlignment="Left" Margin="34,144,0,0"
Name="mediaElement1" VerticalAlignment="Top" Width="386" />
</Grid>
</Grid>

</phone:PhoneApplicationPage>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 78

C# 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 F5debugWp7Media
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
mediaElement1.Source = new Uri("Bear.wmv", UriKind.Relative);
mediaElement1.Play();
}

}
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 79


Now we are done with our code. Let us build and execute the application by pressing the F5 button
from the keyboard or by selecting the Build and Execute option from the toolbar. We can see the
output of the application shown in the screen below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 80
Now we can see the video streaming, with the option to restart and reset the video at any point of
time. We can also customize it to select the file randomly and play as we normally do using the
playlist, which we will see in depth in our upcoming chapters.

Summary
In this chapter, we have seen how to use the Media Element to stream video files and use it
effectively. Also we have seen the different options to restart, reset the videos to make it user
friendly.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 81
Working with Toast Notifications

Introduction

In this chapter, we are going to see how to use Toast Notifications in Windows Phone 7. Windows
Phone 7 application development supports push notifications, which provides developers a much
more convenient option to transfer message to a Windows Phone 7 device from a web service
whenever a new event occurs. Push notifications are of 3 types, which are as follows
Toast Notification This notification is launched at the top of the screen with a custom
message such as an email alert or weather alert. The notification will be displayed for 10
second unless the user dismisses the alert. If the user clicks on the alert then the application
which sends the notification will be launched
Tile Notification This notification is used to display a dynamic representation of the
application state. We can control the image, text and badge count of the notification.
Raw Notification This notification is used only when the application is running on the
foreground and if the application services are running in background. The notification will
not be delivered and it gets discarded which is not delivered to the Windows Phone device.

We will see each notification in depth and see a demo application for each notification in our
upcoming chapters. Let us see the step by step process on how to create a TOAST application; we
need to create a client application to send the notification to the device which we will be covering in
this chapter.

Steps
Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7
application with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 82


Now add a button to create the push channel, which will be required to create a Toast notification.
If there are any already available notification events available, it will use the same or else it will
create a new notification event and then connect through the channel. Add the below XAML code to
get the channel notification to trigger.

XAML Code:
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Toast Notification" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left"
Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click"
/>
</Grid>
</Grid>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 83

Now we need to go to the code behind and start the process of establishing the Notification channel
to get the event trigger. To do that, we first need to add the below two using statements.

using Microsoft.Phone.Notification;
using System.Diagnostics;


Now we need to write the code to get the open channel details, which will be used to send the Toast
Notification. To do that, we will use the output window to get the channel details. Use the code
given below in the code behind for creating the channel.

private void getChannelURI(Uri value)
{
Dispatcher.BeginInvoke(() =>
{
Debug.WriteLine("URI: " + value.ToString());
});

Debug.WriteLine("URI: " + value.ToString());
}

Now we need to handle the BindToShellToast of HttpNotificationChannel to bind the toast
notifications. To do that, add the code below.

private static void ShellBinding(HttpNotificationChannel httpChannel)
{
try
{
httpChannel.BindToShellToast();
}
catch (Exception)
{
//Catach if required.
}
}

Now we need to add the code below to check if the application is running correctly and get the toast
notification message in order to log it for administration purposes.

void Channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 84
Debug.WriteLine("Toast Notification Received!!!");
if (e.Collection != null)
{
Dictionary collection = (Dictionary)e.Collection;
System.Text.StringBuilder messageBuilder = new System.Text.StringBuilder();
}
});
}

void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
getChannelURI(e.ChannelUri);
}


Now we need to have a method which will do the channel setup step by step. First it will check if the
channel is already available; if it is available, we need to check if the channel is null. If null then we
need to close the channel and open a new channel. Initially if the channel is not available then we
can directly create the HttpNotificationChannel and do the process to create the channel, as shown
in the screen below.

private void ChannelSetup()
{
HttpNotificationChannel httpChn = null;
string chnName = "Channel0";

httpChn = HttpNotificationChannel.Find(chnName);

if (httpChn != null)
{
if (httpChn.ChannelUri == null)
{
httpChn.UnbindToShellToast();
httpChn.Close();
ChannelSetup();
return;
}
else
{
getChannelURI(httpChn.ChannelUri);
}
ShellBinding(httpChn);
}
else
{
httpChn = new HttpNotificationChannel(chnName);
httpChn.ChannelUriUpdated += new EventHandler(ChannelUriUpdated);
httpChn.ShellToastNotificationReceived += new
EventHandler(Channel_ShellToastNotificationReceived);
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 85
httpChn.Open();
ShellBinding(httpChn);
}
}

Now we need to call the above method on the button click event, as shown in the screen below.

private void button1_Click(object sender, RoutedEventArgs e)
{
ChannelSetup();
}


Now we are done with the Windows Phone 7 client notification application. We will check by
building and executing the application and we can see the Windows Phone 7 Emulator, as shown in
the screen below.



Now click on the Establish Channel button, which will establish the channel and we can see the
channel URI in the Output window, since we have coded to get the channel details. To get to the
output window, just go to the Visual Studio toolbar and select View > Output window and we can
see the output window, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 86


Now copy and keep the channel details on a separate notepad. We need to create a Server to post
the toast notifications to the application device.
We will create a web page from which we will post the toast notifications and get the notification
onto the Windows Phone 7 device. To start with, first create an ASP.NET Web application in C#, as
shown in the screen below.



Now add the design code below to the ASPX page so that we will get the same look and feel for this
tutorial. Here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI and
notification message) and a button to trigger the event for the toast message to be sent to the
Windows Phone 7 Device.

ASPX Code:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="F5debugWp7ToastNotificationServer._Default" %>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 87
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
}
.style3
{
width: 690px;
}
.style4
{
width: 143px;
}
.style5
{
width: 38px;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table>
<tr>
<td colspan="3">
<asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="Large" Text="F5Debug Windows
Phone 7 Toast Notification"></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Channel URI"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" Width="661px"></asp:TextBox>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 88
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Label ID="Label3" runat="server" Text="Notification Title"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Label ID="Label4" runat="server" Text="Notification SubTitle"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server" Width="659px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 89
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Button ID="Button1" runat="server" Font-Bold="True"
onclick="Button1_Click" Text="Send Notification" Width="134px" />
</td>
<td>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
</table>
</asp:Content>



Now go to the code behind and add the code below. This code will get the user inputs, mainly the
Channel URI, and pass the message to the Microsoft Push Notification services. Just copy the code
below to proceed further.

Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 90
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;

namespace F5debugWp7ToastNotificationServer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
string PushNotificationXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification
xmlns:wp=\"WPNotification\">" + "<wp:Toast>" + "<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" + "</wp:Toast>" + "</wp:Notification>";

string strChannelURI = TextBox1.Text.ToString();
string strNotifitcationTitle = TextBox2.Text.ToString();
string strNotifitcationsubTitle = TextBox3.Text.ToString();

if (strChannelURI == string.Empty || strNotifitcationTitle == string.Empty || strNotifitcationsubTitle
== string.Empty)
{
lblresult.Text = "All the fields are Mandatory!!!";
return;
}

HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(strChannelURI);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
string str = string.Format(PushNotificationXML, strNotifitcationTitle, strNotifitcationsubTitle);
byte[] strBytes = new UTF8Encoding().GetBytes(str);
sendNotificationRequest.ContentLength = strBytes.Length;
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(strBytes, 0, strBytes.Length);
}
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

lblresult.Text = "Status: " + notificationStatus + " : " + deviceConnectionStatus;
}
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 91
}
}

Now run the Windows Phone 7 Toast notification application to get the channel URI. Once we get
the channel URI, keep the application running in the background and navigate to the home page of
the Windows Phone 7 Application. Now run the Server application
(F5debugWp7ToastNotificationServer) and enter the details, as shown below.


Now click on the Send Notification button and navigate to the Windows Phone 7 Emulator to see the
Toast Notification Message on the top, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 92


Summary
In this chapter we have seen what a Push Notification is in Windows Phone 7 and the types of
notification available. Also we have seen how to send a Toast Notification in detail.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 93
Working with Tile Notifications

Introduction

In this chapter, we are going to see how to work with the Tile Notification, which is one of the
Microsoft Push Notification Services available. In our previous chapter, we have seen how to use the
Toast Notification service to create a channel and send toast messages to a Windows Phone 7
Device. In this exercise, we will follow the same process and see the steps to create the channel and
send Tile notification messages.

Tile Notifications are used to show up to date status of an application on the Windows Phone 7 start
screen as a tile. This will work only if the application is pinned to the start screen. Basically we can
see 3 types of information on the Tile Notifications, as follows
Count We can call this a Badge, is an integer value between 0 and 99. We can specify the
count, as per the requirements, which can be updated on the notifications
Background Image An image property which will display the images as the background for
the tile.
Title Title of the application, which should normally be within 15 characters; exceeding 15
characters will be truncated automatically.

The tile images can be .jpg or .png files and should be of 173 X 173 pixels to have a better
appearance. If it is less than the specified pixels, it will be stretched automatically and the look and
feel will suffer. Let us see the step by step process on how to achieve these tasks.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 94


Now let us start designing the interface to create a channel. As we discussed in our previous chapter,
we will create the channel first, which will be required to communicate for the Tile Notifications. If
there are already notification events available, it will use the same or else it will create a new
notification event and then connect through the channel. Add the below XAML code to get the
channel notification to trigger.

XAML Code:
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Tile Notification" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left"
Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click"
/>
</Grid>


Now we need to go to the code behind and start the process of establishing the Notification channel
to get the event trigger. To do that, we need to add the below two using statements.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 95
using Microsoft.Phone.Notification;
using System.Diagnostics;

Now we need to write the code to get the open channel details, which will be used to send the Tile
Notification. To do that, we will use the output window to get the channel details. Copy the code
below to the code behind page. Also, we need to have a method which will do the channel setup. It
will first check if the channel is already available; if it is available, we need to check if the channel is
null, if null we need to close the channel and open a new channel. Initially, if the channel is not
available then we can directly create the HttpNotificationChannel and perform the process to create
the channel, as shown in the screen below.

private void ChannelSetup()
{
HttpNotificationChannel pushtileChannel;
string strchannelName = "Channel0";

pushtileChannel = HttpNotificationChannel.Find(strchannelName);
if (pushtileChannel == null)
{
pushtileChannel = new HttpNotificationChannel(strchannelName);

pushtileChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushtileChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

pushtileChannel.Open();
pushtileChannel.BindToShellTile();
}
else
{
pushtileChannel.ChannelUriUpdated += new
EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushtileChannel.ErrorOccurred += new
EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

System.Diagnostics.Debug.WriteLine(pushtileChannel.ChannelUri.ToString());
Debug.WriteLine(String.Format("URI : {0}",
pushtileChannel.ChannelUri.ToString()));
}
}

void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{

Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 96
Debug.WriteLine(String.Format("URI : {0}",
e.ChannelUri.ToString()));
});
}

void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
Dispatcher.BeginInvoke(() =>
Debug.WriteLine(String.Format("Tile Notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}


Now we need to call the above method on the button click event, as shown in the screen below.

private void button1_Click(object sender, RoutedEventArgs e)
{
ChannelSetup();
}


Now we are done with the Windows Phone 7 client notification applications. We will check by
building and executing the application and we can see the Windows Phone 7 Emulator, as shown in
the screen below.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 97
Now click on the Establish Channel button, which will establish the channel and we can see the
channel URI in the Output window, since we have coded to get the channel details. To get the
output window just go to the Visual Studio toolbar and select View > Output Window and we can
see the output window, as shown in the screen below.


Let us copy and keep the channel details on a separate notepad. We need to create a Server to post
the tile notifications to the application device to show the title.

Now we need to create a background image with 173 X 173 pixels, as shown in the screen below,
and add it to the project solution. Note that we need to change the Build Action from Resource to
Content, as shown below.




We will create a web page from which we will post the tile notifications on to the Windows Phone 7
device. To start with, first create an ASP.NET Web application in C#, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 98


Now add the design code below to the ASPX page so that we will get the same look and feel for this
tutorial. Here we have added 4 labels and 4 textboxes to get the user inputs (Channel URI, Front tile
message, Background and Notification txt) and a button to trigger the event for the tile message to
be sent to the Windows Phone 7 Device. Just copy and paste the ASPX code below.

ASPX Code:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="F5debugWp7TileNotificationServer._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
}
.style3
{
width: 690px;
}
.style4
{
width: 143px;
}
.style5
{
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 99
width: 38px;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table class="style1">
<tr>
<td colspan="3">
<asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="Large" Text="F5Debug
Windows Phone 7 Tile Notification"></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
&nbsp;</td>
<td class="style3">
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Notification URI"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtNotURI" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
&nbsp;</td>
<td class="style3">
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
<asp:Label ID="Label5" runat="server" Text="Notification Front Tile"></asp:Label>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 100
</td>
<td class="style3">
<asp:TextBox ID="txtNotFrontTile" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td class="style4">
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td class="style4">
<asp:Label ID="Label3" runat="server" Text="Notification Background"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtNotBck" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
&nbsp;</td>
<td class="style3">
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
<asp:Label ID="Label4" runat="server" Text="Notification Count"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtNotCount" runat="server" Width="659px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 101
<tr>
<td class="style5">
&nbsp;</td>
<td>
&nbsp;</td>
<td class="style3">
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style5">
&nbsp;</td>
<td>
<asp:Button ID="btnSendNote" runat="server" Font-Bold="True"
onclick="Button1_Click" Text="Send Notification" Width="134px" />
</td>
<td>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
</table>
</asp:Content>



Now go to the code behind and add the code below. This code will get the user inputs, mainly the
Channel URI, background and the tile information and pass the message to the Microsoft Push
Notification services. Just copy the code below to proceed further.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 102

Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;

namespace F5debugWp7TileNotificationServer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
string PushNotificationXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification
xmlns:wp=\"WPNotification\">" + "<wp:Tile>" +
"<wp:BackgroundImage>" + txtNotBck.Text + "</wp:BackgroundImage>" + "<wp:Count>" +
txtNotCount.Text + "</wp:Count>" + "<wp:Title>" +
txtNotFrontTile.Text + "</wp:Title>" + "</wp:Tile> " + "</wp:Notification>";

string strChannelURI = txtNotURI.Text.ToString();
string strNotificationBackground = txtNotBck.Text.ToString();
string strNotifitcationCount = txtNotCount.Text.ToString();
string strNotifitcationFronttile = txtNotFrontTile.Text.ToString();

if (strChannelURI == string.Empty || strNotificationBackground == string.Empty ||
strNotifitcationCount == string.Empty || strNotifitcationFronttile == string.Empty)
{
lblresult.Text = "All the fields are Mandatory!!!";
return;
}

HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(strChannelURI);
sendNotificationRequest.Method = "POST";

byte[] notificationMessage = Encoding.Default.GetBytes(PushNotificationXML);

// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 103
sendNotificationRequest.Headers.Add("X-NotificationClass", "1");

using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}

// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
lblresult.Text = "Status: " + notificationStatus + " | " + deviceConnectionStatus + " | " +
notificationChannelStatus;
}
}
}


Now we are done with our server code. To test tile notification, first run the Windows Phone 7
application (F5debugWp7TileNotification) and get the Channel URI. Once we got the URL, click on
the Back button and navigate to the application list. Pin our application F5debugWp7TileNotification
by pressing continuously holding down the mouse pointer and we can see the context menu, as
shown in the screen below.


Now select pin to start from the menu and we can see the application is pinned to the Tile, in the
screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 104

Now run the F5debugWp7TileNotificationServer web application and enter the values, as shown in
the screen below.



Now click on the Send Notification button and we can see the result in the label at the bottom, as
shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 105



Now go to the Windows Phone 7 Emulator and we can see the Tile notification message which we
sent from the web application, in the screen below.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 106

Summary
In this chapter, we have seen how to use the Tile Notifications to send live updates to the Windows
Phone 7 devices to update the primary tile. In our upcoming chapters we will see how to do the
secondary tiles and see the raw notification process as well.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 107
Working with Raw Notifications

Introduction
In this chapter, we are going to see how to use Raw Notifications to send messages. In our earlier
chapters, we have seen how to use Toast and Tile notifications to send messages, as per the
requirements. Raw Notifications are not like the TOAST and TILE notification; these notifications are
generated by the application itself or from a web service. The application needs to be up and
running in order to receive these notifications. If the application is not running then the message will
be discarded and we will get an error for the notification.

Let us see the steps involved in using the Raw Notification Mechanism to do notifications. Unlike the
Tile, we will not have a good looking image to show the notification rather we will try to catch the
notification to a message box.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 108

Now let us start designing the interface to create a channel, as we discussed in our previous
chapters. We will create the channel first, which will be required to communicate for the Raw
Notifications. If there are any notification events already available, it will use the same, or else it will
create a new notification event and then connect through the channel. Add the below XAML code to
get the channel notification to trigger.

XAML Code:
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Raw Notification" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left"
Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click"
/>
</Grid>
</Grid>


Now we need to go to the code behind and start the process of establishing the Notification channel
to get the event trigger. To do that, we first need to add the below two using statements.

C# Code:
using Microsoft.Phone.Notification;
using System.Diagnostics;

Now let us add the event handlers for sending the URI to the web service, to handle notification
errors and for receiving the raw notification, which is application specific, as shown in the below 3
event handler codes.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 109

C# Code:
void RawNotificationChannelURI(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
Debug.WriteLine(String.Format("URI : {0}", e.ChannelUri.ToString()));

});
}

void RawNotificationError(object sender, NotificationChannelErrorEventArgs e)
{
Dispatcher.BeginInvoke(() =>
Debug.WriteLine(String.Format("Notification {0}. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}

void RawNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string strRawMessage;

using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
strRawMessage = reader.ReadToEnd();
}

Dispatcher.BeginInvoke(() =>
Debug.WriteLine(String.Format("Raw Notification {0}:\n{1}",
DateTime.Now.ToShortTimeString(), strRawMessage)));
}


Now we need to write the code to get the open channel details, which will be used to send the Raw
Notification. To do that, we will use the output window to get the channel details. Copy the code
below to the code behind page. Also, we need to have a method which will perform the channel
setup. It will first check if the channel is already available; if it is available, we need to check if the
channel is null. If it is null, then we need to close the channel and open a new channel. Initially, if
the channel is not available, then we can directly create the HttpNotificationChannel and perform
the process to create the channel, as shown in the screen below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 110
C# Code:
private void SetupChannel()
{
HttpNotificationChannel pushRawChannel;
string strRawchannelName = "RawChannel0";

pushRawChannel = HttpNotificationChannel.Find(strRawchannelName);

if (pushRawChannel == null)
{
pushRawChannel = new HttpNotificationChannel(strRawchannelName);

pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);
pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);
pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

pushRawChannel.Open();
}
else
{
pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);
pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);
pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

System.Diagnostics.Debug.WriteLine(pushRawChannel.ChannelUri.ToString());
Debug.WriteLine(String.Format("Channel Uri = {0}", pushRawChannel.ChannelUri.ToString()));

}
}


Now we need to call the above method on the button click event, as shown in the screen below.

C# Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
SetupChannel();
}


Now we are done with the Windows Phone 7 client notification application. We will check by
building and executing the application. We can see the application in the Windows Phone 7
Emulator in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 111


Now click on the Establish Channel button, which will establish the channel and we can see the
channel URI in the Output window, since we have coded to get the channel details. To get the
output window, just go to the Visual Studio toolbar and select View > Output window. We can see
the output window in the screen below.




Let us copy and keep the channel details on a separate notepad. Now we need to create a Server to
post the raw notifications to the application device. We will create a web page from which we will
post the Raw Notifications and get the notification. To start with, first create an ASP.NET Web
application in C#, as shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 112


Now add the design code below to the ASPX page so that we will get the same look and feel for this
tutorial. Here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI, Title and
Sub Title) and a button to trigger the event for the tile message to be sent to the Windows Phone 7
Device. Just copy and paste the ASPX code below.

ASPX Code:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="F5debugWp7RawNotificationServer._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
}
.style3
{
width: 690px;
}
.style4
{
width: 143px;
}
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 113
.style5
{
width: 38px;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table>
<tr>
<td colspan="3">
<asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="Large" Text="F5Debug Windows
Phone 7 Raw Notification"></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Channel URI"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 114
<td>
<asp:Label ID="Label3" runat="server" Text="Notification Title"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Width="661px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Label ID="Label4" runat="server" Text="Notification SubTitle"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server" Width="659px"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Button ID="Button1" runat="server" Font-Bold="True"
onclick="Button1_Click" Text="Send Notification" Width="134px" />
</td>
<td>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</td>
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 115
<td>
&nbsp;</td>
</tr>
</table>
</asp:Content>



Now go to the code behind and add the code below. This code will get the user inputs, mainly the
Channel URI, and the Raw Message information and pass the message to the Microsoft Push
Notification service.

C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;

namespace F5debugWp7RawNotificationServer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 116
}

protected void Button1_Click(object sender, EventArgs e)
{
try
{
string strChannelURI = TextBox1.Text.ToString();
HttpWebRequest sendRawNotification = (HttpWebRequest)WebRequest.Create(strChannelURI);

sendRawNotification.Method = "POST";

string strRawMessage = "<!--?xml version=\"1.0\" encoding=\"utf-8\"?-->" +
"" +
"" + TextBox2.Text.ToString() + "" +
"" + TextBox3.Text.ToString() + "" +
"";

byte[] notificationMessage = Encoding.Default.GetBytes(strRawMessage);

sendRawNotification.ContentLength = notificationMessage.Length;
sendRawNotification.ContentType = "text/xml";
sendRawNotification.Headers.Add("X-NotificationClass", "3");

using (Stream requestStream = sendRawNotification.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}

HttpWebResponse response = (HttpWebResponse)sendRawNotification.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

lblresult.Text = notificationStatus + " | " + deviceConnectionStatus + " | " +
notificationChannelStatus;
}
catch (Exception ex)
{
lblresult.Text = "Exception caught: " + ex.ToString();
}

}
}
}

Now we are done with our server code. To test the raw notification, run the Windows Phone 7
application (F5debugWp7RawNotification) and get the Channel URI, or make use of the URI which
we saved in our notepad. Note that the application should be running in order to get the notification
message.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 117
Now run the F5debugWp7RawNotificationServer web application and enter the values as shown in
the screen below.


Now click on Send Notification button and we can see the result in the label at the bottom, as shown
in the screen below.



Now go to the Windows Phone 7 Emulator and we can see the Raw Notification Message which we
sent from the web application in the Message Box in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 118



Summary
In this chapter, we have seen how to use the RAW Notification Mechanism to send and receive
notifications while the application is running in the foreground.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 119
Working with Tiles

Introduction

In this chapter, we are going to use how to use Tiles in our Windows Phone 7 development. In our
previous chapters, we have seen Push Notifications and the different types of Notifications available.
Here, we will see the different types of tiles available and also see the steps involved in creating a
tile for an application.

Tiles are nothing but linking an application to the home screen with some options to update the
status. Here we have 2 types of Tile development available:
Application Tile This type is used when the application is pinned to the Start screen by the
user for easy accessing with the application Icon in the application list. Clicking on the tile
will navigate directly to the application for easy accessibility.
Secondary Tile This type is basically created programmatically by the application based on
the user interaction. This type of Tile will be used to navigate to the application and can be
create only once. We need to use Create(Uri, ShellTileData) method to create a secondary
tile.

Let us see the steps on how to create the Application Tile and the Secondary Tile in detail.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 120


Let us create an application tile and see the properties that are to be assigned to create the tile.
Once the page is opened in Visual Studio 2010, add 2 buttons to trigger the Application Tile and
Secondary Tile respectively. Once we have customized the design we can see the UI, as shown in the
screen below.



Now let us add the code to trigger the Application tile. To do that, we need to go to the Application
Tile button click event and write the code below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 121

C# 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;
using Microsoft.Phone.Shell;

namespace F5debugWp7Tiles
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
ShellTile AppShell = ShellTile.ActiveTiles.First();
StandardTileData AppTile = new StandardTileData();
AppTile.Title = "F5debug";
AppTile.BackgroundImage = new Uri("RedTile.jpg", UriKind.Relative);
AppTile.Count= 10;
AppTile.BackTitle = "F5Debug Back";
AppTile.BackBackgroundImage = new Uri("BlueTile.jpg", UriKind.Relative);
AppTile.BackContent=" This is Back Content";
AppShell.Update(AppTile);
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 122


Now we will check if the application is building and executing correctly and the Application Tile is
pinning the application to start. To check, build and execute the application by pressing F5 directly
and we can see the application loaded to the Windows Phone 7 Emulator in the screen below.


Now click on the Application Tile button and we can see that application tile gets created on the
start screen. To check that, click on the Start button at the bottom and in the list view of the
applications select our application F5debugWp7Tiles and select pin to start. Now go back to the
main screen (Home) and we can see the tiles in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 123


Now that we are good with creating an Application Tile, let us start with creating a Secondary Tile.
To start with, first let us add a new page Page1.xaml and design it as shown in the screen below.

XAML Code:

<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Secondary Tiles" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="193" HorizontalAlignment="Left" Margin="71,146,0,0" Name="textBlock1"
FontSize="36" TextWrapping="Wrap" Text="This is Secondary Tile Application"
VerticalAlignment="Top" Width="293" />
</Grid>
</Grid>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 124


Now navigate to the MainPage.XAML and add the code below to the second button click event
(Secondary Tile). The code given below will create the tile and will pass on to Page1.xaml.
C# Code:
private void button2_Click(object sender, RoutedEventArgs e)
{
StandardTileData SecTitle = new StandardTileData();
SecTitle.Title = "F5Debug Sec Title";
SecTitle.BackgroundImage = new Uri("BlueTile.jpg", UriKind.Relative);
SecTitle.Count = 70;
var URINav = "/Page1.xaml?state=Sec Tile";
ShellTile.Create(new Uri(URINav, UriKind.Relative), SecTitle);
}


Now on Page1.xaml, we need to do some manipulation when clicking on the secondary tile. Here,
we are showing a sample page on page navigation, so we have not written any code on the
OnNavigatedTo event, as shown below.

C# Code:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 125
Now we are done with our code, just build and execute the project and we can see the screen with
the 2 buttons, as displayed in the screen below.


Now click on Secondary Tile and we can see the Secondary tile created, as shown in the screen
below.


Clicking on the secondary tile (F5Debug Sec Tile) will navigate to the Secondary Tile Page
(Page1.xaml), shown in the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 126



Summary
In this chapter we have seen what a Tile is and how to create a basic tile and to assign a tile with
basic properties. Also we have seen how to create a Secondary tile and use it on navigation, based
on purpose.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 127
Working with Launchers

Introduction
In this chapter, we are going to see what Launchers are and what the use of a Launcher is when
developing a Windows Phone 7 Application. Launcher, in Windows Phone 7, is an API used to launch
some of the built in applications from which the user can select some task. Once the user selects the
application, we can handle the task as per the most convenient option to do some manipulations as
per the task raised. Some of the examples of using the launchers are triggering a contact application
to select some contact information.
Launchers have some common steps to launch a particular application, as follows
Creating an instance of the task.
Setting the parameters to organize the task.
Calling the show method to invoke the task.
Let us see the list of Launchers available and the usage of each launcher tasks to get a clear idea on
when to use each task to get a better user experience.

Launchers Tasks:
SMS Compose Task This task is used to send a message from the application. We can
launch the SMS Composer of the Messaging application and we can optionally specify the
recipients, body etc to make it easy. The message composer screen will be opened along
with the default items and the message will not be sent until the Send button is clicked.
Email Compose Task This task is used to send an Email message from the application. This
task will launch the Email Composing screen with the option to load data which we can
specify as static or dynamic using our code. The Email will not be sent until the user presses
the Send button from the task.
Phone Call Task This task is used to make phone calls for the users within the application.
We can specify properties like calling number, name etc but until the call button is pressed
manually, the call will not be processed.
Web Browser Task Used to launch the web browser to open a specified URL mentioned
using the properties at run time.
Media Player Launcher Task This task is used to launch the Media Player and play some
media files of our choice, by selecting the media file or by playing them randomly. Also we
have options to make use of some of the properties like rewind, pause, forward etc to make
it an easy to use to control.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 128
Connection Settings Task This task is used to adjust the network settings by providing
options for the users to handle it based on necessary settings.
Bing Maps Directions Task This task is used to launch BING maps to get the direction of a
specified location, by providing the location details as a parameter.
Bing Maps Task This task is used to launch the BING maps application and search the
location within the map. We can use the inbuilt options within the task to ZOOM in and
ZOOM out.
Search Task This task is used to perform an online search of the content, which can be
used to search for the application which we develop. This task performs a general search for
the content which we specify, normally on BING.
Share Link Task This task is used to share some links to social networking sites. We can use
this task to launch from our application and share some links to the network.
Share Status Task This task is used to share our status message to social networking sites.
We can use this task to launch from our application and send status messages to different
social networking sites.
Marketplace Detail Task This task is used to launch the Marketplace client application and
displays the detailed information of a specific application which we want to look at. If no
application parameter is passed, it opens the default, the current application from which it
was called.
Marketplace Hub Task This task is used to launch the Marketplace hub within the
Marketplace client application to display the type of content which we are looking for.
Marketplace Review Task This task is used to launch the Marketplace application and
show the reviews page for the application from which the task was invoked.
Marketplace Search Task This task is used to search the Marketplace with some particular
content of application. Using this task launches the marketplace application with the
specified search filter options to select from the list of applications.
We will create an example on how to use one of the tasks. Now let us create a Phone Call task and
see how to launch the Phone application to make a call.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 129


Now let us add a button to invoke the PhoneCall Task and call a particular number. Write the code
given below on the click event of the button. Also note that we need to add the following using
Directive in order to use the PhoneCall task (using Microsoft.Phone.Tasks; )

XAML Code:
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Launchers" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Call Karthik!!!" Height="182" HorizontalAlignment="Left" Margin="80,89,0,0"
Name="button1" VerticalAlignment="Top" Width="292" Click="button1_Click" />
</Grid>
</Grid>


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 130

C# Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
PhoneCallTask pctask = new PhoneCallTask();
pctask.DisplayName = "Karthikeyan";
pctask.PhoneNumber = "+9196000000096";
pctask.Show();
}




Now we are done with the code. Build and execute the project by pressing F5 and we can see the
application opened in the Windows Phone 7 Emulator in the screens below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 131



Summary
In this chapter, we have seen what Launchers are in Windows Phone 7 development and the list of
Launchers available. Also, we have seen a sample on what the PhoneCallTask is and how to use it
practically within Windows Phone 7 application development.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 132
Working with Choosers

Introduction
In this chapter, we are going to see what Choosers are in Windows Phone 7 development and the
different type of chooser tasks available. In our previous chapter, we have seen what Launchers are
and the different tasks involved with launchers and a sample application on how to use Launchers.
Similarly here in this chapter we will see choosers in detail.

Chooser, in Windows Phone 7, is an API used to launch some of the built in applications, within
which the user can perform some task related to the application launched. Unlike launchers, here
using choosers we can perform some task and pass data to get the task completed as per the
requirement. Basically, the choosers will be supplied with some data and status to do some
manipulations accordingly. Some examples of using the choosers are selecting a particular photo
from the photo hub, saving a ringtone etc.
Choosers have some common steps to launch a particular application, as follows
Creating an instance of the task.
Identifying the callback method to run after the task completes.
Setting the parameters to organize the task.
Calling the show method to invoke the task.
Implementing the completed event handler to get the data and status.

Let us see the list of Choosers available and the usage of each and every chooser tasks to get a clear
idea on when to use each task to give a better user experience.

Chooser Tasks:
Email Address Chooser Task This task is used to launch the contact application to select a
particular contacts email address to do some manipulations within the application from
which this task is called.
Save Contact Task This task is used to launch the contact application in order to save the
contact details of a contact to the contact details section.
Save Email Address Task This task is used to launch the contact application in order to
save an email address of a contact to the contact details section.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 133
Save Phone Number Task This task is used to launch the contact application in order to
save a phone number to the contact details from the application which triggered this task.
Camera Capture Task This task is used to launch the in-built camera application to capture
a photo and use it with the application from which the task is called.
Game Invite Task This task is used to launch an invite screen for a multi player games
application. This invitation will be sent asynchronously so that the task makes use of the
invitation response to get connected for playing games across sessions.
Address Chooser Task This task is used to launch the contact application to select a
particular contacts physical address selected by the user to do some manipulations within
the application from which this task is called.
Photo Chooser Task This task is used to launch the Photo Chooser application from which
we can select a photo from the hub and use it for manipulations within the application from
which we can trigger this task.
Phone Number Chooser Task This task is used to launch the contact application to select a
particular contacts phone number to do some manipulations within the application from
which this task is called.
Save Ringtone Task This task is used to save an audio file as a ringtone to the systems
ringtone list if the audio file meets the requirement for it to be considered as a ringtone. This
task will launch the ringtone application and set the ringtone properties to be used within
the device profile or within some specific group or a contact.

We will create a small example on how to use one of the Chooser tasks. Let us create a Phone
number chooser application to select a contact and make a call.

Steps

Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 134


Now let us add a button to invoke the Phone Number Chooser task and call a particular contact
number. Write the code below on the click event of the button. Also note that we need to add the
following using Directive in order to use the PhoneNumberChooser task (using
Microsoft.Phone.Tasks; ). The PhoneNumberChooser Task invokes the contacts application to get
the selected contact from the user. The chooser works asynchronously so that the completed event
must be subscribed to, before launching the chooser. Once the chooser task returns the Phone
Number then the PhoneCallTask is used to make the phone call to the user selected Phone number,
as shown in the code.

XAML Code:
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Choosers" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 135
<Button Content="Choose Contact" Height="189" HorizontalAlignment="Left" Margin="74,85,0,0"
Name="button1" VerticalAlignment="Top" Width="297" Click="button1_Click" />
</Grid>
</Grid>

C# 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;
using Microsoft.Phone.Tasks;

namespace F5debugWp7Choosers
{
public partial class MainPage : PhoneApplicationPage
{
PhoneNumberChooserTask pnChooserTask;

// Constructor
public MainPage()
{
InitializeComponent();

pnChooserTask = new PhoneNumberChooserTask();
pnChooserTask.Completed += new EventHandler(pnChooserTask_Completed);
}

void pnChooserTask_Completed(object sender, PhoneNumberResult e)
{
PhoneCallTask phoneCallTask = new PhoneCallTask();
phoneCallTask.PhoneNumber = e.PhoneNumber;
phoneCallTask.Show();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
pnChooserTask.Show();
}
}
}
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 136



Now we are done with the code. Build and execute the project by pressing F5 and we can see the
application opened in Windows Phone 7 Emulator in the screens below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 137

Summary
In this chapter, we have seen what Choosers are in Windows Phone 7 development and the list of
Choosers available. Also, we have seen a sample on what the PhoneNumberChooser Task is and how
to use it practically within Windows Phone 7 application development.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 138
Working with Navigation


Introduction
In this chapter, we are going to see how Navigation works within Windows Phone 7 Development.
Navigating between pages in Windows Phone 7 is an important task in development of an
application, since we cannot design an application that fits into a single page. Navigation can be
done in two ways; one is to just pass between the pages to show the end user with detailed
information and second is to pass values from one page to other based on the user inputs to show
the details by passing parameters.

We can easily navigate between the pages with the options available. We have different Navigation
events available which can be overridden to be used to track any navigation that happens on the
page flow. Below are a list of navigation events available with Windows Phone 7, which can be used
on need basis, as explained below.
OnNavigatedTo: Triggered when the page is loaded.
OnNavigatingFrom: Triggered just before the page unload event, we can use this if we need
to stop the navigation.
OnNavigatedFrom: Triggered after the page is navigated.
OnBackKeyPress: Triggered when the user presses the Back Button

Let us see the steps involved in performing the two navigations in detail.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 139


Now let us add 2 pages to show how to navigate between the pages and also to pass parameters
and retrieve them in another page. To add the pages, just right click on the project name and click
on Add New Items and select Windows Phone Portrait Page, as shown in the screen below.


Now we have added 2 pages (NavPage1.xaml and NavPage2.xaml). Let us design the Mainpage.xaml
with 2 buttons to navigate on button click, as shown below. Just copy the xaml code provided below
to get the same look and feel.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 140
XAML Code:
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Navigation" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Navigation Without Parameters" Height="172" HorizontalAlignment="Left"
Margin="12,96,0,0" Name="button1" VerticalAlignment="Top" Width="437" Click="button1_Click"
/>
<Button Content="Navigation With Parameters" Height="172" HorizontalAlignment="Left"
Margin="11,298,0,0" Name="button2" VerticalAlignment="Top" Width="438" Click="button2_Click"
/>
</Grid>
</Grid>



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 141
Now let us write our code to navigate between the pages without passing parameters. Go to the
code behind and write the code given below on the button1 click event. Before that, we will just
make a small design change in NavPage1.xaml to have a good look and feel on the page by adding a
Textblock with a welcome message.
C# Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/NavPage1.xaml", UriKind.Relative));
}



Now we can build and execute the solution to check if we are good with the code. Once the build is
complete, let us go ahead with the second button navigation to pass some values from
MainPage.XAML to NavPage2.XAML. So write the code below in the button2 click event. Before that,
we will add 2 TextBlock to get the parameters, which we pass from MainPage.XAML.

C# Code:
private void button2_Click(object sender, RoutedEventArgs e)
{
string strParam1 = "Welcome Page";
string strParam2 = "Navigation with Parameters!!!";
NavigationService.Navigate(new Uri(string.Format("/NavPage2.xaml?Val1={0}&Val2={1}",
strParam1, strParam2), UriKind.Relative));
}
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 142


Now we need to go to NavPage2.XAML and write the code below to get the parameters and assign
them to the text block.

NavPage2.xaml.cs page:
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 F5debugWp7Navigation
{
public partial class NavPage2 : PhoneApplicationPage
{
public NavPage2()
{
InitializeComponent();
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 143
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{

string strvalue1 = NavigationContext.QueryString["val1"];

string strvalue2 = NavigationContext.QueryString["val2"];

textBlock1.Text = strvalue1.ToString() + strvalue2.ToString();

base.OnNavigatedTo(e);
}

}

}



Now build and execute the project by pressing F5. We can see the Windows Phone 7 Emulator
opened and we can see the end result in the screens below.





Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 144

Output Screens:




Summary
In this chapter, we have seen how to use Page Navigation with and without passing any parameter
values.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 145
Working with Web Browser Control


Introduction
In this chapter, we are going to see how to use the Web Browser control in Windows phone 7
development. The Web Browser control is used to access static content or web based content, based
on the development need. We can use this control in a number of ways in our Windows Phone 7
development, such as using it to dynamically generate HTML code and display it as a page or show a
static page saved in Isolated Storage. Let us see the steps involved in making use of the Windows
Phone 7 Web Browser control.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid
project name, as shown in the screen below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 146
Now we can see the Windows Phone 7 designer and XAML windows where we can start designing
our application. Let us start with dragging and dropping the Web Browser control from the Visual
Studio ToolBox. Resize it as shown in the screen below.


XAML Code:
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Web Browser" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser HorizontalAlignment="Left" Margin="9,121,0,0" Name="webBrowser1"
VerticalAlignment="Top" Height="475" Width="441" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="-4,22,0,0" Name="textBox1"
Text="TextBox" VerticalAlignment="Top" Width="380" />
<Button Content="Go" Height="72" HorizontalAlignment="Left" Margin="371,22,0,0"
Name="button1" VerticalAlignment="Top" Width="85" />
</Grid>


Now let us add our code behind to access a web site by providing the URL. We need to use the
Source property of the Web Browser Control to assign the URI to navigate to, on clicking of the
button. We also have an alternative approach of using the Navigate(URI) property to do the same
task, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 147
C# Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string strURI = textBox1.Text.ToString();

webBrowser1.Source = new Uri(strURI, UriKind.Absolute);

//webBrowser1.Navigate(new Uri(strURI, UriKind.Absolute));
}



Now let us run the application to check the output in the Windows Phone 7 Emulator. Press F5 to
build and execute the project and we can see the result, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 148


Now let us see how we can create a dynamic HTML page and map it to the web browser control to
load the content as a static page. Let us add a new page and add the web browser control to that, as
we did in our above steps. Once we have added the control to load the HTML, we can see that
screen looks like below.

XAML Code:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Web Browser" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser HorizontalAlignment="Left" Margin="9,6,0,0" Name="webBrowser1"
VerticalAlignment="Top" Width="441" Height="595" />
</Grid>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 149


Now let us add the code to load the HTML content using the WebBrowser_onloaded event as shown
in the code below. The code will take the static HTML content and load it in the web browser
control. Add the code below to the code behind of the page, which can load any static HTML page,
as per the requirement.

C# Code:
public WebBrowserPage2()
{
InitializeComponent();
webBrowser1.Loaded += WebBrowser_OnLoaded;
}

private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)
{
webBrowser1.NavigateToString("<html><head><meta name='viewport' content='width=480, user-
scalable=yes' /></head><body><h2>Welcome to F5debug!!!</h2><p>To get more updates visit
www.f5Debug.net</p></body></html>");
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 150


Now let us run the application and we can see the Web Browser control load the static HTML
content. To build and execute the application press F5 and we can see the output in the Windows
Phone 7 Emulator, as shown below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 151

Summary
In this chapter, we have seen how to use the Web Browser control within Windows Phone 7
application development and also the possible ways of using this control effectively.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 152
Working with Screen Orientation


Introduction
In this chapter, we are going to see about Screen Orientations in Windows Phone 7 Development. As
a Windows Phone 7 user, we can see screen orientations are pretty simple just by titling the device
and seeing the screen tilt with the device, but as a developer we have to handle much of the
orientations programmatically, as per the requirement. The built-in sensors play a major role when
using the screen orientations, for the developers to design the application, which looks easy to the
end user.

In Windows Phone 7 development, by default the screen is in Portrait mode and we have 3 types of
supported Screen Orientations, as below
Portrait
Landscape(Left)
Landscape(Right)

In order to use the orientation change within Windows Phone development, in the XAML page we
need to make use of the SupportedPageOrientation properties. We can make use of these
orientations in page level so that for each of the page we can specify a different orientation for
better usability. The properties of SupportedPageOrientation can be one of the below options
Portrait
Landscape
PortraitOrLandscape
Let us see the steps involved in using Windows Phone 7 screen orientation effectively.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 153

We can see a new Windows Phone 7 Application created with the designer windows and the XAML
window open. Now we can see the Orientations mentioned in the XAML code highlighted in the
screen below. By default, we can see the Orientation is specified as Portrait.

XAML Code:
SupportedOrientations="Portrait" Orientation="Portrait"


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 154

Now we will add some controls to have a good user look and feel, as shown in the screen. Once we
added the controls, your complete XAML code will look like the below listing where we can see
SupportedOrientaion=Portrait. Now run the application by pressing F5 and we can see the
application in Portrait orientation, as shown in the screen below.

XAML Code:
<phone:PhoneApplicationPage
x:Class="F5debugWp7Orientations.MainPage"
xmlns="<a
href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.micros
oft.com/winfx/2006/xaml/presentation"</a>
xmlns:x="<a
href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winf
x/2006/xaml"</a>
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="<a
href="http://schemas.microsoft.com/expression/blend/2008&quot;">http://schemas.microsoft.com
/expression/blend/2008"</a>
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-
compatibility/2006&quot;">http://schemas.openxmlformats.org/markup-compatibility/2006"</a>
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all 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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Orientations" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 155
<TextBlock Height="30" HorizontalAlignment="Left" Margin="41,47,0,0" Name="textBlock1"
Text="Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="143,27,0,0" Name="textBox1" Text=""
VerticalAlignment="Top" Width="307" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="41,125,0,0" Name="textBlock2"
Text="Age" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="143,105,0,0" Name="textBox2" Text=""
VerticalAlignment="Top" Width="307" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="41,203,0,0" Name="textBlock3"
Text="Address" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="143,183,0,0" Name="textBox3" Text=""
VerticalAlignment="Top" Width="307" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="41,281,0,0" Name="textBlock4"
Text="Mobile No" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="143,261,0,0" Name="textBox4" Text=""
VerticalAlignment="Top" Width="307" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="41,359,0,0" Name="textBlock5"
Text="City" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="143,339,0,0" Name="textBox5" Text=""
VerticalAlignment="Top" Width="307" />
<Button Content="Add" Height="72" HorizontalAlignment="Left" Margin="54,456,0,0"
Name="button1" VerticalAlignment="Top" Width="160" />
<Button Content="Clear" Height="72" HorizontalAlignment="Left" Margin="240,456,0,0"
Name="button2" VerticalAlignment="Top" Width="160" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>

Portrait Mode:


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 156
We can switch between the orientations right from the Emulator by clicking on the buttons shown in
the screen below.



Now let us change the Orientation in the XAML Code to Landscape, as shown in the code below and
run the application once again and see the application output in the screen below.

XAML Code:
x:Class="F5debugWp7Orientations.MainPage"
xmlns="<a
href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.micros
oft.com/winfx/2006/xaml/presentation"</a>
xmlns:x="<a
href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winf
x/2006/xaml"</a>
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="<a
href="http://schemas.microsoft.com/expression/blend/2008&quot;">http://schemas.microsoft.com
/expression/blend/2008"</a>
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-
compatibility/2006&quot;">http://schemas.openxmlformats.org/markup-compatibility/2006"</a>
mc:Ignorable="d" d:DesignWidth="728" d:DesignHeight="480"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Landscape" Orientation="Landscape"
shell:SystemTray.IsVisible="True">



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 157

Landscape:



We can also control the orientation from the code behind programmatically by using one of the code
snippets below, as per the requirements.

C# Code:
// Portrait Orientation
SupportedOrientations = SupportedPageOrientation.Portrait;
// Landscape Orientation
SupportedOrientations = SupportedPageOrientation.Landscape;
// For Lanscape and Portrait
SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;

Based on the application design and requirement, we can assign the orientation; customize it to
create a better look and feel.

Summary
In this chapter, we have seen the different screen orientations which can be used in Windows Phone
7 application development to create a good user experience.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 158
Working with BING Map Control

Introduction
In this chapter, we are going to see the most useful control in Windows Phone 7 development, yes
the BING Map Control. The BING Map Silverlight control for Windows Phone 7 combines the power
of Silverlight and Bing maps to get the best mapping experience for developers and the real users to
create a location based application.

The BING Map control in Windows Phone 7 application development is derived from the name
spaces Microsoft.Phone.Controls and Microsoft.Phone.Controls.Maps. Developers need to register
for a BING Map developers account to get the keys which are used in developing an application with
the Bing Maps. Here in this chapter we will see the steps involved in using BING Maps control and to
get the most enriching map applications.

Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid
project name, as shown in the screen below.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 159
Note To get the BING Map Keys, we need to register a BING Map account using the below URL
http://www.bingmapsportal.com/

Once we register with a valid Windows Live ID, we need to login again and go to the section Create
or View Keys under the My Account category



Now we will be requested to provide the application details listed below:
Application name: a valid application name
Application URL: a valid application URL to access
Application type: a valid application type to be selected from the list

Once we provided the details, we will be provided with the BING Maps key, as shown in the screen
below.



Now we need to go back to the F5debugWp7BingMapControl project and start designing the
application by dragging and dropping the BING Map control from the toolbox and some buttons, as
shown in the screen below.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 160
XAML Code:
<phone:PhoneApplicationPage
x:Class="F5debugWp7BingMapControl.MainPage"
xmlns="<a
href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.micros
oft.com/winfx/2006/xaml/presentation"</a>
xmlns:x="<a
href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winf
x/2006/xaml"</a>
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="<a
href="http://schemas.microsoft.com/expression/blend/2008&quot;">http://schemas.microsoft.com
/expression/blend/2008"</a>
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-
compatibility/2006&quot;">http://schemas.openxmlformats.org/markup-compatibility/2006"</a>
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="696"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" xmlns:my="clr-
namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"
Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all 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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Bing Maps" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<my:Map Height="523" CredentialsProvider="At7uQrXAsuZLAGFyv2pz6MGQ6-
EhRIqjd1l0zTto9HhHzV2VcClvIQBbumcUz74S" HorizontalAlignment="Left" Margin="6,6,0,0"
Name="map1" VerticalAlignment="Top" Width="444" />
</Grid>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 161
<shell:ApplicationBarIconButton IconUri="/Images/appbar.share.rest.png" Text="Road View"
Click="ApplicationBarIconButton_Click"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.feature.video.rest.png" Text="Aerial
View" Click="ApplicationBarIconButton_Click_1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="Zoom In"
Click="ApplicationBarIconButton_Click_2"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar.next.rest.png" Text="Zoom Out"
Click="ApplicationBarIconButton_Click_3"/>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>





Now we need to use the below using directive to start using the map properties in the code behind.
So add the code below, to the using list at the top.
C# Code:
using Microsoft.Phone.Controls.Maps;

We need to add the code below to the Road View and Aerial View button click events.

C# Code:
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
map1.Mode = new RoadMode();
}
private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
{
map1.Mode = new AerialMode();
}
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 162


Build and execute the application to check if the first 2 buttons are working as expected. Press F5 to
start building the project and we can see the application loaded in the Windows Phone 7 Emulator in
the screen below.


We can see a message Invalid Credentials: Sign up for a developer account at:
http://www.microsoft.com/maps/developers as shown in the screen above. To remove this message
we need to make use of the key which we got after registering with the Bing Maps website. To do
this, go to the XAML Code and add the key to the BING Maps section, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 163
XAML Code:
<my:Map Height="523" CredentialsProvider="Insert the KEY here" HorizontalAlignment="Left"
Margin="6,6,0,0" Name="map1" VerticalAlignment="Top" Width="444" />



Run the application again by pressing the F5 key and we can see the error message is removed and
the application in Aerial View and Road View, as shown in the screens below.


Now we will write our code to do the zooming for the maps. Write the code below in the respective
code behind to get Zooming in and out.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 164
C# Code:
private void ApplicationBarIconButton_Click_2(object sender, EventArgs e)
{
double dbZoom;
dbZoom = map1.ZoomLevel;
map1.ZoomLevel = ++dbZoom;
}

private void ApplicationBarIconButton_Click_3(object sender, EventArgs e)
{
double dbZoom;
dbZoom = map1.ZoomLevel;
map1.ZoomLevel = --dbZoom;
}



Now build and execute the project and we can see the Zoom in and Zoom out buttons are working
effectively, as shown in the screens below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 165


Now that we got the expected output as shown in the above screens, let us do an additional task of
pinning the location. Normally we need to do this while travelling using a map direction. To start
coding the PINNING option, first add the map1_MouseLeftButtonUp event and write the code
below, which will do the location pinning, as shown.

C# Code:
int intcount = 0;
private void map1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
intcount = intcount + 1;
Pushpin pn = new Pushpin();
pn.Location = map1.ViewportPointToLocation(e.GetPosition(sender as Map));
pn.Content = "Location" + intcount;

(sender as Map).Children.Add(pn);
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 166


Now that we are done with our code, let us build and execute the application by pressing F5. We can
see the expected output. Just use the Mouse Up to click on the location shown in the Windows
Phone 7 Emulator to pin the location, as shown in the screens below.


Summary
In this chapter, we have seen how to use the BING Map control effectively within Windows Phone 7
development to build a rich user interface.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 167
Working with Device Information

Introduction

In this chapter, we are going to see how to get the Device information for managing the device. We
will see how to make use of the Device detection APIs available in the Windows Phone 7 SDK to
detect the Device information, Memory detection, Keyboard installed or not etc, with the API.

To detect the device information, we are going to use the DeviceExtendedProperties class. We have
different options to get the information of the device, network etc.. with the API. We will see only
retrieving of the device information in this chapter. We are going to retrieve the below list of device
information.

S No Information Description
1 DeviceUniqueId Gets device Unique ID.
2 DeviceManufacturer Gets Device Manufacture details.
3 ApplicationCurrentMemoryUsage Gets Application Memory Usage.
4 ApplicationPeakMemoryUsage Gets Application Memory Leak Usage.
5 DeviceName Gets the Device Name.
6 DeviceFirmwareVersion Gets the Firmware Version.
7 DeviceHardwareVersion Gets the Hardware Version.
8 DeviceTotalMemory Gets the physical Memory RAM Usage.
9 Power Source Indicates if the device works with power or
battery.
10 Iskeyboardpresent Indicates if any physical keyboard is installed
with device
11 IsKeyboardDeployed Indicates if the user deploy the physical
keyboard
12 ApplicationMemoryUsageLimit Gets the maximum amount of memory.

Let us see steps for implementing the device information class to get the information and display it
to the end users.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 168
Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid
project name, as shown in the screen below.


Now let us start with our design to see the device information in one page. Once we are done with
the design, we can see that the screen looks like below. Copy the XAML code to get the same look
and feel. We can also directly drag and drop the controls from the toolbox and design it as per the
requirements.

XAML Code:
<phone:PhoneApplicationPage
x:Class="F5debugWp7DeviceInformation.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"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 169
<!--LayoutRoot is the root grid where all 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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Device Info" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,23,0,0" Name="ttDeviceInfo"
Text="F5debug - Device Information List" VerticalAlignment="Top" Width="438" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,76,0,0" Name="ttdeviceuniqueid"
Text="Device Unique ID:" VerticalAlignment="Top" Width="176" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,76,0,0"
Name="txtDeviceUniqueID" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,112,0,0" Name="textBlock4"
Text="Device Manufacturer:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,112,0,0"
Name="txtDeviceManufacturer" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,148,0,0" Name="textBlock6"
Text="Device Name:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,148,0,0" Name="txtDeviceName"
Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,184,0,0" Name="textBlock8"
Text="Firmware Version:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,184,0,0"
Name="txtFirmwareVersion" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,220,0,0" Name="textBlock10"
Text="Hardware Version:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,220,0,0"
Name="txtHardwareVersion" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,251,0,0" Name="textBlock12"
Text="Total Memory:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,251,0,0" Name="txtTotalMemory"
Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,287,0,0" Name="textBlock14"
Text="Current Memory:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,287,0,0"
Name="txtCurrentMemory" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,323,0,0" Name="textBlock16"
Text="Peak Memory:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,323,0,0" Name="txtPeakMemory"
Text="" VerticalAlignment="Top" Width="219" />
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 170
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,394,0,0" Name="textBlock18"
Text="Power Source:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,394,0,0" Name="txtPowerSource"
Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,430,0,0" Name="textBlock20"
Text="Keyboard Installed:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,430,0,0"
Name="txtkeyboardinstalled" Text="" VerticalAlignment="Top" Width="219" />
<Button Content="Get Details" Height="72" HorizontalAlignment="Left" Margin="46,520,0,0"
Name="button1" VerticalAlignment="Top" Width="359" Click="button1_Click" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,467,0,0" Name="textBlock3" Text=
"Keyboard Deployed:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,467,0,0"
Name="txtKeyboardDeployed" Text="" VerticalAlignment="Top" Width="219" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,359,0,0" Name="textBlock1"
Text="Maximum Memory:" VerticalAlignment="Top" Width="200" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="218,359,0,0"
Name="txtMaximuMemory" Text="" VerticalAlignment="Top" Width="219" />
</Grid>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 171


Let us start with our code to get the device information and load it to the respective text blocks as
shown in the code below. We can use the Device Status class to get the details of the device
properties except the device unique ID. We will write the code later to get the unique ID of the
device.

C# 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;
using Microsoft.Phone.Info;
using System.Windows.Threading;

namespace F5debugWp7DeviceInformation
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 172
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
txtCurrentMemory.Text = DeviceStatus.ApplicationCurrentMemoryUsage.ToString();
txtMaximuMemory.Text = DeviceStatus.ApplicationMemoryUsageLimit.ToString();
txtPeakMemory.Text = DeviceStatus.ApplicationPeakMemoryUsage.ToString();
txtTotalMemory.Text = DeviceStatus.DeviceTotalMemory.ToString();

txtDeviceManufacturer.Text = DeviceStatus.DeviceManufacturer.ToString();
txtDeviceName.Text = DeviceStatus.DeviceName.ToString();

txtFirmwareVersion.Text = DeviceStatus.DeviceFirmwareVersion.ToString();
txtHardwareVersion.Text = DeviceStatus.DeviceHardwareVersion.ToString();

txtKeyboardDeployed.Text = DeviceStatus.IsKeyboardDeployed.ToString();
txtkeyboardinstalled.Text = DeviceStatus.IsKeyboardPresent.ToString();

txtPowerSource.Text = DeviceStatus.PowerSource.ToString();

//txtDeviceUniqueID.Text = "";
}
}}



Now let us write the code for getting the Device Unique ID. We use the DeviceExtendedProperties
property TryGetValue to get the Unique ID, since we get it as a byte array, we do a conversion to a
string and assign it to the text block, as shown below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 173
C# 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;
using Microsoft.Phone.Info;
using System.Windows.Threading;

namespace F5debugWp7DeviceInformation
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
txtCurrentMemory.Text = DeviceStatus.ApplicationCurrentMemoryUsage.ToString();
txtMaximuMemory.Text = DeviceStatus.ApplicationMemoryUsageLimit.ToString();
txtPeakMemory.Text = DeviceStatus.ApplicationPeakMemoryUsage.ToString();
txtTotalMemory.Text = DeviceStatus.DeviceTotalMemory.ToString();

txtDeviceManufacturer.Text = DeviceStatus.DeviceManufacturer.ToString();
txtDeviceName.Text = DeviceStatus.DeviceName.ToString();

txtFirmwareVersion.Text = DeviceStatus.DeviceFirmwareVersion.ToString();
txtHardwareVersion.Text = DeviceStatus.DeviceHardwareVersion.ToString();

txtKeyboardDeployed.Text = DeviceStatus.IsKeyboardDeployed.ToString();
txtkeyboardinstalled.Text = DeviceStatus.IsKeyboardPresent.ToString();

txtPowerSource.Text = DeviceStatus.PowerSource.ToString();

//txtDeviceUniqueID.Text = "";
}
}
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 174


Now we are done with our code. Let us build and execute the application by pressing F5 directly
from the keyboard. We can see the application loaded to the Windows Phone 7 Emulator in the
screen below with the expected output.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 175

Summary
In this chapter, we have seen how to get the device information details and the device unique id
using the Device Status class in detail.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 176
Working with Themes

Introduction
In this chapter, we are going to see how to effectively use Themes in Windows Phone 7 application
development. As we all know, a theme is a set of resources which are used to maintain a consistent
look and feel for all the controls and resources used within a Windows Phone 7 Application.
Windows Phone 7 Themes play a major role when developing applications where color plays an
important role.

Some of the advantages of using Themes in Windows Phone 7 is consistency across the default
controls used within the application without adjusting some of the common properties like color,
fonts, styles etc. We can override the theme anytime at run time and in the application level without
doing many changes. Themes in Windows Phone 7 are a combination of a background and an accent
color. The background color is basically the background image color which we use in our application
and accent color is the one that is applied to the controls used within the application.

The Background color in Windows Phone 7 has 2 options, Light Color and Dark Color and as far as
Assent color is concerned, we have 10 options which we will see in detail in our upcoming chapters.
Windows Phone 7 Themes are selected using the Setting options, when the user selects the theme,
the complete application system gets changed, but when we change the theme, only the theme
related color changes occur within the application scope.

Theme resources are normally maintained in the TthemeResource.XAML file, the resources are
maintained based on the background color and the accent color selected by the user or the
developer. Theme resources files are available in the location below, based on the OS which we are
using.
64-bit DriveName\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Design
32-bit Drive\Program Fles\Microsoft SDKs\Windows Phone\v7.1\Design
Let us see the steps involved in using themes with Windows Phone 7 development.


Steps
Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid
project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 177


Now let us start with adding some colourful controls to the MainPage.XAML file and see how the UI
gets affected when changing the theme. Just copy the below XAML code or drag and drop the
controls from the toolbox and design the UI as shown in the screen below to get the same look and
feel.


XAML Code:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Themes" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Rectangle Height="235" HorizontalAlignment="Left" Margin="38,33,0,0" Name="rectangle1"
Stroke="{StaticResource PhoneForegroundBrush}" StrokeThickness="1" VerticalAlignment="Top"
Fill= "{StaticResource PhoneAccentBrush}" Width="163" />

<Rectangle Height="235" HorizontalAlignment="Left" Margin="259,33,0,0" Name="rectangle2"
Stroke="Aqua" StrokeThickness="1" VerticalAlignment="Top" Width="163"
Fill= "Aqua"/>

<Ellipse Height="253" HorizontalAlignment="Left" Margin="38,329,0,0" Name="ellipse1"
Stroke="{StaticResource PhoneForegroundBrush}" StrokeThickness="1" VerticalAlignment="Top"
Fill= "{StaticResource PhoneAccentBrush}" Width="163" />

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 178
<Ellipse Height="253" HorizontalAlignment="Left" Margin="259,329,0,0" Name="ellipse2"
Stroke="Beige" StrokeThickness="1" VerticalAlignment="Top" Width="163"Fill=
"DarkGreen"/></Grid>



In the above XAML code, we have added 2 Rectangles and 2 Eclipses to differentiate the usage of
themes in real time. The first Rectangle is designed to get the application resources details to fill the
shape border color and background color, whereas for the 2nd rectangle we have directly specified
the color without getting the color from the application resource. Similarly we have done the same
with the Eclipse as well, such that the first one uses the application resource and the second one is
directly assigned the color.

Now to tell the Windows Phone runtime environment to take care of the necessary changes for the
theme, add the code below to the MainPage.XAML.cs page constructor, as shown in the screen
below.

C# Code:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Themes" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Rectangle Height="235" HorizontalAlignment="Left" Margin="38,33,0,0" Name="rectangle1"
Stroke="{StaticResource PhoneForegroundBrush}" StrokeThickness="1" VerticalAlignment="Top"
Fill= "{StaticResource PhoneAccentBrush}" Width="163" />

<Rectangle Height="235" HorizontalAlignment="Left" Margin="259,33,0,0" Name="rectangle2"
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 179
Stroke="Aqua" StrokeThickness="1" VerticalAlignment="Top" Width="163"
Fill= "Aqua"/>

<Ellipse Height="253" HorizontalAlignment="Left" Margin="38,329,0,0" Name="ellipse1"
Stroke="{StaticResource PhoneForegroundBrush}" StrokeThickness="1" VerticalAlignment="Top"
Fill= "{StaticResource PhoneAccentBrush}" Width="163" />

<Ellipse Height="253" HorizontalAlignment="Left" Margin="259,329,0,0" Name="ellipse2"
Stroke="Beige" StrokeThickness="1" VerticalAlignment="Top" Width="163"
Fill= "DarkGreen"/>
</Grid>




We are done with our code and we will build and execute the application by pressing F5 directly.
We can see that the application loads in the Windows Phone 7 Emulator as displayed in the screen
below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 180



We can see the output shows different Color for the first rectangle and the first eclipse since we
have assigned the Application resource when a theme comes into the picture. Now let us change the
theme and see how the theme affects the images. Click on the Start button from the emulator and
go the application listing and select Settings and then theme options.

Now change the Background and the Accent Color and go back to the application to check the
output. We can see the Color again changes for the first rectangle and the first eclipse since they are
controlled with the application resource, as shown in the screens below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 181


Now on changing the themes we can see the complete Color shifting, as shown in the screens below.


Summary
In this chapter, we have seen what themes are in Windows Phone 7 development and the difference
between using a theme and not using theme when application resources are used in real time.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 182
Working with Isolated Storage


Introduction
In this chapter, we are going to see what an Isolated Storage is in Windows Phone 7 Development.
Isolated Storage is something which we have with Silverlight. In Windows Phone 7, Isolated Storage
is space provided to store data locally which is isolated from other applications. Each application can
have their own space (storage) so that other applications data cannot be shared within the
application which gives more security to the data. If we need to share the data then we can use
Azure storage or any other cloud medium to share the data between the applications.

In Windows Phone 7 Development Isolated Storage can be used in 3 different ways to store data
such as Storing data like Key-Value pair using the Files and Folders to store the data in separate
files, and lastly using relational data by using a local database. In the Windows Phone 7 Architecture,
all the files and folders are limited with access to the specific application itself, which prevents the
application from accessing other application data and vice versa. Out of the three types of data
storage we can store in Isolated Storage, File and Folder plays a vital role in Windows Phone 7
Application development, since we need to persist the user data locally in order to use it.

In this chapter, we will see how to use the Key Value Pair option to store and retrieve data using
Isolated Storage. This option uses the IsolatedStorageSettings Class to store the data.
IsolatedStroageClass provides an effective way to store the data in Key Value pairs in a local
IsolatedStorageFile. In Windows Phone 7 Application development, IsolatedStorageSettings is not
thread safe so the application throws an IsolatedStorageException when Save is invoked.
IsolatedStorageSetting class normally uses the 3 methods below to store and retrieve data with
isolated storage.
Add We can make use of this method to store data in the dictionary as key value pair.
Remove We can make use of this method to remove/delete data with a specified key.
Contains We can make use of this method to check if particular data is available or not
using the specified key.
Let us now see the steps involved in using the IsolatedStorageSetting class to store data in a key
value pair.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 183
Steps
Open Visual Studio 2010 IDE and Create a new Silverlight for Windows Phone 7 Application with a
valid project name, as shown in the screen below.


Now let us add some control to get the user input and save it to Isolated Storage. Also, we will add
some buttons to retrieve the data using the key and add one more button to delete the data using
the same key. So once we add our controls, we can see the page design, as shown in the screen
below.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 184
XAML Code:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="39" HorizontalAlignment="Left" Margin="12,67,0,0" Name="textBlock1"
Text="Data" VerticalAlignment="Top" Width="106" TextAlignment="Center" />
<TextBox Height="72" HorizontalAlignment="Right" Margin="0,42,17,0" Name="textBox1" Text=""
VerticalAlignment="Top" Width="347" />
<Button Content="Retrive" Height="72" HorizontalAlignment="Left" Margin="59,244,0,0"
Name="button1" VerticalAlignment="Top" Width="160" />
<Button Content="Delete" Height="72" HorizontalAlignment="Left" Margin="225,244,0,0"
Name="button2" VerticalAlignment="Top" Width="160" />
<Button Content="Save Data" Height="72" HorizontalAlignment="Left" Margin="59,166,0,0"
Name="button3" VerticalAlignment="Top" Width="326" />
<TextBlock Height="204" HorizontalAlignment="Left" Margin="73,355,0,0" Name="textBlock2"
Text="" VerticalAlignment="Top" Width="299" />
</Grid>


First we need to add the using directive to get the Isolated Storage class which is used to do the
manipulations within the application.

using System.IO.IsolatedStorage;


Now let us start writing our code to use the IsolatedStorageSettings class. We need to first create
an instance of the class and try to invoke the ADD Method to save the data.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 185

Code Behind:
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;
using System.IO.IsolatedStorage;

namespace F5debugWp7IsolatedStorage
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 186
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings ISSetting = IsolatedStorageSettings.ApplicationSettings;
if (!ISSetting.Contains("DataKey"))
{
ISSetting.Add("DataKey", txtSaveData.Text);
}
else
{
ISSetting["DataKey"] = txtSaveData.Text;
}
ISSetting.Save();
}
}
}

In the above code, we can see we have a key DataKey which is used to save the data which the user
types in the text block. We need to create an instance of the IsolatedStorageSettings and use the
instance to call the ADD method by passing the Key and the Value. Here we have provided some
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 187
validation to first check if the Key (DataKey) is already available or if the data key is not available, we
make use of the SAVE Method to save the data to the Isolated Storage.

Now let us write the code to retrieve the data using the key which we saved in the above code. Copy
the code below to the Retrieve button click event. To retrieve the data the key value pair is accessed
directly from the applicationsettings property of IsolatedStorageSettings, as shown in the screen
below.


Code Behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("DataKey"))
{
textBlock2.Text = "Key : DataKey || Value : ";
textBlock2.Text += IsolatedStorageSettings.ApplicationSettings["DataKey"] as string;
}
else
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 188
{
textBlock2.Text = "Key Not Found";
}
}
Finally, let us write the code to delete the data using the key (DataKey). Here also we need to use
the ApplicationSettings Property to access the data using the Key and delete it using the Remove
method, as shown in the screen below.



Code Behind:
private void button2_Click(object sender, RoutedEventArgs e)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("DataKey"))
{
IsolatedStorageSettings.ApplicationSettings.Remove("DataKey");
}
}


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 189

Now that we are done with the code, we can build and execute the project by simply pressing the F5
button from the keyboard or use the Toolbar to select the Build and Execute solution. Once the
application is built, we can see the application opened in the Windows Phone 7 Emulator, as shown
in the screen below. We can play around with the application by adding data and retrieving the data
using the key, which we assigned internally.

Output Screens:


Summary
In this chapter, we have seen what Isolated Storage is in Windows Phone 7 Development and we
have seen how to use Key Value Pairs to save and retrieve data effectively. In our upcoming
chapters, we will see how to use Files and Folders to save data in Isolated Storage.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 190
Working with Files and Folders

Introduction
In this chapter, we are going to see the most important topic on Windows Phone 7 Development,
which is Isolated Storage for Files and Folders. Typically any application development requires a
location to store the user data locally to manipulate. Here, with Windows Phone 7 development we
have Isolated Storage to store data in an isolated location which is accessible to that particular
application only. In our previous chapter, we have seen what Isolated Storage is and we have seen
how to use a dictionary to store data locally in a key value pair.
In this chapter, we are going to see how to perform the below tasks on Isolated Storage for Files and
Folders:
Write some text to a text file
Read the text file
Delete the text file
Write some text to a text file inside a folder
Read the text file inside a folder
Let us see the steps involved In using Files and Folders to store data locally with a Windows Phone 7
device.


Steps
Open Visual Studio 2010 as an administrator and create a new Silverlight for Windows Phone 7
project with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 191


The IsolatedStorageFileStream class is used in Windows Phone 7 Development to read, write and
create files in Isolated Storage. We can create an instance of this class to get the stream of an object
to read and write using the StreamReader and StreamWriter. To start, let us first design a unique
interface by using the controls from the toolbox. Once the design is completed, we can see the
screen, as shown below. Copy the XAML Code below to get the same look and feel.



XAML Code:
<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-->
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 192
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Files N Folder" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="15,41,0,0" Name="textBlock1"
Text="File Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="132,19,0,0" Name="txtFileName"
Text="" VerticalAlignment="Top" Width="304" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="15,105,0,0" Name="textBlock2"
Text="Folder Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="132,83,0,0" Name="txtFolderName"
Text="" VerticalAlignment="Top" Width="304" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="15,168,0,0" Name="textBlock3"
Text="File Data" VerticalAlignment="Top" />
<TextBox Height="149" HorizontalAlignment="Left" Margin="132,146,0,0" Name="txtFiledata"
Text="" VerticalAlignment="Top" Width="304" />
<Button Content="Save" Height="72" HorizontalAlignment="Left" Margin="9,357,0,0"
Name="button1" VerticalAlignment="Top" Width="220" Click="button1_Click" />
<CheckBox Content="Save in Root" Height="72" HorizontalAlignment="Left" Margin="-1,289,0,0"
Name="cbroot" VerticalAlignment="Top" />
<CheckBox Content="Save in Folder" Height="72" HorizontalAlignment="Right" Margin="0,289,45,0"
Name="cbfolder" VerticalAlignment="Top" />
<Button Content="Read" Height="72" HorizontalAlignment="Left" Margin="222,357,0,0"
Name="button2" VerticalAlignment="Top" Width="211" Click="button2_Click" />
<Button Content="Write to a Directory" Height="72" HorizontalAlignment="Left"
Margin="12,418,0,0" Name="button3" VerticalAlignment="Top" Width="421" Click="button3_Click"
/>
<Button Content="Read from a Directory" Height="72" HorizontalAlignment="Left"
Margin="12,478,0,0" Name="button4" VerticalAlignment="Top" Width="421" Click="button4_Click"
/>
<Button Content="Delete a file Permanently" Height="72" HorizontalAlignment="Left"
Margin="15,537,0,0" Name="button5" VerticalAlignment="Top" Width="421" Click="button5_Click"
/>
</Grid>
</Grid>

Now that we are done with the design, let us start with the code behind to write the core logic to
work with files and folders. First, we need to import the namespace required for Isolated Storage by
adding the below 2 namespaces to the code behind.

Code Behind:
using System.IO;
using System.IO.IsolatedStorage;
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 193
Task 1 Write text to a text file
Now our first task is to write some data to a text file and store it in isolated storage. We need to use
the IsolatedStorageFile class instance to get the user store for the specific application and to write
the file we need to use the IsolatedStorageFileStream by providing the parameters that are required
to store the file locally, as shown in the code below.



Code Behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
if (cbroot.IsChecked == true)
{
string strFilename = txtFileName.Text.ToString();
string strFileData = txtFiledata.Text.ToString();
IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication();
using (StreamWriter swfile = new StreamWriter(new IsolatedStorageFileStream(strFilename,
FileMode.Create, FileAccess.Write, ISFile)))
{
swfile.WriteLine(strFileData);
swfile.Close();
}
MessageBox.Show("File Saved!!!");
}
else
{
MessageBox.Show("Select the checkbox to save file in root or in a folder");
}
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 194
Task 2 Read the text file
Our next task is to read the text file from the root folder where we saved the text data in our
previous task. For this task, we again need to use the IsolatedStorageFile Class and
IsolatedStorageFileStream to get the data, as shown in the code below.



private void button2_Click(object sender, RoutedEventArgs e)
{
string strFilename = txtFileName.Text.ToString();

IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream ISFileStream = ISFile.OpenFile(strFilename, FileMode.Open,
FileAccess.Read);
using (StreamReader reader = new StreamReader(ISFileStream))
{
string strData = reader.ReadLine();
MessageBox.Show(strData.ToString());
}
}

Task 3 Delete the text file

In this task, we are going to see how to delete the text file from Isolated Storage which we created in
our previous tasks. To delete the file, we need to make use of the IsolatedStorageFile class and
invoke the DeleteFile method by passing the filename directly, as shown in the code below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 195
Also, to delete a folder, we can use the DeleteDirectory method which does a similar process of
deleting the directory completely.



Code Behind:
private void button5_Click(object sender, RoutedEventArgs e)
{
string strFilename = txtFileName.Text.ToString();

IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication();
ISFile.DeleteFile(strFilename);
}


Task 4 Write some text to a text file inside a folder

Our next task is to write some text to a text file and save the file to a specific folder for easy data file
maintenance within Isolated Storage. Normally, this task is very important for developing an
application with Windows Phone 7 to store data locally in a folder.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 196


Code Behind:
private void button3_Click(object sender, RoutedEventArgs e)
{
if (cbfolder.IsChecked == true)
{
string strFileName = txtFileName.Text.ToString();
string strFileDirectory = txtFolderName.Text.ToString();
string strFileData = txtFiledata.Text.ToString();

IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication();
ISFile.CreateDirectory(strFileDirectory);

string strPath = strFileDirectory + "\\" + strFileName;

StreamWriter swWriter = new StreamWriter(new IsolatedStorageFileStream(strPath,
FileMode.OpenOrCreate, ISFile));
swWriter.WriteLine(strFileData);
swWriter.Close();
MessageBox.Show("File Saved!!!");
}
else
{
MessageBox.Show("Select the checkbox to save file in root or in a folder");
}

}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 197
Task 5 Read the text file inside a folder

Our final task is to read the file which we created and saved in a particular folder in our previous
task. This task uses the same IsolatedStorageFile and IsolatedStorageFileStream to read the data, as
shown in the code below.



Code Behind:
private void button4_Click(object sender, RoutedEventArgs e)
{
string strFilename = txtFileName.Text.ToString();
string strFileDirectory = txtFolderName.Text.ToString();
string strPath = strFileDirectory + "\\" + strFilename;

IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream ISFileStream = ISFile.OpenFile(strPath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(ISFileStream))
{
string strData = reader.ReadLine();
MessageBox.Show(strData.ToString());
}
}

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 198
Now that we are done with the complete tasks, we can see the expected output, as shown in the
screen below. To build and execute the project, simply press F5 from the keyboard or from the
Visual Studio toolbar.

Output Screens:



Summary
In this chapter, we have seen Files and Folders in Isolated Storage for Windows Phone 7
development using the IsolatedStorageFile class. In our next chapter, we will see how to use the
local storage database to read and write data.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 199
Creating a Local Database

Introduction
In this chapter, we are going to see the usage of Isolated Storage by creating a local relational
database and save data locally that it is accessible to the specific Windows Phone 7 application. The
local relational database will be created in the Isolated Storage Container where in Windows Phone
7, we need to make use of LINQ to SQL for all the database operations. LINQ to SQL plays a major
role in creating the data schema, selecting the data and making operations on the data as and when
required. The LINQ to SQL object model uses the System.Data.Linq.DataContext namespace to
basically make a proxy call to the local database in the Isolated Storage container. The LINQ to SQL
Runtime acts as a bridge between the data context object and the real data to do the manipulations,
based on the user selection.

When considering making use of a local database for a Windows Phone 7 Application, we need to
consider some of the points mentioned below to get as much performance and usage over the
application.
Database file will be stored in the Isolated Storage Container.
Database is available specific to the application targeted as it is Isolated from other
application.
LINQ is used to query the data from the database since TSQL Querying is not supported.
Local database feature can be accessed directly by adding System.Data.Linq assembly only
since primary support is available with the framework.
Connection string much be use in the format of Data Source
=isostore:/DirectoryName/Databasename.sdf;
We are going to see how to perform CRUD operation for the Windows Phone 7 Application Isolated
Storage Local database using the Data Context class with a sample application. We will get clear idea
on how to perform the below tasks with Windows Phone 7.
Creating a local database
Adding data to the local database
Fetching data from local database
Deleting data from the local database
Deleting a local database

Let us see the steps on how to achieve the above tasks with the Isolated Storage Local Database in
Windows Phone 7 Application development by creating a sample application.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 200
Steps
Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7
Application project with a valid project name, as shown in the screen below.



Now let us design the user Interface to achieve the tasks listed above. Copy the XAML code below to
get a unique user interface with the controls provided to achieve each and every task, as shown in
the screen below.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 201
XAML Code:
<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="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Employee DB" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox Height="72" HorizontalAlignment="Left" Margin="113,28,0,0" Name="txtName" Text=""
VerticalAlignment="Top" Width="324" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="33,57,0,0" Name="textBlock1"
Text="Name" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="113,93,0,0" Name="txtAge" Text=""
VerticalAlignment="Top" Width="324" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="33,122,0,0" Name="textBlock2"
Text="Age" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="113,159,0,0" Name="txtEmpid" Text=""
VerticalAlignment="Top" Width="324" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="33,188,0,0" Name="textBlock3"
Text="Emp ID" VerticalAlignment="Top" />
<Button Content="Create Database" Height="72" HorizontalAlignment="Left" Margin="33,255,0,0"
Name="button1" VerticalAlignment="Top" Width="404" Click="button1_Click" />
<Button Content="Add an Employee" Height="72" HorizontalAlignment="Left" Margin="33,319,0,0"
Name="button2" VerticalAlignment="Top" Width="404" Click="button2_Click" />
<Button Content="Delete an Employee" Height="72" HorizontalAlignment="Left"
Margin="33,384,0,0" Name="button3" VerticalAlignment="Top" Width="404" Click="button3_Click"
/>
<Button Content="Fetch all Employees" Height="72" HorizontalAlignment="Left"
Margin="33,449,0,0" Name="button4" VerticalAlignment="Top" Width="404" Click="button4_Click"
/>
<Button Content="Delete Database" Height="72" HorizontalAlignment="Left" Margin="33,514,0,0"
Name="button5" VerticalAlignment="Top" Width="404" Click="button5_Click" />
</Grid>
</Grid>

Now that we are done with the user interface design, we need to create a data context and start
using the data object model and the data schema to perform the operations. Let us start with adding
the LINQ to SQL data context reference by right clicking the project from solution explorer and
adding the reference from the Add Reference menu, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 202



Once we added the reference for System.Data.Linq to the application, we need to add the below
namespaces to the code behind page of the MainPage.Xaml.



Code Behind:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 203
Now our first task is to create a database. Since we are going to use the LINQ to SQL data context as
a bridge between the local database and the data context, we need to create 2 classes as shown
below.

The first class is the Employee class, which holds the properties for the fields that are tables and
columns which are used to build the database. Copy the code below to a new class, as shown in the
screen below. The class has 3 properties that are going to be the data columns which we are going to
get as inputs from the end users. In the code below, we are providing the properties for each of the
column with one being a primary key and other are not null etc, which we need to specify based on
the database design, based on the requirement.



Code Behind:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Linq.Mapping;
using System.Data.Linq;

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 204
namespace F5debugWp7LocalDatabase
{
[Table]
public class Employee
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false, AutoSync =
AutoSync.OnInsert)]
public int EmployeeID
{
get;
set;
}

[Column(CanBeNull = false)]
public string EmployeeName
{
get;
set;
}

[Column(CanBeNull = false)]
public string EmployeeAge
{
get;
set;
}
}
}

Now we need to add another class called EmployeeDataContext, which is basically used as the
database schema to create an instance. Copy the code from the code block below to create it.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 205

Code Behind:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Linq;

namespace F5debugWp7LocalDatabase
{
public class EmployeeDataContext:DataContext
{
public EmployeeDataContext(string connectionString)
: base(connectionString)
{
}

public Table<Employee> Employees
{
get
{
return this.GetTable<Employee>();
}
}
}
}

Now let us start with our code on the MainPage.Xaml.cs to perform each of the tasks that were
mentioned above.

Task 1 Creating a local database
First let us start with creating a database, which is the very first step we need to perform when we
are going to use the local database storage. We need to have a connection string, which is pointing
to the local database storage. Let us create the connection string as a private constant, as shown in
the code below.

Code Behind:
private const string strConnectionString = @"isostore:/EmployeeDB.sdf";
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 206

Now we need to add the code below to create a database instance. Here we are going to create an
instance of the Data context by passing the connection string, which is pointing to the local database
storage, as shown in the screen below.


Code Behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists() == false)
{
Empdb.CreateDatabase();
MessageBox.Show("Employee Database Created Successfully!!!");
}
else
{
MessageBox.Show("Employee Database already exists!!!");
}
}
}

Task 2 Adding data to the local database

Our second task is to add some records to the database. To add the employee, we need to create an
instance of the data context and pass the properties that match the column properties which we
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 207
created in our data context initially. Here we are going to add an employee which has an Employee
ID, Employee Name and Employee Age. We have created the instance and passed the values
appropriately. Once we fetch the user inputs, we need to insert the details on submit, so we use the
InsertOnSubmit method to add the employees, as shown in the screen below.


Code Behind:
private void button2_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
Employee newEmployee = new Employee {
EmployeeID = Convert.ToInt32(txtEmpid.Text.ToString()),
EmployeeAge= txtAge.Text.ToString(),
EmployeeName=txtName.Text.ToString()
};

Empdb.Employees.InsertOnSubmit(newEmployee);
Empdb.SubmitChanges();
MessageBox.Show("Employee Added Successfully!!!");
}
}

Task 3 Fetching data from local database

Our next task is to fetch a consolidated list of data from the local database. So in order to fetch the
data, we use the LINQ query format to query the data based on the data table and the data context.
We have used a simple List to consolidate the data using the LINQ query and we are using the string
builder to consolidate the data as user readable, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 208


Code Behind:
public IList<Employee> GetEmployeeList()
{
IList<Employee> EmployeeList = null;
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
EmployeeList = EmpQuery.ToList();
}
return EmployeeList;
}

private void button4_Click(object sender, RoutedEventArgs e)
{
IList<Employee> EmployeesList = this.GetEmployeeList();

StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine("Employee Details");
foreach (Employee emp in EmployeesList)
{
strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
}
MessageBox.Show(strBuilder.ToString());
}


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 209

Task 4 Deleting data from the local database

Our next task is to delete the user specific data from the local isolated storage database. This is
straight forward as we query the data from the data context and delete it, as shown in the screen
below.



Code Behind:
private void button3_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees where Emp.EmployeeName ==
txtName.Text select Emp;
Employee EmpRemove = EmpQuery.FirstOrDefault();
Empdb.Employees.DeleteOnSubmit(EmpRemove);
Empdb.SubmitChanges();
MessageBox.Show("Employee Deleted Successfully!!!");
}
}




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 210
Task 5 Deleting a local database

Our final task is to delete the database completely once the user removes the application from the
device. So to delete the data, we can use the code given below.



Code Behind:
private void button5_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists())
{
Empdb.DeleteDatabase();
MessageBox.Show("Employee Database Deleted Successfully!!!");
}
}
}

Once we are done with the above code, our consolidated code will be like below. Just copy and
paste it directly on to the cs page for easy access to the code which we have in the above 5 tasks.



Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 211
Consolidated Code Base:
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;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace F5debugWp7LocalDatabase
{
public partial class MainPage : PhoneApplicationPage
{
private const string strConnectionString = @"isostore:/EmployeeDB.sdf";

// Constructor
public MainPage()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists() == false)
{
Empdb.CreateDatabase();
MessageBox.Show("Employee Database Created Successfully!!!");
}
else
{
MessageBox.Show("Employee Database already exists!!!");
}
}
}

private void button2_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 212
{
Employee newEmployee = new Employee {
EmployeeID = Convert.ToInt32(txtEmpid.Text.ToString()),
EmployeeAge= txtAge.Text.ToString(),
EmployeeName=txtName.Text.ToString()
};

Empdb.Employees.InsertOnSubmit(newEmployee);
Empdb.SubmitChanges();
MessageBox.Show("Employee Added Successfully!!!");
}
}

public IList<Employee> GetEmployeeList()
{
IList<Employee> EmployeeList = null;
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
EmployeeList = EmpQuery.ToList();
}
return EmployeeList;
}

private void button4_Click(object sender, RoutedEventArgs e)
{
IList<Employee> EmployeesList = this.GetEmployeeList();

StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine("Employee Details");
foreach (Employee emp in EmployeesList)
{
strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
}
MessageBox.Show(strBuilder.ToString());
}

private void button3_Click(object sender, RoutedEventArgs e)
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees where Emp.EmployeeName ==
txtName.Text select Emp;
Employee EmpRemove = EmpQuery.FirstOrDefault();
Empdb.Employees.DeleteOnSubmit(EmpRemove);
Empdb.SubmitChanges();
MessageBox.Show("Employee Deleted Successfully!!!");
}
}

private void button5_Click(object sender, RoutedEventArgs e)
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 213
{
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
{
if (Empdb.DatabaseExists())
{
Empdb.DeleteDatabase();
MessageBox.Show("Employee Database Deleted Successfully!!!");
}
}
}
}

}

Now we are done with our code. To build and test the application press F5 and we can see the
expected outputs in the screen below.


Output Screens:

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 214


Summary
In this chapter, we have seen how to use the local Isolated Storage to create and use a database by
using a LINQ to SQL data context and we have seen the different steps to achieve the tasks
mentioned at the start of this chapter.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 215
Consuming an ODATA Service

Introduction
In this chapter, we are going to see how to consume an ODATA service in a Windows Phone 7
application. ODATA means Open Data Protocol, an entity model used to access data as a REST
service, which can be used to execute queries and to create, update and delete data on to the
remote data service. An ODATA service allows the consumers to query the data over the HTTP
protocol and retrieve the result in a plain XML format. Normally, a mobile application development
requires data that is available as a service which can be consumed and used on demand, where the
ODATA Service plays a major role. We have a variety of ODATA services that are available in the
market; rather we can create our ODATA service which can also be consumed as a WCF Data Service.

As per the ODATA website, The Open Data Protocol (OData) is a Web protocol for querying and
updating data that provides a way to unlock your data and free it from silos that exist in applications
today. OData does this by applying and building upon Web technologies such as HTTP, Atom
Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of
applications, services, and stores. The protocol emerged from experiences implementing AtomPub
clients and servers in a variety of products over the past several years. OData is being used to
expose and access information from a variety of sources including, but not limited to, relational
databases, file systems, content management systems and traditional Web sites.

We have a comprehensive list of public ODATA Services that can be consumed from the client
devices using the link http://www.odata.org/producers. Let us see the steps involved in consuming
an ODATA Service in our Windows Phone 7 application and how to make use of it efficiently.

Steps
Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7
project with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 216


Now we need to design our XAML page where we want to show our consumed ODATA service. We
can use a Listbox and dynamically bind the data which we consume, as shown in the screen below.





Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 217
XAML Code:
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--<span class="hiddenSpellError" pre="">TitlePanel</span> contains the name of the application
and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="OData Service" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
<!--<span class="hiddenSpellError" pre=""-->StackPanel>

<!--<span class="hiddenSpellError" pre="">ContentPanel</span> - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<button>OData" Margin="0,507,0,0" Click="Button_Click"></button>
<ListBox x:Name="MainListBox"&nbsp; ItemsSource="{Binding}" Margin="0,6,0,106">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding Path=Name}" TextWrapping="NoWrap"
Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Path=Description}" TextWrapping="NoWrap"
Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Path=Url}" TextWrapping="NoWrap" Margin="12,-6,12,0"
Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>


Once we designed the XAML page, we need to consume the ODATA service. In this sample
application, we will make use of Telerik Videos ODATA service which is available to the public. The
ODATA service is available using the URI http://tv.telerik.com/services/odata.svc/. To add the
ODATA service, right click on the project name and select Add Service Reference, as shown in the
screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 218



Clicking on Add Service Reference will open a pop window where we need to provide the OATA
Service URI. Click on the Go button to discover the service online. Once the service is discovered, we
need to change the namespace to a user defined one, ODataTelerik, as shown in the screen below.



After successfully adding the ODATA service reference to the project, we can see a list of files added
to the service reference folder. Now that we are ready with the service, our next step is to write
some code that will do the necessary process to get the data from the service and show it to the
user interface. Add the below 2 namespaces, which are required to consume and get the data from
the ODATA service.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 219
Code Behind:
using System.Data.Services.Client;
using F5debugWp7ODataConsule.ODataTelerik;


Once we added the above 2 namespaces, we need to start with our code to consume the service.
Copy the code below and add it to the Mainpage class. This code creates an instance of the
reference, which we added to the project, and get the ODATA service URI, which is used to create a
reference, while consuming the service, as shown in the code below.



Code Behind:
private ODataDataSource TelerikEntity;
private static string strODataURI = "<a
href="http://tv.telerik.com/services/odata.svc/%22;">http://tv.telerik.com/services/odata.svc/";</a
>
private readonly Uri tURI = new Uri(strODataURI);
private DataServiceCollection<Video> videos;

Now in the button click event, we need to call the ODATA Service and get the data. Once we create
the instance, we can query the data from the DataServiceCollection by just using a LINQ query, as
shown in the screen below. Copy and paste the code below into the button click event to proceed
further.

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 220


Code Behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
TelerikEntity = new ODataDataSource(tURI);
videos = new DataServiceCollection<video tabindex="0">(TelerikEntity);</video>

var queryvideo = from vid in TelerikEntity.Videos
select vid;

videos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(videos_LoadCompleted);
videos.LoadAsync(queryvideo);
}

Now we need to add the code below, which is required to handle the completion of loading the data
to the user interface to scroll and have a better look for the end users, as shown.

Code Behind:
void videos_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
if (videos.Continuation != null)
{
videos.LoadNextPartialSetAsync();
}
else
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 221
{
this.MainListBox.DataContext = videos;
}
}
else
{
MessageBox.Show("Error while fetching the data!!!");
}
}

Now we are done with our code. Our final code behind class will look like below.
Code Behind:
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;

using System.Data.Services.Client;
using F5debugWp7ODataConsule.ODataTelerik;

namespace F5debugWp7ODataConsule
{
public partial class MainPage : PhoneApplicationPage
{
private ODataDataSource TelerikEntity;
private static string strODataURI = "<a
href="http://tv.telerik.com/services/odata.svc/%22;">http://tv.telerik.com/services/odata.svc/";</a
>
private readonly Uri tURI = new Uri(strODataURI);
private DataServiceCollection<Video> videos;

// Constructor
public MainPage()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
TelerikEntity = new ODataDataSource(tURI);
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 222
videos = new DataServiceCollection<Video>(TelerikEntity);

var queryvideo = from vid in TelerikEntity.Videos
select vid;

videos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(videos_LoadCompleted);
videos.LoadAsync(queryvideo);
}

void videos_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
if (videos.Continuation != null)
{
videos.LoadNextPartialSetAsync();
}
else
{
this.MainListBox.DataContext = videos;
}
}
else
{
MessageBox.Show("Error while fetching the data!!!");
}
}
}
}

Build and execute the application by pressing F5 from the keyboard and we can see the expected
results are shown in the screens below.








Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 223
Output Screens:



Summary
In this chapter we have seen what an ODATA service is and how to consume a service from a
Windows Phone 7 application.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 224
Consuming a WCF Service

Introduction

In this chapter, we are going to see how to consume a WCF Service in a Windows Phone 7
Application Development. For the beginners, WCF stands for Windows Communication Foundation,
a Microsoft framework to build applications with a Service Oriented Architecture. We can use WCF
as a service to send data across the application with the endpoints predefined to communicate. The
service endpoints can be hosted on an IIS Server and be available anytime, or it can also be an
application oriented service to provide on demand usage. The data transfer through the messages
can be of any format that the sender and receiver are able to understand over the protocol.

In Windows Phone 7 development, we have scenarios where we need to pass and get data over a
service through some authorized protocols and secured ports where WCF plays a major role. Let us
see the steps involved in consuming a WCF Service in a Windows Phone 7 Application, taking into
consideration that the reader should be familiar with creating a WCF Service and hosting one on IIS.
Refer to MSDN to get some idea on how to create and host the WCF Service using the link
http://msdn.microsoft.com/en-us/library/ms733766.aspx

Steps
Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7
Application with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 225


We can see the project is created and the main page is opened with the default controls. Let us
consider that we have a WCF application already created and hosted on IIS which can be consumed
and when passed a value (2 numbers), it will get output as the sum of the values passed. So from our
Windows Phone 7 application, we can pass 2 values and make WCF do the sum and send the result
back, which can be viewed in the application.

First, let us add some controls which get the users input that should be passed to the WCF Service
and display the results to the end users. Copy the XAML code provided below to get the same user
interface with respect to the design.




Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 226
XAML Code:
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--<span class="hiddenSpellError" pre="">TitlePanel</span> contains the name of the application
and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource
PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="WCF Service" Margin="9,-7,0,0" Style="{StaticResource
PhoneTextTitle1Style}"/>
</StackPanel>

<!--<span class="hiddenSpellError" pre="">ContentPanel</span> - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="30,43,0,0" Name="textBlock1"
Text="Value 1" VerticalAlignment="Top" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="30,117,0,0" Name="textBlock2"
Text="Value 2" VerticalAlignment="Top" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="119,19,0,0" Name="textBox1" Text=""
VerticalAlignment="Top" Width="313" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="119,97,0,0" Name="textBox2" Text=""
VerticalAlignment="Top" Width="313" />
<TextBlock Height="116" HorizontalAlignment="Left" Margin="53,312,0,0" Name="txtResult"
Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="379" />
<Button Content="Consume WCF and Get Result" Height="72" Margin="6,196,0,0"
Name="button1" VerticalAlignment="Top" />
</Grid>
</Grid>

Now we can consume the WCF Service by right clicking on the Project and selecting Add Service
reference. We can see a pop up window where we need to input the WCF Service and the details, as
shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 227


Clicking on OK will add the service reference to the project file and we can see the service reference
files added with the name provided in the namespace along with some reference files as well. We
need to create our code logic to consume the service and pass the values, as shown in the code
below.



Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 228
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace F5debugWp7ConsumeWCF
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
WCFServiceToSumData.Service1Client client = new WCFServiceToSumData.Service1Client();
int intvalue1 = Convert.ToInt32(textBox1.Text.ToString());
int intvalue2 = Convert.ToInt32(textBox2.Text.ToString());

client.Add2NumbersAsync(intvalue1, intvalue2);
client.Add2NumbersCompleted += new
EventHandler<WCFServiceToSumData.Add2NumbersCompletedEventArgs>(client_getStringComplet
ed);

}

private void client_getStringCompleted(object sender,
WCFServiceToSumData.Add2NumbersCompletedEventArgs e)
{
txtResult.Text = "The Sum of the above 2 number is " + e.Result;

}
}
}

Now we are done with our code. To check if things are working, we can run the application by
pressing F5 from the keyboard or from the toolbar. We can see the expected results once we pass
the data, as shown in the screens below.






Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 229

Output Screens:




Summary
In this chapter, we have seen how to make use of a WCF service which we created locally or to
consume a 3rd party WCF Service and get the desired output, as per the requirement in Windows
Phone 7 application.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 230
Encrypting Data for Security

Introduction

In this chapter, we are going to see how to encrypt data and use it in a Windows Phone 7
application. Security is a concern for developing applications with mobile since misusing of data like
passwords, connection strings etc. are highly possible which we need to take care by encrypting and
decrypting wherever possible. In Windows Phone 7, we have the Data Protection API, which can be
used to encrypt data, store confidential data within the Applications Isolated Storage or with
encrypting using local keys is not highly secure since the keys that are required to decrypt the data
will reside on the device itself. The Data Protection API solves this problem by explicitly generating
and storing the key. The ProtectData class is used to access the Data Protection APIs that can be
used with inbuilt methods, which we are going to see in this chapter.

The Data Protection APIs use the Protect Method and UnProtect Method, which are used to encrypt
and decrypt the data as and when required, while using dynamic key generations as and when
called. Let us see the steps for using these methods to encrypt and decrypt in this chapter.

Steps
Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7
application with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 231


Now let us design the application to get the inputs from the user to encrypt the data and store the
pin in isolated storage using the Protectdata method. Once we added the controls to the page we
can see the screen as shown below.



Let us start with our code behind to add the core logic to encrypt the data. To do that, we need to
import some namespaces which are not available initially. Copy and paste the 4 namespaces below
to the code behind.


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 232
Code Behind:
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Security.Cryptography;

Once we added the using statement, we need to add the code below to encrypt the data, which the
user inputs, as shown in the screen below. In this code we are going to encrypt the pin to a byte
array using the protect method.



Code Behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
byte[] PinByte = Encoding.UTF8.GetBytes(textBlock1.Text);
byte[] ProtectedPinByte = ProtectedData.Protect(PinByte, null);
this.Writedata(ProtectedPinByte);
textBlock1.Text = "";
MessageBox.Show("Encrypted the Pin!!!");
}

private void Writedata(byte[] pinData)
{
IsolatedStorageFile ISfile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream swIS = new IsolatedStorageFileStream(strFilePath,
System.IO.FileMode.Create, System.IO.FileAccess.Write, ISfile);

Stream writer = new StreamWriter(swIS).BaseStream;
writer.Write(pinData, 0, pinData.Length);
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 233
writer.Close();
swIS.Close();
}

Now we are done with the code to encrypt the data. We use the Writedata private method to store
the data to Isolated Storage by using the Isolated Stream Class. Once the pin is encrypted, we have
provided a message box to indicate to the user that the data is encrypted correctly. Now let us
decrypt the data on the second button click event.

Decrypting the data will be done using the UnProtect method, which reads the data from Isolated
Storage, decrypts the pin and gets the data, as shown in the screen below.



Code Behind:
private void button2_Click(object sender, RoutedEventArgs e)
{
byte[] ProtectedPinByte = this.ReadPinFromFile();
byte[] PinByte = ProtectedData.Unprotect(ProtectedPinByte, null);
textBlock1.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length);

}

private byte[] ReadPinFromFile()
{
IsolatedStorageFile ISfile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream rsIS = new IsolatedStorageFileStream(strFilePath,
System.IO.FileMode.Open, FileAccess.Read, ISfile);

Stream reader = new StreamReader(rsIS).BaseStream;
byte[] pinArray = new byte[reader.Length];

Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 234
reader.Read(pinArray, 0, pinArray.Length);
reader.Close();
rsIS.Close();

return pinArray;
}

Now we are done with our code. To check the encryption and decryption, run the application by
pressing F5 directly from the keyboard. We can see the application loads in the Windows Phone 7
Emulator. Input sample data and we can see the encryption and decryption happening, as shown in
the screens below.

Output Screens:



Summary
In this chapter, we have seen an interesting API, to encrypt and decrypt data which can be used
when required with the application development.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 235
WP7 Tool kit for Silverlight

Introduction

In this chapter, we are going to see how to use the Windows Phone 7 Tool Kit for Silverlight, which is
available as open source and can be downloaded and installed to the local developer machine to use
in application development. The toolkit has been localized to support all the new languages
supported by Mango along with new Mango specific controls like the HubTile, localization etc. The
toolkit provides a rich set of controls which are available to kick start the development process with
ease. We just need to download the tool kit and do some installation steps to make the tool kit fits
in with our development environment.

Below is the list of controls that are available with the Silverlight for Windows Phone 7 Tool Kit:
AutoCompleteBox
ContextMenu
DatePicker
DateTimeConverters
DatePicker
ExpanderView
GestureService/GestureListener
HeaderedItemsControl
HubTile
ListPicker
LocalizedResources
LockablePivot
LongListSelector
MultiselectList
Page Transitions
PerformanceProgressBar
PhoneTextBox
TiltEffect
TimePicker
ToggleSwitch
WrapPanel.
Let us see the steps involved in using this tool kit with Visual Studio 2010 to develop applications for
Windows Phone 7. Before that, we need to download the tool kit from the location below and have
the set up ready.
Link http://silverlight.codeplex.com/releases/view/75888
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 236
Steps
Once we download the package from the above link, run the package and we can see the wizard to
install the package shown in the screens below. Just complete the installation and we can see the
tool kit installed successfully to the local development machine.





Once the installation is complete, we can see the tool kit is installed to the folder shown in the
screen below. We can see the installation has occurred in the path

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Toolkit\Oct11

We can access the tool kit sources here. Now let us open Visual Studio 2010 and create a new
Silverlight for Windows Phone 7 project with a valid project name, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 237


Once the project is created, we will add a reference to the Microsoft Windows Phone tool kit. To do
that, right click on the project and select add reference and point to the folder where the tool kit is
installed (C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Toolkit\Oct11\Bin) and select
the dll Microsoft.Phone.Controls.Toolkit, as shown in the screen below.


Now that we have the tool kit ready, we need to add the namespace reference to the XAML Page, as
shown in the screen below. This will be standard across the project. Here we are just telling the
XAML loader that we are going to use the tool kit namespace within the page. We need to add this
namespace to all the pages wherever we use the controls.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 238


XAML Code:
xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

Now we will create an example by adding the autocomplete text box of the tool kit. To do that just
go to the grid and type the code below to get the autocomplete text box ready to use.



XAML Code:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Margin="31,29,195,519" Text="Autocomplete Text Box" >
<toolkit:AutoCompleteBox x:Name="acBoxDestination" Margin="31,94,0,428"
HorizontalAlignment="Left" Width="407" /> </Grid>

Now go to the code behind and add the code below in the main loaded event so that when the
application starts, we will get the autocomplete text box loaded with the predefined data.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 239


Code Behind:
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 F5debugWp7ToolKit
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List lstnames = new List();
lstnames.Add(Karthik);
lstnames.Add(Ram);
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 240
lstnames.Add(Rahman);
lstnames.Add(Bhaskar);
lstnames.Add(Arjun);
this.acBoxSour.ItemsSource = lstnames;
}
}
}

Now we are done with our code. Run the application by pressing F5 directly from the keyboard and
we can see the application loads with the emulator. Just input the starting letter and we can see the
autocomplete box pulls the complete phrase in the screen below.

Output Screens:



Summary
In this chapter, we have seen how to download, install and then use the Windows Phone 7 tool kit to
develop a productive application. We saw an example of using the Autocomplete text box.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 241
Deploying Application to Marketplace

Introduction

In this chapter, we are going to see how to deploy an application to the marketplace. Windows
Phone Marketplace is a portal where we need to publish the applications developed using the
Windows Phone SDK and make it available to the public for download. Windows Phone Market is a
one stop portal where users can purchase apps or games using credit cards or download free
applications with ease and provide reviews to applications that are very helpful.

Microsoft Windows Phone Marketplace can be accessed using the link
https://windowsphone.create.msdn.com. As a developer, we need to register with the market place
to publish our application for download. For registration, Microsoft provides options for Students,
Developers and Business to register, as per their requirement, with some nominal fees per year of
registration. Once we registered with the App Hub, the marketplace for Windows Phone, we are
able to upload our application to the marketplace with ease, provided the application follows some
validation procedures, which are listed by Microsoft. As a developer, we need to take care of all the
certification procedures. You can get a detailed idea on the certification procedures and
requirements in the MSDN link http://go.microsoft.com/fwlink/?LinkID=183220

Now let us steps involved in publishing the application to the Windows Phone Marketplace. Once we
are done with the design and development of the application, we need to build the final version in a
Release Build and see the Application package created a .XAP file, which is the extension of the
Windows Phone package accepted in the marketplace. Remember that the package size should not
exceed 225MB in size, which is the maximum size allowed. The package will be located in the BIN
folder of the project, under Release build, as shown in the screen below. The below application is
built and completed in release mode and we can see the .xap file created with the name of the
project.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 242


Now login to the marketplace and we can see the option to select which type of application we are
going to upload to the marketplace. The account registered here was a developer account so we
have a limitation of submitting 100 free applications and unlimited paid applications, as per the
standards followed by Microsoft. At the left side we have the metro tile indicating Submit for
Windows Phone and Submit for Xbox 360; We need to select Submit for Windows Phone, since our
application targets Windows Phone 7, as shown in the screen below.



After clicking on Submit for Windows Phone 7, the browser will be navigated to the Application
Submission page, where we need to input our application details and the package (.XAP file) in order
to upload to the server for validating the application. We need to provide the Application Name,
target place (Public or Private), the package location and finally the version of the application, as
shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 243


Providing the application details and clicking on the NEXT button will start uploading the package to
the server, which may take time depending on the size of the application uploaded. We can see the
progress of the application uploaded in the screen below.



Once the package is uploaded, we will be navigated to the next screen, which is the place we need
to describe the application and the category to which the application fits in. It is very important to
choose the correct category, since most users search for the applications based on the category.
Once we selected the category and sub category, we need to provide a description of the application
which will be the place we explain the purpose of the application so that it reaches the audience, as
shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 244


Following the description, we need to provide some basic information like our website URL, and the
email address which is required by the users to provide support. The next section is the Artwork,
where we need to concentrate more. This section handles the icons and the tile images that are
required for the application as well as for the marketplace which showcases our application to the
end users. The Artwork has different icon dimensions which need to be taken care of prior to
starting the upload of the application. Check this MSDN chapter on handling icons and screen shot
requirements before uploading the application to the marketplace. http://msdn.microsoft.com/en-
us/library/gg442300%28v=vs.92%29.aspx


Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 245


Once we uploaded the tile images, icons and the screen shots, we need to click on NEXT and proceed
to the next section. The next screen is the place where we need to specify the price of our
application, as per the developers choice. We have the option to select the target country or world
wide. We need to select the base amount and click on Select all in the World Wide distribution to
submit the application to the larger audience. Once selecting the above options, click on Next to
proceed further.



Clicking on Next will proceed to the final section, where need to provide our inputs to the testing
team. Once we provide the instructions, we need to select the publish option, based on the 3
options provided. Once we are done with the selection, click on Next to complete the application
submission procedure, as shown in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 246


On successful submission, our application will be uploaded to the marketplace and it will be in the
certification stage. We will see the submission success message, as shown in the screen below. Click
on View Life Cycle page to check the life cycle of the application certification process.



Clicking on View Life Cycle will navigate to the page where we can see the different sections and the
life cycle. The process flows to complete the validation and certification process of the application to
the marketplace, are displayed in the screen below.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 247


Summary
In this chapter, we have seen how to package and publish the application to the Windows Phone 7
Marketplace, with a step by step approach to overcome the certification issues.
Windows Phone Development Step by Step Tutorial

Karthikeyan Anbarasan, Microsoft MVP 2012 www.F5debug.Net Page 248
F5debug - Windows Phone Apps

Below is the list of window phone application that are developed and made available as free
download for the community by the Author Karthikeyan Anbarasan, Microsoft MVP.

S No
Application
Name Deep Link
1 Aarupadai Veedu
http://www.windowsphone.com/en-us/apps/4c30f162-7cac-434e-
83b5-618285cada3b
2 Tirupati Balaji
http://www.windowsphone.com/en-us/apps/cdd1fbbf-d175-46bd-
95d3-cd13124b6dff
3 Kolangal
http://www.windowsphone.com/en-us/apps/e7a9de20-8cd2-4110-
9ea2-f9aeaf3e70fe
4 Tamil Disc Floor
http://www.windowsphone.com/en-us/apps/9d5100e6-e273-440e-
bf70-57d2c739fd3a
5 Chennai Auto Fare
http://www.windowsphone.com/en-us/apps/cf693e33-1f2d-4899-
9223-1670d8b0ac4e
6 Chennai Postal Code
http://www.windowsphone.com/en-us/apps/02b40520-75e8-4f2e-
aa2c-88b346562cc2
7 TamilNadu RTO Finder
http://www.windowsphone.com/en-us/apps/77840e9a-0d45-432d-
ba5a-79235d81d9d4
8 Distance to Central
http://www.windowsphone.com/en-us/apps/bcdd6c17-cc18-47d9-
8242-fbc8bf15e830
9 Navagraha Temples
http://www.windowsphone.com/en-us/apps/53e8c5c8-d543-47c6-
97bb-16ca22152193
10 Start Blogging
http://www.windowsphone.com/en-us/apps/7505422f-b2d3-44ee-
97e1-387826b6ad37
11 VadivelComedy
http://www.windowsphone.com/en-us/apps/a7d1939e-01b6-4373-
99e0-f2c2102183cc
12 F5Debug
http://www.windowsphone.com/en-US/apps/7c61caea-943d-4716-
a436-29ba6f35a7bb

You might also like