• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this document? Why not share!

Windows phone development step by step tutorial

on

  • 1,304 views

 

Statistics

Views

Total Views
1,304
Views on SlideShare
1,304
Embed Views
0

Actions

Likes
1
Downloads
55
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Windows phone development step by step tutorial Windows phone development step by step tutorial Document Transcript

    • Windows Phone Development Step by Step TutorialKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 1
    • Windows Phone Development Step by Step TutorialCopyrightThis is a preliminary document and may be changed substantially. The informationcontained in this document represents the current view of the author as of the date ofpublication. 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. Withoutlimiting 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, withoutthe 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-mailaddress, logo, person, place, or event is intended or should be inferred. ©2012 Karthikeyan Anbarasan, (www.F5debug.Net) All rights reserved.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 2
    • Windows Phone Development Step by Step Tutorial I dedicate this eBook to my Parents and my Wife, who make it all worthwhile. — Karthikeyan Anbarasan, Microsoft MVP www.f5debug.netKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 3
    • Windows Phone Development Step by Step TutorialABOUT THE AUTHORKarthikeyan Anbarasan, Microsoft MVP (Most Valuable Professional) in ASP.NET/IISArchitecture and founder of the blog www.f5debug.net, has over 6 years’ experience onMicrosoft Technologies (Windows Phone, Windows Azure, SQL Azure, Public and PrivateCloud, 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 heis a Mindcracker and DNF Most Valuable Professional.Karthik works for 8KMiles Software Services as a Technical Cloud Architect and in his freetime used to write articles on any of the Microsoft technology and products which he isfamiliar with. He has been certified by Microsoft in few of the technologies and has beenawarded 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 4
    • Windows Phone Development Step by Step TutorialACKNOWLEDGEMENTI would like to express my heartful thanks to Mahesh Chand (Founder of MindcrackerNetworks) and Pinal Dave (Founder of Blogs.SQLAuthority.com), for constant motivation inpublishing this second eBook of mine.I have always been a big believer in advocating free knowledge and education for all. Tocontinue this belief, I have personally begun writing free distributable books for thecommunity. 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 blogwww.F5Debug.net. I should also mention about my website www.f5debug.net, which hasalways inspired me to write more on .NET and related technologies.Thanks to Daniel and Mahesh Chand for reviewing and checking the technical accuracy ofthe Book. A special thanks to my wife who complied and formatted this book.DISCLAIMERThe publisher and the author make no representations or warranties with respect to theaccuracy or completeness of the contents of this eBook. The strategies contained hereinmay not be suitable for every situation. Neither the publisher nor the author shall be liablefor damages arising here from. Further, readers should be aware that Internet Web siteslisted in this work may have changed or disappeared between when this work was writtenand when it is read.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 5
    • Windows Phone Development Step by Step TutorialTABLE OF CONTENTSWindows Phone Overview ............................................................................................................. 8Hello World Silverlight Application.............................................................................................. 15Working with Alarms/Reminders ................................................................................................ 38Working with Contacts ................................................................................................................. 47Working with Calendar ................................................................................................................. 51Working with Camera ................................................................................................................... 56Working with Panorama Control ................................................................................................. 63Working with Pivot Control .......................................................................................................... 70Working with Media ..................................................................................................................... 75Working with Toast Notifications ................................................................................................ 81Working with Tile Notifications ................................................................................................... 93Working with Raw Notifications ................................................................................................107Working with Tiles ......................................................................................................................119Working with Launchers.............................................................................................................127Working with Choosers ..............................................................................................................132Working with Navigation............................................................................................................138Working with Web Browser Control .........................................................................................145Working with Screen Orientation ..............................................................................................152Working with BING Map Control ...............................................................................................158Working with Device Information .............................................................................................167Working with Themes ................................................................................................................176Working with Isolated Storage ..................................................................................................182Working with Files and Folders..................................................................................................190Creating a Local Database ..........................................................................................................199Consuming an ODATA Service ...................................................................................................215Consuming a WCF Service ..........................................................................................................224Encrypting Data for Security ......................................................................................................230WP7 Tool kit for Silverlight.........................................................................................................235Deploying Application to Marketplace ......................................................................................241F5debug - Windows Phone Apps ...............................................................................................248Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 6
    • Windows Phone Development Step by Step TutorialKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 7
    • Windows Phone Development Step by Step Tutorial Windows Phone OverviewIntroductionIn this chapter we are going to see what Windows Phone 7 is and what are the hardware andsoftware requirements for developing a Windows Phone 7 Application and we are also going to seethe 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 2010IDE, Expression Blend, Silverlight and XAML code. Windows Phone 7 provides 2 types of frameworksupon 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 wehave restrictions over developing applications targeting the native application development which isa bit disappointment. We can develop native applications with Windows Phone 7 using VC++ butwith some restrictions over using multi-tasking and its features. We can also make use of the .NetCompact framework which has support over Windows Phone 7 Development.Before we start developing Windows Phone 7 applications, we need to have a look at therequirements to set up the development environment. Microsoft has suggested the software andhardware requirements which need to be considered when we start developing the application. Thehardware requirements are mainly for the device manufactures to certify the hardware required tohave better performance for the application that runs on the devices. As far as the softwaredevelopment is concerned we need to have the latest updates running so that we can make use ofthe 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 playaround with the development of applications for mobile. We need to first know that WindowsMobile and Windows Phone 7 are 2 different platforms even though both run on top of the CEKernel as far as the APIs are concerned. Windows Mobile and Windows Phone 7 do not have supportto run applications between the different platforms.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 8
    • Windows Phone Development Step by Step TutorialHardware RequirementsBelow are some of the hardware requirements the device manufactures needed to take care ofwhile designing the device. These are the minimum requirements that should be considered and canhave variations to have a better performing device. As a developer we will not have much controlover these requirements, but developers can target the application development based on thedevice with the hardware requirements specified. When considering Windows Mobile we can sayWindows 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 ControlsThe items mentioned above are the minimum requirements, so a device can have a maximumcapacity to perform better. When we consider setting up the development environment for theWindows Phone 7 Software Development Kit, we need to consider the requirements below to setupthe software. The Windows Phone 7 SDK is supported with one of the below OS’s with all theversions 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 MachinesAlso 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 driverKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 9
    • Windows Phone Development Step by Step TutorialSoftware RequirementsOnce we are ready with the hardware setup of the environment we need to install the requiredsoftware to start with the development of Windows Phone 7 Applications. To start with, Microsofthas provided all of the required and supported software with the SDK, which we can just downloadfrom the link Windows Phone SDK 7.1This SDK will install the development environment, providing options for the developers to developapplications and games on both Windows Phone 7.0 and Windows Phone 7.5. The above WindowsPhone 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 PhoneOnce the installation of the Windows Phone 7.1 SDK is complete, we can see new templates areadded to the Visual Studio 2010 IDE (Silverlight for Windows Phone 7 and XNA Games Studio). Weare set to start with the application development.Windows Phone 7 ArchitectureThe architecture of Windows Phone 7 is made on top of 4 main components, where eachcomponent, internally has many items to be seen in depth, which we will see in our upcomingchapters. Taking a quick look at the below figure will give us some idea on the architecture.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 10
    • Windows Phone Development Step by Step TutorialThe 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 developmentusing XAML (Extensible Application Markup Language) Programming. Developers will have flexibilityin using this framework along with most used UI tools like Microsoft Blend, Adobe Photoshop etc. tocreate 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 marketfor developing rich browser applications and it provides an option of creating applications withXAML which is highly advantageous for creating a vector based applications. So it gives thedevelopers 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 11
    • Windows Phone Development Step by Step TutorialWhere 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 muchknown 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 integrationof Xbox live integration with Windows Phone 7. The XNA engine provides the rich user experiencethat every developer can take advantage in providing next generation games with 2D and 3D gameloop engines. XNA Game Studio application development for entertainment or for the enterpriselooks like the image below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 12
    • Windows Phone Development Step by Step TutorialHow Windows Azure Cloud fits in Windows Phone 7?When we create an application with Windows Phone 7, we need to save some data for futureretrieval which is going to be a bit tougher here. Windows Phone 7 doesn’t provide directconnectivity with a database to save the data. To overcome this we need to use AZURE. WindowsAzure provides the platform of Cloud Computing for storing and retrieving data from differentlocations 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 ofuser visit gets increased which eventually requires an enterprise database to save the details. So inthis case we can use the Azure availability of extending the size of the database as per the needsince it is maintained in the cloud.Microsoft has provided us with an additional advantage of using Bing Maps which is given free ofcost, only for Windows Phone 7. Additionally Push notification services are also provided in thecloud using which we can send notifications to the mobile, such as Text which is eventually a betterprocess for the business needs.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 13
    • Windows Phone Development Step by Step TutorialWindows Phone 7 Development Life CycleAs developers of Windows Phone 7 applications, we need to register with App hub using the belowlink http://create.msdn.com/en-US/ by giving our Windows Live credentials which act like a singlesign on for all the process which Microsoft provides. The main idea behind registering with App hubis, once we register and develop an application in Windows Phone 7 we can use our registeredhandset as a physical device to test our application. App Hub provides developers with up to 3devices that can be registered and tested it in real-time. Now let us understand the steps involved insetting 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 testingour 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 readingthe 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=9730558Once the development is completed and the validation process is checked and passed by theMarket, then the application will be available online for downloads.Microsoft reserves the rights to give 5 free applications downloads and unlimited number of paidapplication downloads. Microsoft charges an amount of $99 for the market place registration tosubmit the developed application. For each download, Microsoft takes 30% of the fees paid and thedeveloper will get 70% for his development.SummaryWe have seen in this chapter a complete overview on what Windows Phone 7 development is andthe hardware and software requirements for developing a Windows Phone 7 Application in detail. Inour upcoming chapters, we will see some of the interesting features of Windows Phone 7development.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 14
    • Windows Phone Development Step by Step Tutorial Hello World Silverlight ApplicationIntroductionIn this chapter we are going to see how to create a Silverlight Windows Phone 7 Application usingthe Visual Studio IDE. In our earlier chapter we have seen the software and the hardwarerequirement in order to develop a Windows Phone application. Here in this chapter we will create aHello World Application and try to run it in the Windows Phone 7 Emulator to check the workingmodel of the application. Let us see the steps involved in designing the Hello World application usingthe Visual Studio 2010 IDE.StepsAs we discussed in our earlier chapter, after installing the Windows Phone 7 SDK, we can see thenew template options available with the Visual Studio 2010. The new templates are for creatingSilverlight for Windows Phone Application and the other one is for XNA Game Studio 4.0, which willhelp us to develop the respective application as per the requirement as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 15
    • Windows Phone Development Step by Step TutorialIn this book we are going to concentrate more on the Silverlight for Windows Phone applicationdevelopment for enterprise and commercial application builders. Also we will see how to create aXNA Game studio application as well so that it will give us some idea on the difference between thetwo 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 screenbelow.Clicking on OK will create the application; we can see a popup window asking us to select the versionof Windows Phone 7 OS. We will go with selecting the latest platform, Windows Phone OS 7.1 asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 16
    • Windows Phone Development Step by Step TutorialClicking on OK will open the project in Visual Studio. We can see the Windows Phone 7 interface inthe designer view and the XAML code below.Now drag and drop controls from the toolbox to get some user input and show the output HelloWorld. 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 17
    • Windows Phone Development Step by Step TutorialThe XAML code for the above design is given in the code block below. Give it a look to get an idea onthe 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. Herewe 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 uppercase, 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="F5Debug" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 andwrite the code belo, which get the user input from the 2 text boxes (First Name and Last Name ) toprovide a welcome message to the user.C# Code:using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 18
    • Windows Phone Development Step by Step Tutorialusing 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{// Constructorpublic 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();}}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 19
    • Windows Phone Development Step by Step TutorialNow build the application and execute the project. Check the output by pressing F5 from thekeyboard directly or by pressing the play button from the IDE tool bar and we can see the output inthe 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 Emulatorand not Windows Phone Device.Now we can enter the test inputs and click on the Submit button to get the welcome message asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 20
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter we have seen the steps involved in creating a Hello World application in WindowsPhone 7 with Silverlight.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 21
    • Windows Phone Development Step by Step Tutorial Using Expression BlendIntroductionIn this chapter we are going to see how to design the user interface of a Windows Phone 7Application using Expression Blend. Expression Blend is one of the products of the Expression Suiteof applications, which is used to design rich user interface for a XAML based application. Basically wecan design any Silverlight or WP7 application which are XAML based and now we can use thisproduct 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 whenwe made the development environment ready (Check my first chapter on Overview of WindowsPhone 7 Development). Let us see the steps involved in using Expression Blend to make rich userexperienced designs for Windows Phone 7 Applications.StepsLet us take the sample which we used in the last chapter. Open Visual Studio 2010 and open theproject and we can see the application like below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 22
    • Windows Phone Development Step by Step TutorialNow we will design this page using Expression Blend. To start with, first locate the page in theSolution Explorer of Visual Studio 2010 and then right click and select Open in Expression Blend asshown in the screen below.Clicking on Open in Expression Blend will load the Expression Blend IDE and we can see the pageopened as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 23
    • Windows Phone Development Step by Step TutorialNow we need to select the button (SUBMIT) from the Object and Timeline pane on the left side andright click to select the Edit template option to create an empty template as shown in the screenbelow.Now we can see a pop up window, which has the option to create the empty Control templateresource for the button. Just click on OK to proceed further without changing any options.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 24
    • Windows Phone Development Step by Step TutorialNow select the GRID from the Objects and Timeline pane and right click to change the layout. Fromthe 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 theborder thickness and corner radius as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 25
    • Windows Phone Development Step by Step TutorialNow change the background color by selecting the Brushes section. Change the color as per therequirement and also we have option to customize by providing the color code directly as shown inthe screen below.Similarly we need to change the setting for the Border Brush by selecting from the color pallet or byproviding the color code as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 26
    • Windows Phone Development Step by Step TutorialNow we need to switch to the Assets panel and select the text block tool from the controls paneunder 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 layoutsections on the right side panel and changing the alignments, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 27
    • Windows Phone Development Step by Step TutorialNow this step is very important. To change the content of the text property, select the CommonProperty category and click on the Advanced Property option to change the template binding toContent, as shown in the screen below.Now we are done with our design and the user interface. We can see the button customized andlooks like a rich user interface, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 28
    • Windows Phone Development Step by Step TutorialNow go back to the Visual Studio IDE and load the project, we can see a alert window that some ofthe resources are changed outside Visual Studio and if we need to restore those changes. Click onYes 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 directlyselecting the Build solution. We can see the application loaded on to the Windows Phone 7 Emulatorand we can see the output as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 29
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter we have seen the steps involved in using Expression Blend to design a rich userinterface for a Windows Phone 7 Application and load it into the Windows Phone Emulator.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 30
    • Windows Phone Development Step by Step Tutorial Working with Application BarIntroductionIn this chapter we are going to see how to use Application Bar effectively for Windows Phone 7Application development. In our earlier chapters, we have seen how to create an application usingVisual 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 makeeffective use of it.The Application Bar is a set of Icons that can be configured at the bottom of an application for eachpage or for multiple pages. These buttons can be used to navigate to frequently used pages acrossthe application, which makes navigation for users quick and easy. It automatically adjusts its iconsand 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 letus see the steps involved in adding an Application Bar to a new project and configuring theapplication bar with icons and menu items.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application namedF5debugWp7ApplicationBar, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 31
    • Windows Phone Development Step by Step TutorialWe can now see the project is created and ready to start with our development task. As we followsome standards, we can change the page header and make some small modifications so that thepage looks unique. Once we are done with the changes, to add the application bar, go to the XAMLPage and we can see a commented section, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 32
    • Windows Phone Development Step by Step TutorialWe just need to uncomment this section to have the application bar ready with some defaultbuttons and menus, which we can configure as per our requirements. Once we uncomment thissection we can see that we have 2 application bar icons added and 2 menu items added with thedefault values. Now we will change it to 3 Application bar icons and 3 Menu items. Before we startadding the code for it, we need to have the Application bar icons ready. By default when we installthe Windows Phone 7 SDK, we have the icons installed to the local development machine which willbe available in the below locations.DriveNameProgram FilesMicrosoft SDKsWindows Phonev7.1IconsdarkDriveNameProgram Files (x86)Microsoft SDKsWindows Phonev7.1IconsdarkWe 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 asshown in the screen below. Before that, add the icons that are required to use in the application barto a new Images folder.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 33
    • Windows Phone Development Step by Step TutorialNow we need to build the application icons. To do that, go to the properties of the each image andchange the Build Action from Content from Resources. Do the same for all the icons which havebeen added to the images folder.Once we are done with the above step, go to the XAML code and make the changes for each buttonby 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 34
    • Windows Phone Development Step by Step Tutorial<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 arevisible. To build and execute the application, just press F5 or select the build solution option fromthe 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 eventhandler code in the XAML and add the event triggering code to the code behind, as shown in thecode below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 35
    • Windows Phone Development Step by Step TutorialXAML 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!!!");}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 36
    • Windows Phone Development Step by Step TutorialWe have just added code to trigger a Message Box stating which button is clicked. Once we are donewith the above code, press F5 to build and execute the application and click on the Application Barbutton to see the expected output, as shown in the screen below.SummaryIn this chapter we have seen how to use the Application Bar and the steps to configure theapplication bar with menu items. The Application Bar can be of use in different scenarios and usedacross the pages. We can also use Application Bar globally.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 37
    • Windows Phone Development Step by Step Tutorial Working with Alarms/RemindersIntroductionIn this chapter we are going to how to use the Alarms and Reminders notifications in a WindowsPhone 7 Application. A notification is a message that pops up on the screen to the end users at aspecified time, scheduled initially. We can make the pop up with some customized message for userfriendly 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 textinformation to show the end user and also we can provide a navigation URI of a page to be openedby clicking on the reminder UI. We can also include some query string parameters to passinformation that should be used within the page or the application to which the navigation ispointing to. Microsoft has a limitation of using 50 Alarm or Reminder notifications within a singleapplication.Alarms and Reminders use the Alarm Class and Reminder Class respectively. We will see in thischapter how to use these classes to create alarms and reminders that can be used in real time. Wewill create a new Windows Phone 7 project and provide options to add an alarm and reminder. Letus see the steps involved in adding alarm and reminder notifications.StepsTo create an Alarm application, Open Visual Studio 2010 and create a new Windows Phone forSilverlight application with a valid project name and location to which the project should be saved,as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 38
    • Windows Phone Development Step by Step TutorialNow let us add 2 pages, one for adding an alarm content page and other for adding a remindercontent page. Once we added 2 pages in the main page, we need to add 2 buttons in the main pagefrom 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, weneed to navigate to these 2 pages, as shown in the code behind.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 39
    • Windows Phone Development Step by Step TutorialXAML 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="F5DEBUG" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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# Codeprivate 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 makeuse of the Alarm class which is inherited from the ScheduledNotification class. Now add the controlsto the AddAlarm.XAML Page, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 40
    • Windows Phone Development Step by Step TutorialXAML 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 41
    • Windows Phone Development Step by Step TutorialC# 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 ourrequirement 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 42
    • Windows Phone Development Step by Step TutorialREMINDER Page:Now let us start with designing the Reminder page. Before that we will add a new page calledAddReminder.XAML. The use of this page is to create a reminder trigger which will have the optionto navigate to a URI with passing some parameters. We will pass values to the pages from theReminder page. We will see how to do that with this page. Add contents from the tool box for theReminder 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" />Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 43
    • Windows Phone Development Step by Step Tutorial<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();Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 44
    • Windows Phone Development Step by Step TutorialDateTime 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 ourrequirement 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 querystring value, we need to write the code below in the new page (AddReminder.XAML), as shown inthe 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 45
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter we have seen how to make use of the inbuilt Scheduled Notification mechanism tobuild applications which notifies end users with some custom messages. Alarms and Reminders playa major role for notifications to end users, as per the requirements.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 46
    • Windows Phone Development Step by Step Tutorial Working with ContactsIntroductionIn this chapter we are going to see how to work with inbuilt contacts data and use it across ourrequirement to manipulate the data. Windows Phone 7.1 provides a read only access to the dataavailable locally across the device. We can query the data and select the users based on the searchfilters and also we can do multiple manipulations in order to perform some operation with the user’scontact information.Let us see the steps involved in using contacts for querying data. To launch the contacts, we need touse the AddressChooserTask which is used to select contacts. The queried result can be collected inthe AddressResult object and can be used to list it, as per the requirements. Let us start withcreating a new application and start using the AddressChooserTask.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project and provide avalid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 47
    • Windows Phone Development Step by Step TutorialNow 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 screenbelow.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 contactsdatabase. To do that, go to the button click event and write the code below. Basically, the WindowsPhone 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 48
    • Windows Phone Development Step by Step Tutorialusing Microsoft.Phone.UserData;Now in the button click event add the code below. From the code we can see the Contact class beenused to query the details. Here we will be using the SearchAsyc method to do the search with theobject 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 datacontext and do some small user information with the message. In the SearchAsync method, weprovide different filters that can be used to access the data. Below is the list of filters that can beprovided, 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)Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 49
    • Windows Phone Development Step by Step TutorialNow 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 theEmulator for testing purposes. We can use these contacts to do the testing or delete them based onthe requirement.SummaryIn this chapter we have seen how to perform a contact data search using the AddressChooserTaskand play around with the contact selected to list or to manipulate the contact.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 50
    • Windows Phone Development Step by Step Tutorial Working with CalendarIntroductionIn this chapter, we are going to see how to use the Calendar application to access the calendar dataand use it across the development as and when needed. In our earlier chapters, we have seen howto use the contact and access contact data; we are going to use the same process for accessing thecalendar objects.In order to use the calendar object, we are going to use a reference of the Appointments object anddo an Async search to get the results and show it on a collection of Appointment objects. The endresult in the appointments object can be used in different ways, as per the requirement, by bindingto different controls. The Appointment class is to interact with user appointment data and isinherited from the Microsoft.Phone.UserData namespace. Let us see the steps involved in usingcalendar objects and listing the appointments.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 51
    • Windows Phone Development Step by Step TutorialNow in order to fetch the details of the calendar appointments and show it to the end users, we willadd controls from the toolbox, as shown in the screen below. We can just drag and drop the controlsfrom 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="calendar" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 52
    • Windows Phone Development Step by Step TutorialNow we need to add code to list the calendar appointments in the list view. First add the followingnamespace.using Microsoft.Phone.UserData;Now add the button click event code. Here we are going to create an object of the Appointmentclass and do an AsyncSearch. We need to provide the start time and end time to fetch theappointment details and also should provide the maximum count. Copy and paste the code below tothe code behind for the button click event.C# Code:private void btnAppointment_Click(object sender, RoutedEventArgs e){Appointments aAppointment = new Appointments();aAppointment.SearchCompleted += newEventHandler<AppointmentsSearchEventArgs>(GetAppointments);DateTime starttime = DateTime.Now;DateTime endtime = starttime.AddDays(10);Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 53
    • Windows Phone Development Step by Step Tutorialint 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 datacontext of the list box. If there are no appointments available, we can see an empty result as well. Tocheck the application just run the application by pressing F5 directly from the keyboard or byselecting build and execute solution from the tool bar. We can see the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 54
    • Windows Phone Development Step by Step TutorialSince we are in the emulator and we don’t have any appointments, saved list is empty. If anyappointments are saved in the physical device we will get the complete list of appointments for thenext 10 days here in the list box.SummaryIn this chapter we have seen how to use the calendar object to fetch appointment details and listthem out. We can customize the appointments object to bind with different data binding options, asper the requirements.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 55
    • Windows Phone Development Step by Step Tutorial Working with CameraIntroductionIn this chapter, we are going to see how to use the Camera options in developing applications withWindows Phone 7. In order to access the camera features, we are going to use the Launchers andChoosers which have the inbuilt API’s to perform each task based on the requirement. Tomanipulate the camera photos and storage with the device, we are going to use theCameraCaptureTask. This task is used to launch the default camera application to take some snapshot for any third party application which is trying to use the camera to save images locally or toisolated storage (Isolated storage enables managed applications to create and maintain localstorage. 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 needto have some understanding of the Launchers and Choosers task since we need to select the taskbased on our requirement. Let us use the CameraCaptureTask and complete the process step bystep using Visual Studio for Windows Phone 7.StepsLet us Open Visual Studio 2010 and create a new Silverlight for Windows Phone project with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 56
    • Windows Phone Development Step by Step TutorialNow to invoke the CameraCapture task and save the image locally, we add 2 controls: a button andan image viewer control. The button control is to invoke the CameraCapture task and get the cameraimage. The image viewer control is to display the image which we took using the cameraapplication. 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 57
    • Windows Phone Development Step by Step TutorialNow we are done with our design, our next task is to invoke the camera application and capture animage. Once captured, we are going to assign the image to the Image Viewer control. To invoke theCameraCaptureTask, we need to include the below two namespacesusing Microsoft.Phone.Tasks;using Microsoft.Phone;Now let us add the code behind with the required code. First, we add class level variables which areused to invoke the camera task. Add the below class level variables within the class scope. We arecreating 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 theobject creation in the MainPage constructor and in the button event handler, invoke the camera, asshown in the code below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 58
    • Windows Phone Development Step by Step TutorialC# 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 thepicture. To save the picture, we need to have a mechanism which can be done with the help ofCameraCaptureTask Completed args. To do that, first let us write some code to get the capturedimage 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 bytearray 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 dothis at the CameraCapturedTask completed event. To do that, we need to go back to the MainPageconstructor at the top and add the code below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 59
    • Windows Phone Development Step by Step TutorialC# 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 theimage in the image control. Now we are ready to build and check the output of the application. Todo that, press F5 directly from the keyboard or by pressing the build and execute option from theVisual Studio Tool Bar. Once the application is built and executed successfully, we can see the outputin the Windows Phone 7 Emulator as shown below.Now to invoke the camera, click on the InvokeCamera button and we can see the CameraApplication is invoked. We will see an empty screen with the camera buttons, as shown in the screenbelow.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 60
    • Windows Phone Development Step by Step TutorialNow click on the button at the top right corner so that we can capture some image using theWindows Phone 7 emulator. Since we are using the emulator, we will see a white screen with arectangle in it. We can click on the Accept button at the bottom to capture the image, as shown inthe screen below. If we want to take a new image, we can click on Retake to capture again.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 61
    • Windows Phone Development Step by Step TutorialNow click on the Accept button and we can see the image captured is assigned to the image viewercontrol on the main page, as shown in the screen below. We can see a dull image since we are usingthe Windows Phone 7 emulator; if we deploy the application on to the real device we can get a verygood resolution of the picture.SummaryIn this chapter we have seen how to use a Camera Application to capture images and use them inthe development of our application, as per the requirements. Also, we have seen the Launchers andChoosers CameraCaptureTask to build the application to capture the picture.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 62
    • Windows Phone Development Step by Step Tutorial Working with Panorama ControlIntroductionIn 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 theprevious content. We can consider sliding through a horizontal page with different contents andblocks. We can use this Panorama control to show a rich user interface by dividing the contents todifferent blocks and assigning different items horizontally.Panorama controls are used to browse back and forth the page items within the specified contentblock to get a rich user experience. The Panorama control is the base, which can containPanoramaItem controls, which will host individual contents. Basically, we will have only onePanorama control within which we can have multiple PanoramaItem, to have contents blocked outone by one.The Panorama control can be added and configured directly from the XAML code or we can do itprogrammatically. 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 it’s time for the demo, let us see steps involved in creating a Panorama control based applicationand add some content to see the rich user interface experience it offers.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 63
    • Windows Phone Development Step by Step TutorialNow we can see a beautiful interface with the default design and the background, shown below. Wewill customize the application design in our next steps.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 64
    • Windows Phone Development Step by Step TutorialFirst 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 selectthe complete code and delete it. We can now see the screen looks empty, as shown in the screenbelow.Now change the Panorama control Title and background. To do that, go to the XAML code andchange the Title to F5Debug and to change the background, let us add a new background to theproject solution and map the path to the ImageBrush tag, as shown in the code below. Once we aredone 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 65
    • Windows Phone Development Step by Step TutorialNow 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 tothe end user. Once we added the 3 items we can see our screen looks like below and the code willappear 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 66
    • Windows Phone Development Step by Step TutorialNow 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 XAMLCode. Let us do some customization to get a good user experience with controls as shown in theXAML 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 postupdates 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" />Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 67
    • Windows Phone Development Step by Step Tutorial</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 directlyfrom the keyboard or Build and Execute from the Visual Studio IDE toolbar. We can see theapplication loaded into the Windows Phone 7 Emulator, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 68
    • Windows Phone Development Step by Step TutorialNow 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 inthe screen below.SummaryIn this chapter we have seen how to use the Panorama Control and to design a rich user interface byadding items and changing the background to have a unique interface.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 69
    • Windows Phone Development Step by Step Tutorial Working with Pivot ControlIntroductionIn 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 thePivot control we can easily maintain pages or data views without having the need of loading multiplepages. We can easily filter large data sets into multiple pages. With this control, we can slide backand forth and provide the end user with related data in a much easier view using any of the availablecontrols.The Pivot control is the base application control and inside that we will have a Pivotitem controlwhere we can have multiple items inside a Pivot control. It is recommended to have one pivotcontrol within a page, which in turn can have multiple Pivotitems. The Pivot Control is layered into 2layers; 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 VisualStudio 2010.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 70
    • Windows Phone Development Step by Step TutorialWe 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 requirementKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 71
    • Windows Phone Development Step by Step TutorialIf we can see the XAML code, the pivot control is added by default with default pivot items. We candelete the pivot items inside the pivot control and we can see the empty Pivot control. We willcustomize it by adding our own PivotItems, let us do the same design which we did for thePanorama sample. One difference, we do not have an option to change the background. Once weadd 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 dosome customization to get a good user experience with the controls, as shown in the XAML Codebelow. 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 postupdates here!!!" VerticalAlignment="Top" Width="369" /></Grid></controls:PivotItem>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 72
    • Windows Phone Development Step by Step Tutorial<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 directlyfrom the keyboard or Build and Execute from the Visual Studio IDE toolbar and we can see the pivotcontrol application loaded into the Windows Phone 7 Emulator as shown below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 73
    • Windows Phone Development Step by Step TutorialNow we can directly click on the header title or scroll it horizontally to navigate to the second pivotitem, as shown in the screen below.SummaryIn this chapter, we have seen how to use the pivot control from scratch and design a good userinterface that looks similar to the Panorama control but with some differences which we have seenin the output.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 74
    • Windows Phone Development Step by Step Tutorial Working with MediaIntroductionIn this chapter, we are going to see how to use the media framework, which helps applicationdevelopers to stream video and audio files and to use the integrated Music and Video Hubs to selectmedia files. In our previous chapters, we have seen the different controls to design a rich userinterface application and in this topic we will see much more interesting aspects on handling mediafiles 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 filesusing the inbuilt device media player in Silverlight for Windows Phone 7. In this chapter we will seehow to play a video file using the MediaElement API.Let us see the steps involved in Media development in Windows Phone 7 applications using theMediaElement API.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application project byproviding a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 75
    • Windows Phone Development Step by Step TutorialNow let us customize the Mainpage.xaml by adding a button control and a MediaElement to play thevideo file, as shown in the screen below. Also we have customized the header grid to have a uniquedesign 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. Wehave added a sample .WMV file to the root folder of the project. Once we have added the file, go tothe button click event (Play Video button) and write the code below to stream the video file, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 76
    • Windows Phone Development Step by Step TutorialXAML Code:<phone:PhoneApplicationPagex:Class="F5debugWp7Media.MainPage"xmlns="<ahref="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>xmlns:x="<ahref="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/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="<ahref="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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="video player" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 77
    • Windows Phone Development Step by Step TutorialC# 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{// Constructorpublic MainPage(){InitializeComponent();}private void button1_Click(object sender, RoutedEventArgs e){mediaElement1.Source = new Uri("Bear.wmv", UriKind.Relative);mediaElement1.Play();}}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 78
    • Windows Phone Development Step by Step TutorialNow we are done with our code. Let us build and execute the application by pressing the F5 buttonfrom the keyboard or by selecting the Build and Execute option from the toolbar. We can see theoutput of the application shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 79
    • Windows Phone Development Step by Step TutorialNow we can see the video streaming, with the option to restart and reset the video at any point oftime. We can also customize it to select the file randomly and play as we normally do using theplaylist, which we will see in depth in our upcoming chapters.SummaryIn this chapter, we have seen how to use the Media Element to stream video files and use iteffectively. Also we have seen the different options to restart, reset the videos to make it userfriendly.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 80
    • Windows Phone Development Step by Step Tutorial Working with Toast NotificationsIntroductionIn this chapter, we are going to see how to use Toast Notifications in Windows Phone 7. WindowsPhone 7 application development supports push notifications, which provides developers a muchmore convenient option to transfer message to a Windows Phone 7 device from a web servicewhenever 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 ourupcoming chapters. Let us see the step by step process on how to create a TOAST application; weneed to create a client application to send the notification to the device which we will be covering inthis chapter.StepsOpen Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7application with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 81
    • Windows Phone Development Step by Step TutorialNow 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 willcreate a new notification event and then connect through the channel. Add the below XAML code toget 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Toast Notification" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 82
    • Windows Phone Development Step by Step TutorialNow we need to go to the code behind and start the process of establishing the Notification channelto 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 ToastNotification. To do that, we will use the output window to get the channel details. Use the codegiven 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 toastnotifications. 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 toastnotification message in order to log it for administration purposes.void Channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e){Dispatcher.BeginInvoke(() =>{Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 83
    • Windows Phone Development Step by Step TutorialDebug.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 thechannel is already available; if it is available, we need to check if the channel is null. If null then weneed to close the channel and open a new channel. Initially if the channel is not available then wecan directly create the HttpNotificationChannel and do the process to create the channel, as shownin 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 += newEventHandler(Channel_ShellToastNotificationReceived);Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 84
    • Windows Phone Development Step by Step TutorialhttpChn.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 bybuilding and executing the application and we can see the Windows Phone 7 Emulator, as shown inthe screen below.Now click on the Establish Channel button, which will establish the channel and we can see thechannel URI in the Output window, since we have coded to get the channel details. To get to theoutput window, just go to the Visual Studio toolbar and select View –> Output window and we cansee the output window, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 85
    • Windows Phone Development Step by Step TutorialNow copy and keep the channel details on a separate notepad. We need to create a Server to postthe toast notifications to the application device.We will create a web page from which we will post the toast notifications and get the notificationonto the Windows Phone 7 device. To start with, first create an ASP.NET Web application in C#, asshown 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 thistutorial. Here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI andnotification message) and a button to trigger the event for the toast message to be sent to theWindows Phone 7 Device.ASPX Code:<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs" Inherits="F5debugWp7ToastNotificationServer._Default" %>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 86
    • Windows Phone Development Step by Step Tutorial<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 WindowsPhone 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 87
    • Windows Phone Development Step by Step Tutorial</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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 88
    • Windows Phone Development Step by Step Tutorial<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 theChannel URI, and pass the message to the Microsoft Push Notification services. Just copy the codebelow to proceed further.Code Behind:using System;using System.Collections.Generic;using System.Linq;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 89
    • Windows Phone Development Step by Step Tutorialusing 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:Notificationxmlns: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;}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 90
    • Windows Phone Development Step by Step Tutorial}}Now run the Windows Phone 7 Toast notification application to get the channel URI. Once we getthe channel URI, keep the application running in the background and navigate to the home page ofthe 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 theToast Notification Message on the top, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 91
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter we have seen what a Push Notification is in Windows Phone 7 and the types ofnotification available. Also we have seen how to send a Toast Notification in detail.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 92
    • Windows Phone Development Step by Step Tutorial Working with Tile NotificationsIntroductionIn this chapter, we are going to see how to work with the Tile Notification, which is one of theMicrosoft Push Notification Services available. In our previous chapter, we have seen how to use theToast Notification service to create a channel and send toast messages to a Windows Phone 7Device. In this exercise, we will follow the same process and see the steps to create the channel andsend Tile notification messages.Tile Notifications are used to show up to date status of an application on the Windows Phone 7 startscreen as a tile. This will work only if the application is pinned to the start screen. Basically we cansee 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 betterappearance. If it is less than the specified pixels, it will be stretched automatically and the look andfeel will suffer. Let us see the step by step process on how to achieve these tasks.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 93
    • Windows Phone Development Step by Step TutorialNow 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. Ifthere are already notification events available, it will use the same or else it will create a newnotification event and then connect through the channel. Add the below XAML code to get thechannel 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Tile Notification" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 channelto get the event trigger. To do that, we need to add the below two using statements.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 94
    • Windows Phone Development Step by Step Tutorialusing 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 TileNotification. To do that, we will use the output window to get the channel details. Copy the codebelow to the code behind page. Also, we need to have a method which will do the channel setup. Itwill first check if the channel is already available; if it is available, we need to check if the channel isnull, if null we need to close the channel and open a new channel. Initially, if the channel is notavailable then we can directly create the HttpNotificationChannel and perform the process to createthe 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 += newEventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);pushtileChannel.ErrorOccurred += newEventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);pushtileChannel.Open();pushtileChannel.BindToShellTile();}else{pushtileChannel.ChannelUriUpdated += newEventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);pushtileChannel.ErrorOccurred += newEventHandler<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());Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 95
    • Windows Phone Development Step by Step TutorialDebug.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 bybuilding and executing the application and we can see the Windows Phone 7 Emulator, as shown inthe screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 96
    • Windows Phone Development Step by Step TutorialNow click on the Establish Channel button, which will establish the channel and we can see thechannel URI in the Output window, since we have coded to get the channel details. To get theoutput window just go to the Visual Studio toolbar and select View –> Output Window and we cansee 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 postthe 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 toContent, as shown below.We will create a web page from which we will post the tile notifications on to the Windows Phone 7device. To start with, first create an ASP.NET Web application in C#, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 97
    • Windows Phone Development Step by Step TutorialNow add the design code below to the ASPX page so that we will get the same look and feel for thistutorial. Here we have added 4 labels and 4 textboxes to get the user inputs (Channel URI, Front tilemessage, Background and Notification txt) and a button to trigger the event for the tile message tobe 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{Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 98
    • Windows Phone Development Step by Step Tutorialwidth: 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="F5DebugWindows 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 99
    • Windows Phone Development Step by Step Tutorial</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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 100
    • Windows Phone Development Step by Step Tutorial<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 theChannel URI, background and the tile information and pass the message to the Microsoft PushNotification services. Just copy the code below to proceed further.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 101
    • Windows Phone Development Step by Step TutorialCode 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:Notificationxmlns: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");Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 102
    • Windows Phone Development Step by Step TutorialsendNotificationRequest.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 7application (F5debugWp7TileNotification) and get the Channel URI. Once we got the URL, click onthe Back button and navigate to the application list. Pin our application F5debugWp7TileNotificationby pressing continuously holding down the mouse pointer and we can see the context menu, asshown in the screen below.Now select pin to start from the menu and we can see the application is pinned to the Tile, in thescreen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 103
    • Windows Phone Development Step by Step TutorialNow run the F5debugWp7TileNotificationServer web application and enter the values, as shown inthe screen below.Now click on the Send Notification button and we can see the result in the label at the bottom, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 104
    • Windows Phone Development Step by Step TutorialNow go to the Windows Phone 7 Emulator and we can see the Tile notification message which wesent from the web application, in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 105
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to use the Tile Notifications to send live updates to the WindowsPhone 7 devices to update the primary tile. In our upcoming chapters we will see how to do thesecondary tiles and see the raw notification process as well.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 106
    • Windows Phone Development Step by Step Tutorial Working with Raw NotificationsIntroductionIn this chapter, we are going to see how to use Raw Notifications to send messages. In our earlierchapters, we have seen how to use Toast and Tile notifications to send messages, as per therequirements. Raw Notifications are not like the TOAST and TILE notification; these notifications aregenerated by the application itself or from a web service. The application needs to be up andrunning in order to receive these notifications. If the application is not running then the message willbe 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 theTile, we will not have a good looking image to show the notification rather we will try to catch thenotification to a message box.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 107
    • Windows Phone Development Step by Step TutorialNow let us start designing the interface to create a channel, as we discussed in our previouschapters. We will create the channel first, which will be required to communicate for the RawNotifications. If there are any notification events already available, it will use the same, or else it willcreate a new notification event and then connect through the channel. Add the below XAML code toget 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Raw Notification" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 channelto 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 notificationerrors and for receiving the raw notification, which is application specific, as shown in the below 3event handler codes.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 108
    • Windows Phone Development Step by Step TutorialC# 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 RawNotification. To do that, we will use the output window to get the channel details. Copy the codebelow to the code behind page. Also, we need to have a method which will perform the channelsetup. It will first check if the channel is already available; if it is available, we need to check if thechannel is null. If it is null, then we need to close the channel and open a new channel. Initially, ifthe channel is not available, then we can directly create the HttpNotificationChannel and performthe process to create the channel, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 109
    • Windows Phone Development Step by Step TutorialC# 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 bybuilding and executing the application. We can see the application in the Windows Phone 7Emulator in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 110
    • Windows Phone Development Step by Step TutorialNow click on the Establish Channel button, which will establish the channel and we can see thechannel URI in the Output window, since we have coded to get the channel details. To get theoutput window, just go to the Visual Studio toolbar and select View –> Output window. We can seethe 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 topost the raw notifications to the application device. We will create a web page from which we willpost the Raw Notifications and get the notification. To start with, first create an ASP.NET Webapplication in C#, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 111
    • Windows Phone Development Step by Step TutorialNow add the design code below to the ASPX page so that we will get the same look and feel for thistutorial. Here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI, Title andSub Title) and a button to trigger the event for the tile message to be sent to the Windows Phone 7Device. 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;}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 112
    • Windows Phone Development Step by Step Tutorial.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 WindowsPhone 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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 113
    • Windows Phone Development Step by Step Tutorial<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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 114
    • Windows Phone Development Step by Step Tutorial<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 theChannel URI, and the Raw Message information and pass the message to the Microsoft PushNotification 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){Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 115
    • Windows Phone Development Step by Step Tutorial}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 7application (F5debugWp7RawNotification) and get the Channel URI, or make use of the URI whichwe saved in our notepad. Note that the application should be running in order to get the notificationmessage.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 116
    • Windows Phone Development Step by Step TutorialNow run the F5debugWp7RawNotificationServer web application and enter the values as shown inthe screen below.Now click on Send Notification button and we can see the result in the label at the bottom, as shownin the screen below.Now go to the Windows Phone 7 Emulator and we can see the Raw Notification Message which wesent from the web application in the Message Box in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 117
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to use the RAW Notification Mechanism to send and receivenotifications while the application is running in the foreground.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 118
    • Windows Phone Development Step by Step Tutorial Working with TilesIntroductionIn this chapter, we are going to use how to use Tiles in our Windows Phone 7 development. In ourprevious 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 atile for an application.Tiles are nothing but linking an application to the home screen with some options to update thestatus. 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.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 119
    • Windows Phone Development Step by Step TutorialLet 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 andSecondary Tile respectively. Once we have customized the design we can see the UI, as shown in thescreen below.Now let us add the code to trigger the Application tile. To do that, we need to go to the ApplicationTile button click event and write the code below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 120
    • Windows Phone Development Step by Step TutorialC# 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{// Constructorpublic 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);}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 121
    • Windows Phone Development Step by Step TutorialNow we will check if the application is building and executing correctly and the Application Tile ispinning the application to start. To check, build and execute the application by pressing F5 directlyand 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 thestart screen. To check that, click on the Start button at the bottom and in the list view of theapplications select our application F5debugWp7Tiles and select pin to start. Now go back to themain screen (Home) and we can see the tiles in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 122
    • Windows Phone Development Step by Step TutorialNow 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Secondary Tiles" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 123
    • Windows Phone Development Step by Step TutorialNow 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 theOnNavigatedTo event, as shown below.C# Code:protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){base.OnNavigatedTo(e);}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 124
    • Windows Phone Development Step by Step TutorialNow we are done with our code, just build and execute the project and we can see the screen withthe 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 screenbelow.Clicking on the secondary tile (F5Debug Sec Tile) will navigate to the Secondary Tile Page(Page1.xaml), shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 125
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter we have seen what a Tile is and how to create a basic tile and to assign a tile withbasic properties. Also we have seen how to create a Secondary tile and use it on navigation, basedon purpose.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 126
    • Windows Phone Development Step by Step Tutorial Working with LaunchersIntroductionIn this chapter, we are going to see what Launchers are and what the use of a Launcher is whendeveloping a Windows Phone 7 Application. Launcher, in Windows Phone 7, is an API used to launchsome of the built in applications from which the user can select some task. Once the user selects theapplication, we can handle the task as per the most convenient option to do some manipulations asper the task raised. Some of the examples of using the launchers are triggering a contact applicationto 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 onwhen 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 127
    • Windows Phone Development Step by Step Tutorial  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 andsee how to launch the Phone application to make a call.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 128
    • Windows Phone Development Step by Step TutorialNow let us add a button to invoke the PhoneCall Task and call a particular number. Write the codegiven below on the click event of the button. Also note that we need to add the following usingDirective 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Launchers" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 129
    • Windows Phone Development Step by Step TutorialC# 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 theapplication opened in the Windows Phone 7 Emulator in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 130
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen what Launchers are in Windows Phone 7 development and the list ofLaunchers available. Also, we have seen a sample on what the PhoneCallTask is and how to use itpractically within Windows Phone 7 application development.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 131
    • Windows Phone Development Step by Step Tutorial Working with ChoosersIntroductionIn this chapter, we are going to see what Choosers are in Windows Phone 7 development and thedifferent type of chooser tasks available. In our previous chapter, we have seen what Launchers areand 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, withinwhich the user can perform some task related to the application launched. Unlike launchers, hereusing choosers we can perform some task and pass data to get the task completed as per therequirement. Basically, the choosers will be supplied with some data and status to do somemanipulations accordingly. Some examples of using the choosers are selecting a particular photofrom 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 clearidea 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 contact’s 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.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 132
    • Windows Phone Development Step by Step Tutorial  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 contact’s 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 contact’s 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 system’s 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 Phonenumber chooser application to select a contact and make a call.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 133
    • Windows Phone Development Step by Step TutorialNow let us add a button to invoke the Phone Number Chooser task and call a particular contactnumber. Write the code below on the click event of the button. Also note that we need to add thefollowing using Directive in order to use the PhoneNumberChooser task (usingMicrosoft.Phone.Tasks; ). The PhoneNumberChooser Task invokes the contacts application to getthe selected contact from the user. The chooser works asynchronously so that the completed eventmust be subscribed to, before launching the chooser. Once the chooser task returns the PhoneNumber 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Choosers" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></StackPanel><!--ContentPanel - place additional content here--><Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 134
    • Windows Phone Development Step by Step Tutorial<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;// Constructorpublic 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();}}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 135
    • Windows Phone Development Step by Step TutorialNow we are done with the code. Build and execute the project by pressing F5 and we can see theapplication opened in Windows Phone 7 Emulator in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 136
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen what Choosers are in Windows Phone 7 development and the list ofChoosers available. Also, we have seen a sample on what the PhoneNumberChooser Task is and howto use it practically within Windows Phone 7 application development.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 137
    • Windows Phone Development Step by Step Tutorial Working with NavigationIntroductionIn 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 anapplication, since we cannot design an application that fits into a single page. Navigation can bedone in two ways; one is to just pass between the pages to show the end user with detailedinformation and second is to pass values from one page to other based on the user inputs to showthe details by passing parameters.We can easily navigate between the pages with the options available. We have different Navigationevents available which can be overridden to be used to track any navigation that happens on thepage flow. Below are a list of navigation events available with Windows Phone 7, which can be usedon 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 ButtonLet us see the steps involved in performing the two navigations in detail.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 138
    • Windows Phone Development Step by Step TutorialNow let us add 2 pages to show how to navigate between the pages and also to pass parametersand retrieve them in another page. To add the pages, just right click on the project name and clickon 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.xamlwith 2 buttons to navigate on button click, as shown below. Just copy the xaml code provided belowto get the same look and feel.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 139
    • Windows Phone Development Step by Step TutorialXAML 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Navigation" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 140
    • Windows Phone Development Step by Step TutorialNow let us write our code to navigate between the pages without passing parameters. Go to thecode behind and write the code given below on the button1 click event. Before that, we will justmake a small design change in NavPage1.xaml to have a good look and feel on the page by adding aTextblock 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 iscomplete, let us go ahead with the second button navigation to pass some values fromMainPage.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)); }Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 141
    • Windows Phone Development Step by Step TutorialNow we need to go to NavPage2.XAML and write the code below to get the parameters and assignthem 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();}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 142
    • Windows Phone Development Step by Step Tutorialprotected 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 Emulatoropened and we can see the end result in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 143
    • Windows Phone Development Step by Step TutorialOutput Screens:SummaryIn this chapter, we have seen how to use Page Navigation with and without passing any parametervalues.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 144
    • Windows Phone Development Step by Step Tutorial Working with Web Browser ControlIntroductionIn this chapter, we are going to see how to use the Web Browser control in Windows phone 7development. The Web Browser control is used to access static content or web based content, basedon the development need. We can use this control in a number of ways in our Windows Phone 7development, such as using it to dynamically generate HTML code and display it as a page or show astatic page saved in Isolated Storage. Let us see the steps involved in making use of the WindowsPhone 7 Web Browser control.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 145
    • Windows Phone Development Step by Step TutorialNow we can see the Windows Phone 7 designer and XAML windows where we can start designingour application. Let us start with dragging and dropping the Web Browser control from the VisualStudio 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Web Browser" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 theSource property of the Web Browser Control to assign the URI to navigate to, on clicking of thebutton. We also have an alternative approach of using the Navigate(URI) property to do the sametask, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 146
    • Windows Phone Development Step by Step TutorialC# 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 tobuild and execute the project and we can see the result, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 147
    • Windows Phone Development Step by Step TutorialNow let us see how we can create a dynamic HTML page and map it to the web browser control toload the content as a static page. Let us add a new page and add the web browser control to that, aswe did in our above steps. Once we have added the control to load the HTML, we can see thatscreen 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Web Browser" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 148
    • Windows Phone Development Step by Step TutorialNow let us add the code to load the HTML content using the WebBrowser_onloaded event as shownin the code below. The code will take the static HTML content and load it in the web browsercontrol. 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 visitwww.f5Debug.net</p></body></html>");}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 149
    • Windows Phone Development Step by Step TutorialNow let us run the application and we can see the Web Browser control load the static HTMLcontent. To build and execute the application press F5 and we can see the output in the WindowsPhone 7 Emulator, as shown below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 150
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to use the Web Browser control within Windows Phone 7application development and also the possible ways of using this control effectively.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 151
    • Windows Phone Development Step by Step Tutorial Working with Screen OrientationIntroductionIn this chapter, we are going to see about Screen Orientations in Windows Phone 7 Development. Asa Windows Phone 7 user, we can see screen orientations are pretty simple just by titling the deviceand seeing the screen tilt with the device, but as a developer we have to handle much of theorientations programmatically, as per the requirement. The built-in sensors play a major role whenusing the screen orientations, for the developers to design the application, which looks easy to theend user.In Windows Phone 7 development, by default the screen is in Portrait mode and we have 3 types ofsupported Screen Orientations, as below  Portrait  Landscape(Left)  Landscape(Right)In order to use the orientation change within Windows Phone development, in the XAML page weneed to make use of the SupportedPageOrientation properties. We can make use of theseorientations in page level so that for each of the page we can specify a different orientation forbetter usability. The properties of SupportedPageOrientation can be one of the below options  Portrait  Landscape  PortraitOrLandscapeLet us see the steps involved in using Windows Phone 7 screen orientation effectively.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 152
    • Windows Phone Development Step by Step TutorialWe can see a new Windows Phone 7 Application created with the designer windows and the XAMLwindow open. Now we can see the Orientations mentioned in the XAML code highlighted in thescreen below. By default, we can see the Orientation is specified as Portrait.XAML Code:SupportedOrientations="Portrait" Orientation="Portrait"Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 153
    • Windows Phone Development Step by Step TutorialNow we will add some controls to have a good user look and feel, as shown in the screen. Once weadded the controls, your complete XAML code will look like the below listing where we can seeSupportedOrientaion=”Portrait”. Now run the application by pressing F5 and we can see theapplication in Portrait orientation, as shown in the screen below.XAML Code:<phone:PhoneApplicationPagex:Class="F5debugWp7Orientations.MainPage"xmlns="<ahref="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>xmlns:x="<ahref="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/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="<ahref="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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Orientations" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></StackPanel><!--ContentPanel - place additional content here--><Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 154
    • Windows Phone Development Step by Step Tutorial<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:Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 155
    • Windows Phone Development Step by Step TutorialWe can switch between the orientations right from the Emulator by clicking on the buttons shown inthe screen below.Now let us change the Orientation in the XAML Code to Landscape, as shown in the code below andrun the application once again and see the application output in the screen below.XAML Code:x:Class="F5debugWp7Orientations.MainPage"xmlns="<ahref="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>xmlns:x="<ahref="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/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="<ahref="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">Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 156
    • Windows Phone Development Step by Step TutorialLandscape:We can also control the orientation from the code behind programmatically by using one of the codesnippets below, as per the requirements.C# Code:// Portrait OrientationSupportedOrientations = SupportedPageOrientation.Portrait;// Landscape OrientationSupportedOrientations = SupportedPageOrientation.Landscape;// For Lanscape and PortraitSupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;Based on the application design and requirement, we can assign the orientation; customize it tocreate a better look and feel.SummaryIn this chapter, we have seen the different screen orientations which can be used in Windows Phone7 application development to create a good user experience.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 157
    • Windows Phone Development Step by Step Tutorial Working with BING Map ControlIntroductionIn this chapter, we are going to see the most useful control in Windows Phone 7 development, yesthe BING Map Control. The BING Map Silverlight control for Windows Phone 7 combines the powerof Silverlight and Bing maps to get the best mapping experience for developers and the real users tocreate a location based application.The BING Map control in Windows Phone 7 application development is derived from the namespaces Microsoft.Phone.Controls and Microsoft.Phone.Controls.Maps. Developers need to registerfor a BING Map developers account to get the keys which are used in developing an application withthe Bing Maps. Here in this chapter we will see the steps involved in using BING Maps control and toget the most enriching map applications.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 158
    • Windows Phone Development Step by Step TutorialNote – To get the BING Map Keys, we need to register a BING Map account using the below URLhttp://www.bingmapsportal.com/Once we register with a valid Windows Live ID, we need to login again and go to the section Createor View Keys under the My Account categoryNow 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 listOnce we provided the details, we will be provided with the BING Maps key, as shown in the screenbelow.Now we need to go back to the F5debugWp7BingMapControl project and start designing theapplication by dragging and dropping the BING Map control from the toolbox and some buttons, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 159
    • Windows Phone Development Step by Step TutorialXAML Code:<phone:PhoneApplicationPagex:Class="F5debugWp7BingMapControl.MainPage"xmlns="<ahref="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>xmlns:x="<ahref="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/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="<ahref="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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Bing Maps" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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">Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 160
    • Windows Phone Development Step by Step Tutorial<shell:ApplicationBarIconButton IconUri="/Images/appbar.share.rest.png" Text="Road View"Click="ApplicationBarIconButton_Click"/><shell:ApplicationBarIconButton IconUri="/Images/appbar.feature.video.rest.png" Text="AerialView" 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();}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 161
    • Windows Phone Development Step by Step TutorialBuild and execute the application to check if the first 2 buttons are working as expected. Press F5 tostart building the project and we can see the application loaded in the Windows Phone 7 Emulator inthe 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 messagewe need to make use of the key which we got after registering with the Bing Maps website. To dothis, go to the XAML Code and add the key to the BING Maps section, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 162
    • Windows Phone Development Step by Step TutorialXAML 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 andthe 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 respectivecode behind to get Zooming in and out.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 163
    • Windows Phone Development Step by Step TutorialC# 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 workingeffectively, as shown in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 164
    • Windows Phone Development Step by Step TutorialNow that we got the expected output as shown in the above screens, let us do an additional task ofpinning the location. Normally we need to do this while travelling using a map direction. To startcoding the PINNING option, first add the map1_MouseLeftButtonUp event and write the codebelow, 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);}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 165
    • Windows Phone Development Step by Step TutorialNow that we are done with our code, let us build and execute the application by pressing F5. We cansee the expected output. Just use the Mouse Up to click on the location shown in the WindowsPhone 7 Emulator to pin the location, as shown in the screens below.SummaryIn this chapter, we have seen how to use the BING Map control effectively within Windows Phone 7development to build a rich user interface.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 166
    • Windows Phone Development Step by Step Tutorial Working with Device InformationIntroductionIn this chapter, we are going to see how to get the Device information for managing the device. Wewill see how to make use of the Device detection API’s available in the Windows Phone 7 SDK todetect 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 havedifferent options to get the information of the device, network etc.. with the API. We will see onlyretrieving of the device information in this chapter. We are going to retrieve the below list of deviceinformation. S No Information Description1 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 device11 IsKeyboardDeployed Indicates if the user deploy the physical keyboard12 ApplicationMemoryUsageLimit Gets the maximum amount of memory.Let us see steps for implementing the device information class to get the information and display itto the end users.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 167
    • Windows Phone Development Step by Step TutorialStepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a validproject 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 withthe design, we can see that the screen looks like below. Copy the XAML code to get the same lookand feel. We can also directly drag and drop the controls from the toolbox and design it as per therequirements.XAML Code:<phone:PhoneApplicationPagex: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">Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 168
    • Windows Phone Development Step by Step Tutorial<!--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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Device Info" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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" />Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 169
    • Windows Phone Development Step by Step Tutorial<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>Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 170
    • Windows Phone Development Step by Step TutorialLet us start with our code to get the device information and load it to the respective text blocks asshown in the code below. We can use the Device Status class to get the details of the deviceproperties except the device unique ID. We will write the code later to get the unique ID of thedevice.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{// Constructorpublic MainPage(){Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 171
    • Windows Phone Development Step by Step TutorialInitializeComponent();}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 DeviceExtendedPropertiesproperty TryGetValue to get the Unique ID, since we get it as a byte array, we do a conversion to astring and assign it to the text block, as shown below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 172
    • Windows Phone Development Step by Step TutorialC# 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{// Constructorpublic 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 = "";}}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 173
    • Windows Phone Development Step by Step TutorialNow we are done with our code. Let us build and execute the application by pressing F5 directlyfrom the keyboard. We can see the application loaded to the Windows Phone 7 Emulator in thescreen below with the expected output.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 174
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to get the device information details and the device unique idusing the Device Status class in detail.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 175
    • Windows Phone Development Step by Step Tutorial Working with ThemesIntroductionIn this chapter, we are going to see how to effectively use Themes in Windows Phone 7 applicationdevelopment. As we all know, a theme is a set of resources which are used to maintain a consistentlook 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 animportant role.Some of the advantages of using Themes in Windows Phone 7 is consistency across the defaultcontrols 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 withoutdoing many changes. Themes in Windows Phone 7 are a combination of a background and an accentcolor. The background color is basically the background image color which we use in our applicationand 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 asAssent 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 themerelated color changes occur within the application scope.Theme resources are normally maintained in the TthemeResource.XAML file, the resources aremaintained based on the background color and the accent color selected by the user or thedeveloper. Theme resources files are available in the location below, based on the OS which we areusing.  64-bit – DriveNameProgram Files (x86)Microsoft SDKsWindows Phonev7.1Design  32-bit – DriveProgram FlesMicrosoft SDKsWindows Phonev7.1DesignLet us see the steps involved in using themes with Windows Phone 7 development.StepsOpen Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a validproject name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 176
    • Windows Phone Development Step by Step TutorialNow let us start with adding some colourful controls to the MainPage.XAML file and see how the UIgets affected when changing the theme. Just copy the below XAML code or drag and drop thecontrols from the toolbox and design the UI as shown in the screen below to get the same look andfeel.XAML Code:<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"><TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Themes" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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" />Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 177
    • Windows Phone Development Step by Step Tutorial<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 ofthemes in real time. The first Rectangle is designed to get the application resources details to fill theshape border color and background color, whereas for the 2nd rectangle we have directly specifiedthe color without getting the color from the application resource. Similarly we have done the samewith the Eclipse as well, such that the first one uses the application resource and the second one isdirectly assigned the color.Now to tell the Windows Phone runtime environment to take care of the necessary changes for thetheme, add the code below to the MainPage.XAML.cs page constructor, as shown in the screenbelow.C# Code:<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"><TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Themes" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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"Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 178
    • Windows Phone Development Step by Step TutorialStroke="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 screenbelow.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 179
    • Windows Phone Development Step by Step TutorialWe can see the output shows different Color for the first rectangle and the first eclipse since wehave assigned the Application resource when a theme comes into the picture. Now let us change thetheme and see how the theme affects the images. Click on the Start button from the emulator andgo 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 theoutput. We can see the Color again changes for the first rectangle and the first eclipse since they arecontrolled with the application resource, as shown in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 180
    • Windows Phone Development Step by Step TutorialNow on changing the themes we can see the complete Color shifting, as shown in the screens below.SummaryIn this chapter, we have seen what themes are in Windows Phone 7 development and the differencebetween using a theme and not using theme when application resources are used in real time.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 181
    • Windows Phone Development Step by Step Tutorial Working with Isolated StorageIntroductionIn 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 Storageis space provided to store data locally which is isolated from other applications. Each application canhave their own space (storage) so that other application’s data cannot be shared within theapplication which gives more security to the data. If we need to share the data then we can useAzure 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 datasuch as Storing data like Key-Value pair using the Files and Folders to store the data in separatefiles, 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 theapplication from accessing other application data and vice versa. Out of the three types of datastorage we can store in Isolated Storage, File and Folder plays a vital role in Windows Phone 7Application 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 usingIsolated 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 localIsolatedStorageFile. In Windows Phone 7 Application development, IsolatedStorageSettings is notthread safe so the application throws an IsolatedStorageException when Save is invoked.IsolatedStorageSetting class normally uses the 3 methods below to store and retrieve data withisolated 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 keyvalue pair.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 182
    • Windows Phone Development Step by Step TutorialStepsOpen Visual Studio 2010 IDE and Create a new Silverlight for Windows Phone 7 Application with avalid 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 addsome buttons to retrieve the data using the key and add one more button to delete the data usingthe same key. So once we add our controls, we can see the page design, as shown in the screenbelow.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 183
    • Windows Phone Development Step by Step TutorialXAML 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 themanipulations within the application.using System.IO.IsolatedStorage;Now let us start writing our code to use the IsolatedStorageSettings class. We need to first createan instance of the class and try to invoke the ADD Method to save the data.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 184
    • Windows Phone Development Step by Step TutorialCode 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 F5debugWp7IsolatedStorageKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 185
    • Windows Phone Development Step by Step Tutorial{ 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 usertypes in the text block. We need to create an instance of the IsolatedStorageSettings and use theinstance to call the ADD method by passing the Key and the Value. Here we have provided someKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 186
    • Windows Phone Development Step by Step Tutorialvalidation to first check if the Key (DataKey) is already available or if the data key is not available, wemake 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. Copythe code below to the Retrieve button click event. To retrieve the data the key value pair is accesseddirectly from the applicationsettings property of IsolatedStorageSettings, as shown in the screenbelow.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; } elseKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 187
    • Windows Phone Development Step by Step Tutorial { textBlock2.Text = "Key Not Found"; } }Finally, let us write the code to delete the data using the key (DataKey). Here also we need to usethe ApplicationSettings Property to access the data using the Key and delete it using the Removemethod, 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"); } }Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 188
    • Windows Phone Development Step by Step TutorialNow that we are done with the code, we can build and execute the project by simply pressing the F5button from the keyboard or use the Toolbar to select the Build and Execute solution. Once theapplication is built, we can see the application opened in the Windows Phone 7 Emulator, as shownin the screen below. We can play around with the application by adding data and retrieving the datausing the key, which we assigned internally.Output Screens:SummaryIn this chapter, we have seen what Isolated Storage is in Windows Phone 7 Development and wehave seen how to use Key Value Pairs to save and retrieve data effectively. In our upcomingchapters, we will see how to use Files and Folders to save data in Isolated Storage.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 189
    • Windows Phone Development Step by Step Tutorial Working with Files and FoldersIntroductionIn 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 alocation to store the user data locally to manipulate. Here, with Windows Phone 7 development wehave Isolated Storage to store data in an isolated location which is accessible to that particularapplication only. In our previous chapter, we have seen what Isolated Storage is and we have seenhow 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 andFolders:  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 folderLet us see the steps involved In using Files and Folders to store data locally with a Windows Phone 7device.StepsOpen Visual Studio 2010 as an administrator and create a new Silverlight for Windows Phone 7project with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 190
    • Windows Phone Development Step by Step TutorialThe IsolatedStorageFileStream class is used in Windows Phone 7 Development to read, write andcreate files in Isolated Storage. We can create an instance of this class to get the stream of an objectto read and write using the StreamReader and StreamWriter. To start, let us first design a uniqueinterface by using the controls from the toolbox. Once the design is completed, we can see thescreen, 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-->Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 191
    • Windows Phone Development Step by Step Tutorial<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"><TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Files N Folder" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 towork with files and folders. First, we need to import the namespace required for Isolated Storage byadding the below 2 namespaces to the code behind.Code Behind:using System.IO;using System.IO.IsolatedStorage;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 192
    • Windows Phone Development Step by Step TutorialTask 1 – Write text to a text fileNow our first task is to write some data to a text file and store it in isolated storage. We need to usethe IsolatedStorageFile class instance to get the user store for the specific application and to writethe file we need to use the IsolatedStorageFileStream by providing the parameters that are requiredto 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");}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 193
    • Windows Phone Development Step by Step TutorialTask 2 – Read the text fileOur next task is to read the text file from the root folder where we saved the text data in ourprevious task. For this task, we again need to use the IsolatedStorageFile Class andIsolatedStorageFileStream 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 fileIn this task, we are going to see how to delete the text file from Isolated Storage which we created inour previous tasks. To delete the file, we need to make use of the IsolatedStorageFile class andinvoke the DeleteFile method by passing the filename directly, as shown in the code below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 194
    • Windows Phone Development Step by Step TutorialAlso, to delete a folder, we can use the DeleteDirectory method which does a similar process ofdeleting 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 folderOur next task is to write some text to a text file and save the file to a specific folder for easy data filemaintenance within Isolated Storage. Normally, this task is very important for developing anapplication with Windows Phone 7 to store data locally in a folder.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 195
    • Windows Phone Development Step by Step TutorialCode 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");}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 196
    • Windows Phone Development Step by Step TutorialTask 5 – Read the text file inside a folderOur final task is to read the file which we created and saved in a particular folder in our previoustask. This task uses the same IsolatedStorageFile and IsolatedStorageFileStream to read the data, asshown 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());}}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 197
    • Windows Phone Development Step by Step TutorialNow that we are done with the complete tasks, we can see the expected output, as shown in thescreen below. To build and execute the project, simply press F5 from the keyboard or from theVisual Studio toolbar.Output Screens:SummaryIn this chapter, we have seen Files and Folders in Isolated Storage for Windows Phone 7development using the IsolatedStorageFile class. In our next chapter, we will see how to use thelocal storage database to read and write data.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 198
    • Windows Phone Development Step by Step Tutorial Creating a Local DatabaseIntroductionIn this chapter, we are going to see the usage of Isolated Storage by creating a local relationaldatabase and save data locally that it is accessible to the specific Windows Phone 7 application. Thelocal relational database will be created in the Isolated Storage Container where in Windows Phone7, we need to make use of LINQ to SQL for all the database operations. LINQ to SQL plays a majorrole in creating the data schema, selecting the data and making operations on the data as and whenrequired. The LINQ to SQL object model uses the System.Data.Linq.DataContext namespace tobasically make a proxy call to the local database in the Isolated Storage container. The LINQ to SQLRuntime 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 toconsider some of the points mentioned below to get as much performance and usage over theapplication.  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 IsolatedStorage Local database using the Data Context class with a sample application. We will get clear ideaon 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 databaseLet us see the steps on how to achieve the above tasks with the Isolated Storage Local Database inWindows Phone 7 Application development by creating a sample application.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 199
    • Windows Phone Development Step by Step TutorialStepsOpen Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7Application 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 toget a unique user interface with the controls provided to achieve each and every task, as shown inthe screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 200
    • Windows Phone Development Step by Step TutorialXAML 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="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="Employee DB" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 startusing the data object model and the data schema to perform the operations. Let us start with addingthe LINQ to SQL data context reference by right clicking the project from solution explorer andadding the reference from the Add Reference menu, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 201
    • Windows Phone Development Step by Step TutorialOnce we added the reference for System.Data.Linq to the application, we need to add the belownamespaces 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;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 202
    • Windows Phone Development Step by Step TutorialNow our first task is to create a database. Since we are going to use the LINQ to SQL data context asa bridge between the local database and the data context, we need to create 2 classes as shownbelow.The first class is the Employee class, which holds the properties for the fields that are tables andcolumns which are used to build the database. Copy the code below to a new class, as shown in thescreen below. The class has 3 properties that are going to be the data columns which we are going toget as inputs from the end users. In the code below, we are providing the properties for each of thecolumn with one being a primary key and other are not null etc, which we need to specify based onthe 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;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 203
    • Windows Phone Development Step by Step Tutorialnamespace 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 thedatabase schema to create an instance. Copy the code from the code block below to create it.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 204
    • Windows Phone Development Step by Step TutorialCode 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 werementioned above.Task 1 – Creating a local databaseFirst let us start with creating a database, which is the very first step we need to perform when weare going to use the local database storage. We need to have a connection string, which is pointingto the local database storage. Let us create the connection string as a private constant, as shown inthe code below.Code Behind:private const string strConnectionString = @"isostore:/EmployeeDB.sdf";Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 205
    • Windows Phone Development Step by Step TutorialNow we need to add the code below to create a database instance. Here we are going to create aninstance of the Data context by passing the connection string, which is pointing to the local databasestorage, 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 databaseOur second task is to add some records to the database. To add the employee, we need to create aninstance of the data context and pass the properties that match the column properties which weKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 206
    • Windows Phone Development Step by Step Tutorialcreated in our data context initially. Here we are going to add an employee which has an EmployeeID, Employee Name and Employee Age. We have created the instance and passed the valuesappropriately. Once we fetch the user inputs, we need to insert the details on submit, so we use theInsertOnSubmit 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 databaseOur next task is to fetch a consolidated list of data from the local database. So in order to fetch thedata, 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 stringbuilder to consolidate the data as user readable, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 207
    • Windows Phone Development Step by Step TutorialCode 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());}Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 208
    • Windows Phone Development Step by Step TutorialTask 4 – Deleting data from the local databaseOur next task is to delete the user specific data from the local isolated storage database. This isstraight forward as we query the data from the data context and delete it, as shown in the screenbelow.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!!!"); } }Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 209
    • Windows Phone Development Step by Step TutorialTask 5 – Deleting a local databaseOur final task is to delete the database completely once the user removes the application from thedevice. 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 andpaste it directly on to the cs page for easy access to the code which we have in the above 5 tasks.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 210
    • Windows Phone Development Step by Step TutorialConsolidated 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))Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 211
    • Windows Phone Development Step by Step Tutorial{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)Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 212
    • Windows Phone Development Step by Step Tutorial{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 theexpected outputs in the screen below.Output Screens:Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 213
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to use the local Isolated Storage to create and use a database byusing a LINQ to SQL data context and we have seen the different steps to achieve the tasksmentioned at the start of this chapter.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 214
    • Windows Phone Development Step by Step Tutorial Consuming an ODATA ServiceIntroductionIn this chapter, we are going to see how to consume an ODATA service in a Windows Phone 7application. ODATA means Open Data Protocol, an entity model used to access data as a RESTservice, which can be used to execute queries and to create, update and delete data on to theremote data service. An ODATA service allows the consumers to query the data over the HTTPprotocol and retrieve the result in a plain XML format. Normally, a mobile application developmentrequires data that is available as a service which can be consumed and used on demand, where theODATA Service plays a major role. We have a variety of ODATA services that are available in themarket; 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 andupdating data that provides a way to unlock your data and free it from silos that exist in applicationstoday. OData does this by applying and building upon Web technologies such as HTTP, AtomPublishing Protocol (AtomPub) and JSON to provide access to information from a variety ofapplications, services, and stores. The protocol emerged from experiences implementing AtomPubclients and servers in a variety of products over the past several years. OData is being used toexpose and access information from a variety of sources including, but not limited to, relationaldatabases, file systems, content management systems and traditional Web sites.We have a comprehensive list of public ODATA Services that can be consumed from the clientdevices using the link http://www.odata.org/producers. Let us see the steps involved in consumingan ODATA Service in our Windows Phone 7 application and how to make use of it efficiently.StepsOpen Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7project with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 215
    • Windows Phone Development Step by Step TutorialNow we need to design our XAML page where we want to show our consumed ODATA service. Wecan use a Listbox and dynamically bind the data which we consume, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 216
    • Windows Phone Development Step by Step TutorialXAML 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 applicationand page title--><StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"><TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="OData Service" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/><!--<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 sampleapplication, we will make use of Telerik Video’s ODATA service which is available to the public. TheODATA service is available using the URI http://tv.telerik.com/services/odata.svc/. To add theODATA service, right click on the project name and select Add Service Reference, as shown in thescreen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 217
    • Windows Phone Development Step by Step TutorialClicking on Add Service Reference will open a pop window where we need to provide the OATAService URI. Click on the Go button to discover the service online. Once the service is discovered, weneed 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 addedto the service reference folder. Now that we are ready with the service, our next step is to writesome code that will do the necessary process to get the data from the service and show it to theuser interface. Add the below 2 namespaces, which are required to consume and get the data fromthe ODATA service.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 218
    • Windows Phone Development Step by Step TutorialCode 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 thereference, which we added to the project, and get the ODATA service URI, which is used to create areference, while consuming the service, as shown in the code below.Code Behind:private ODataDataSource TelerikEntity;private static string strODataURI = "<ahref="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 createthe instance, we can query the data from the DataServiceCollection by just using a LINQ query, asshown in the screen below. Copy and paste the code below into the button click event to proceedfurther.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 219
    • Windows Phone Development Step by Step TutorialCode 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.Videosselect 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 datato 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();}elseKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 220
    • Windows Phone Development Step by Step Tutorial{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 = "<ahref="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);Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 221
    • Windows Phone Development Step by Step Tutorialvideos = new DataServiceCollection<Video>(TelerikEntity);var queryvideo = from vid in TelerikEntity.Videosselect 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 expectedresults are shown in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 222
    • Windows Phone Development Step by Step TutorialOutput Screens:SummaryIn this chapter we have seen what an ODATA service is and how to consume a service from aWindows Phone 7 application.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 223
    • Windows Phone Development Step by Step Tutorial Consuming a WCF ServiceIntroductionIn this chapter, we are going to see how to consume a WCF Service in a Windows Phone 7Application Development. For the beginners, WCF stands for Windows Communication Foundation,a Microsoft framework to build applications with a Service Oriented Architecture. We can use WCFas a service to send data across the application with the endpoints predefined to communicate. Theservice endpoints can be hosted on an IIS Server and be available anytime, or it can also be anapplication oriented service to provide on demand usage. The data transfer through the messagescan 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 aservice through some authorized protocols and secured ports where WCF plays a major role. Let ussee the steps involved in consuming a WCF Service in a Windows Phone 7 Application, taking intoconsideration 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 linkhttp://msdn.microsoft.com/en-us/library/ms733766.aspxStepsOpen Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7Application with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 224
    • Windows Phone Development Step by Step TutorialWe can see the project is created and the main page is opened with the default controls. Let usconsider that we have a WCF application already created and hosted on IIS which can be consumedand when passed a value (2 numbers), it will get output as the sum of the values passed. So from ourWindows Phone 7 application, we can pass 2 values and make WCF do the sum and send the resultback, which can be viewed in the application.First, let us add some controls which get the user’s input that should be passed to the WCF Serviceand display the results to the end users. Copy the XAML code provided below to get the same userinterface with respect to the design.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 225
    • Windows Phone Development Step by Step TutorialXAML 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 applicationand page title--><StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"><TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResourcePhoneTextNormalStyle}"/><TextBlock x:Name="PageTitle" Text="WCF Service" Margin="9,-7,0,0" Style="{StaticResourcePhoneTextTitle1Style}"/></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 Servicereference. We can see a pop up window where we need to input the WCF Service and the details, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 226
    • Windows Phone Development Step by Step TutorialClicking on OK will add the service reference to the project file and we can see the service referencefiles added with the name provided in the namespace along with some reference files as well. Weneed to create our code logic to consume the service and pass the values, as shown in the codebelow.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;Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 227
    • Windows Phone Development Step by Step Tutorialusing 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{// Constructorpublic 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 += newEventHandler<WCFServiceToSumData.Add2NumbersCompletedEventArgs>(client_getStringCompleted);}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 bypressing F5 from the keyboard or from the toolbar. We can see the expected results once we passthe data, as shown in the screens below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 228
    • Windows Phone Development Step by Step TutorialOutput Screens:SummaryIn this chapter, we have seen how to make use of a WCF service which we created locally or toconsume a 3rd party WCF Service and get the desired output, as per the requirement in WindowsPhone 7 application.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 229
    • Windows Phone Development Step by Step Tutorial Encrypting Data for SecurityIntroductionIn this chapter, we are going to see how to encrypt data and use it in a Windows Phone 7application. Security is a concern for developing applications with mobile since misusing of data likepasswords, connection strings etc. are highly possible which we need to take care by encrypting anddecrypting wherever possible. In Windows Phone 7, we have the Data Protection API, which can beused to encrypt data, store confidential data within the Application’s Isolated Storage or withencrypting using local keys is not highly secure since the keys that are required to decrypt the datawill reside on the device itself. The Data Protection API solves this problem by explicitly generatingand storing the key. The ProtectData class is used to access the Data Protection APIs that can beused 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 encryptand decrypt the data as and when required, while using dynamic key generations as and whencalled. Let us see the steps for using these methods to encrypt and decrypt in this chapter.StepsOpen Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7application with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 230
    • Windows Phone Development Step by Step TutorialNow let us design the application to get the inputs from the user to encrypt the data and store thepin in isolated storage using the Protectdata method. Once we added the controls to the page wecan 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 toimport some namespaces which are not available initially. Copy and paste the 4 namespaces belowto the code behind.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 231
    • Windows Phone Development Step by Step TutorialCode 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 theuser inputs, as shown in the screen below. In this code we are going to encrypt the pin to a bytearray 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);Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 232
    • Windows Phone Development Step by Step Tutorialwriter.Close();swIS.Close();}Now we are done with the code to encrypt the data. We use the Writedata private method to storethe data to Isolated Storage by using the Isolated Stream Class. Once the pin is encrypted, we haveprovided a message box to indicate to the user that the data is encrypted correctly. Now let usdecrypt the data on the second button click event.Decrypting the data will be done using the UnProtect method, which reads the data from IsolatedStorage, 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];Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 233
    • Windows Phone Development Step by Step Tutorialreader.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 bypressing F5 directly from the keyboard. We can see the application loads in the Windows Phone 7Emulator. Input sample data and we can see the encryption and decryption happening, as shown inthe screens below.Output Screens:SummaryIn this chapter, we have seen an interesting API, to encrypt and decrypt data which can be usedwhen required with the application development.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 234
    • Windows Phone Development Step by Step Tutorial WP7 Tool kit for SilverlightIntroductionIn this chapter, we are going to see how to use the Windows Phone 7 Tool Kit for Silverlight, which isavailable as open source and can be downloaded and installed to the local developer machine to usein application development. The toolkit has been localized to support all the new languagessupported by Mango along with new Mango specific controls like the HubTile, localization etc. Thetoolkit provides a rich set of controls which are available to kick start the development process withease. We just need to download the tool kit and do some installation steps to make the tool kit fitsin 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 forWindows Phone 7. Before that, we need to download the tool kit from the location below and havethe set up ready.Link – http://silverlight.codeplex.com/releases/view/75888Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 235
    • Windows Phone Development Step by Step TutorialStepsOnce we download the package from the above link, run the package and we can see the wizard toinstall the package shown in the screens below. Just complete the installation and we can see thetool 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 thescreen below. We can see the installation has occurred in the pathC:Program Files (x86)Microsoft SDKsWindows Phonev7.1ToolkitOct11We can access the tool kit sources here. Now let us open Visual Studio 2010 and create a newSilverlight for Windows Phone 7 project with a valid project name, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 236
    • Windows Phone Development Step by Step TutorialOnce the project is created, we will add a reference to the Microsoft Windows Phone tool kit. To dothat, right click on the project and select add reference and point to the folder where the tool kit isinstalled (C:Program Files (x86)Microsoft SDKsWindows Phonev7.1ToolkitOct11Bin) and selectthe 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, asshown in the screen below. This will be standard across the project. Here we are just telling theXAML loader that we are going to use the tool kit namespace within the page. We need to add thisnamespace to all the pages wherever we use the controls.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 237
    • Windows Phone Development Step by Step TutorialXAML 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 justgo 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 theapplication starts, we will get the autocomplete text box loaded with the predefined data.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 238
    • Windows Phone Development Step by Step TutorialCode 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{// Constructorpublic MainPage(){InitializeComponent();Loaded += new RoutedEventHandler(MainPage_Loaded);}void MainPage_Loaded(object sender, RoutedEventArgs e){List lstnames = new List();lstnames.Add(“Karthik”);lstnames.Add(“Ram”);Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 239
    • Windows Phone Development Step by Step Tutoriallstnames.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 andwe can see the application loads with the emulator. Just input the starting letter and we can see theautocomplete box pulls the complete phrase in the screen below.Output Screens:SummaryIn this chapter, we have seen how to download, install and then use the Windows Phone 7 tool kit todevelop a productive application. We saw an example of using the Autocomplete text box.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 240
    • Windows Phone Development Step by Step Tutorial Deploying Application to MarketplaceIntroductionIn this chapter, we are going to see how to deploy an application to the marketplace. WindowsPhone Marketplace is a portal where we need to publish the applications developed using theWindows Phone SDK and make it available to the public for download. Windows Phone Market is aone stop portal where users can purchase apps or games using credit cards or download freeapplications with ease and provide reviews to applications that are very helpful.Microsoft Windows Phone Marketplace can be accessed using the linkhttps://windowsphone.create.msdn.com. As a developer, we need to register with the market placeto 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 ofregistration. Once we registered with the App Hub, the marketplace for Windows Phone, we areable to upload our application to the marketplace with ease, provided the application follows somevalidation procedures, which are listed by Microsoft. As a developer, we need to take care of all thecertification procedures. You can get a detailed idea on the certification procedures andrequirements in the MSDN link http://go.microsoft.com/fwlink/?LinkID=183220Now let us steps involved in publishing the application to the Windows Phone Marketplace. Once weare done with the design and development of the application, we need to build the final version in aRelease Build and see the Application package created a .XAP file, which is the extension of theWindows Phone package accepted in the marketplace. Remember that the package size should notexceed 225MB in size, which is the maximum size allowed. The package will be located in the BINfolder of the project, under Release build, as shown in the screen below. The below application isbuilt and completed in release mode and we can see the .xap file created with the name of theproject.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 241
    • Windows Phone Development Step by Step TutorialNow login to the marketplace and we can see the option to select which type of application we aregoing to upload to the marketplace. The account registered here was a developer account so wehave a limitation of submitting 100 free applications and unlimited paid applications, as per thestandards followed by Microsoft. At the left side we have the metro tile indicating Submit forWindows Phone and Submit for Xbox 360; We need to select Submit for Windows Phone, since ourapplication 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 ApplicationSubmission page, where we need to input our application details and the package (.XAP file) in orderto 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, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 242
    • Windows Phone Development Step by Step TutorialProviding the application details and clicking on the NEXT button will start uploading the package tothe server, which may take time depending on the size of the application uploaded. We can see theprogress 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 needto describe the application and the category to which the application fits in. It is very important tochoose 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 applicationwhich will be the place we explain the purpose of the application so that it reaches the audience, asshown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 243
    • Windows Phone Development Step by Step TutorialFollowing the description, we need to provide some basic information like our website URL, and theemail 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 arerequired for the application as well as for the marketplace which showcases our application to theend users. The Artwork has different icon dimensions which need to be taken care of prior tostarting the upload of the application. Check this MSDN chapter on handling icons and screen shotrequirements before uploading the application to the marketplace. http://msdn.microsoft.com/en-us/library/gg442300%28v=vs.92%29.aspxKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 244
    • Windows Phone Development Step by Step TutorialOnce we uploaded the tile images, icons and the screen shots, we need to click on NEXT and proceedto the next section. The next screen is the place where we need to specify the price of ourapplication, as per the developer’s choice. We have the option to select the target country or worldwide. We need to select the base amount and click on Select all in the World Wide distribution tosubmit the application to the larger audience. Once selecting the above options, click on Next toproceed further.Clicking on Next will proceed to the final section, where need to provide our inputs to the testingteam. Once we provide the instructions, we need to select the publish option, based on the 3options provided. Once we are done with the selection, click on Next to complete the applicationsubmission procedure, as shown in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 245
    • Windows Phone Development Step by Step TutorialOn successful submission, our application will be uploaded to the marketplace and it will be in thecertification stage. We will see the submission success message, as shown in the screen below. Clickon 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 thelife cycle. The process flows to complete the validation and certification process of the application tothe marketplace, are displayed in the screen below.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 246
    • Windows Phone Development Step by Step TutorialSummaryIn this chapter, we have seen how to package and publish the application to the Windows Phone 7Marketplace, with a step by step approach to overcome the certification issues.Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 247
    • Windows Phone Development Step by Step Tutorial F5debug - Windows Phone AppsBelow is the list of window phone application that are developed and made available as freedownload for the community by the Author Karthikeyan Anbarasan, Microsoft MVP. Application S No Name Deep Link http://www.windowsphone.com/en-us/apps/4c30f162-7cac-434e- 1 Aarupadai Veedu 83b5-618285cada3b http://www.windowsphone.com/en-us/apps/cdd1fbbf-d175-46bd- 2 Tirupati Balaji 95d3-cd13124b6dff http://www.windowsphone.com/en-us/apps/e7a9de20-8cd2-4110- 3 Kolangal 9ea2-f9aeaf3e70fe http://www.windowsphone.com/en-us/apps/9d5100e6-e273-440e- 4 Tamil Disc Floor bf70-57d2c739fd3a http://www.windowsphone.com/en-us/apps/cf693e33-1f2d-4899- 5 Chennai Auto Fare 9223-1670d8b0ac4e http://www.windowsphone.com/en-us/apps/02b40520-75e8-4f2e- 6 Chennai Postal Code aa2c-88b346562cc2 http://www.windowsphone.com/en-us/apps/77840e9a-0d45-432d- 7 TamilNadu RTO Finder ba5a-79235d81d9d4 http://www.windowsphone.com/en-us/apps/bcdd6c17-cc18-47d9- 8 Distance to Central 8242-fbc8bf15e830 http://www.windowsphone.com/en-us/apps/53e8c5c8-d543-47c6- 9 Navagraha Temples 97bb-16ca22152193 http://www.windowsphone.com/en-us/apps/7505422f-b2d3-44ee- 10 Start Blogging 97e1-387826b6ad37 http://www.windowsphone.com/en-us/apps/a7d1939e-01b6-4373- 11 VadivelComedy 99e0-f2c2102183cc http://www.windowsphone.com/en-US/apps/7c61caea-943d-4716- 12 F5Debug a436-29ba6f35a7bbKarthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 248