Windows phone development step by step tutorial

2,323
-1

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,323
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
117
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Windows phone development step by step tutorial

  1. 1. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 1
  2. 2. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 2 Copyright This is a preliminary document and may be changed substantially. The information contained in this document represents the current view of the author as of the date of publication. This EBook is for informational purposes only. WE MAKE NO WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in, or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of its author. Unless otherwise noted, the example companies, organizations, products, domain names, e- mail addresses, logos, people, places, and events depicted in this document are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. ©2012 Karthikeyan Anbarasan, (www.F5debug.Net) All rights reserved.
  3. 3. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 3 I dedicate this eBook to my Parents and my Wife, who make it all worthwhile. — Karthikeyan Anbarasan, Microsoft MVP www.f5debug.net
  4. 4. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 4 ABOUT THE AUTHOR Karthikeyan Anbarasan, Microsoft MVP (Most Valuable Professional) in ASP.NET/IIS Architecture and founder of the blog www.f5debug.net, has over 6 years’ experience on Microsoft Technologies (Windows Phone, Windows Azure, SQL Azure, Public and Private Cloud, ASP.Net, C#.net, VB.Net, ADO.Net, Ajax, SQL Server, SSIS, SSRS, SSAS, Biztalk Server, IBM MQ Server, WCF, WPF and some tools like Telerik, Infragisitcs, Syncfusion, etc..) and he is a Mindcracker and DNF Most Valuable Professional. Karthik works for 8KMiles Software Services as a Technical Cloud Architect and in his free time used to write articles on any of the Microsoft technology and products which he is familiar with. He has been certified by Microsoft in few of the technologies and has been awarded by the largest community groups like Mindcracker MVP, Dotnetfunda MVP. Certifications:  Microsoft Certified Professional.  Microsoft Certified Application Developer.  Microsoft Certified Solution Developer.  Microsoft Certified Technology Specialist in Web & Windows Application.  Microsoft Certified Technology Specialist in BizTalk Server.
  5. 5. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 5 ACKNOWLEDGEMENT I would like to express my heartful thanks to Mahesh Chand (Founder of Mindcracker Networks) and Pinal Dave (Founder of Blogs.SQLAuthority.com), for constant motivation in publishing this second eBook of mine. I have always been a big believer in advocating free knowledge and education for all. To continue this belief, I have personally begun writing free distributable books for the community. Please feel free to share this book with your friends and co-workers. Also, do not forget to share your knowledge and spread the word around about the blog www.F5Debug.net. I should also mention about my website www.f5debug.net, which has always inspired me to write more on .NET and related technologies. Thanks to Daniel and Mahesh Chand for reviewing and checking the technical accuracy of the Book. A special thanks to my wife who complied and formatted this book. DISCLAIMER The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this eBook. The strategies contained herein may not be suitable for every situation. Neither the publisher nor the author shall be liable for damages arising here from. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
  6. 6. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 6 TABLE OF CONTENTS Windows Phone Overview .............................................................................................................8 Hello World Silverlight Application..............................................................................................15 Working with Alarms/Reminders ................................................................................................38 Working with Contacts .................................................................................................................47 Working with Calendar.................................................................................................................51 Working with Camera...................................................................................................................56 Working with Panorama Control .................................................................................................63 Working with Pivot Control..........................................................................................................70 Working with Media.....................................................................................................................75 Working with Toast Notifications ................................................................................................81 Working with Tile Notifications ...................................................................................................93 Working with Raw Notifications ................................................................................................107 Working with Tiles ......................................................................................................................119 Working with Launchers.............................................................................................................127 Working with Choosers ..............................................................................................................132 Working with Navigation............................................................................................................138 Working with Web Browser Control .........................................................................................145 Working with Screen Orientation..............................................................................................152 Working with BING Map Control ...............................................................................................158 Working with Device Information .............................................................................................167 Working with Themes ................................................................................................................176 Working with Isolated Storage ..................................................................................................182 Working with Files and Folders..................................................................................................190 Creating a Local Database ..........................................................................................................199 Consuming an ODATA Service ...................................................................................................215 Consuming a WCF Service..........................................................................................................224 Encrypting Data for Security ......................................................................................................230 WP7 Tool kit for Silverlight.........................................................................................................235 Deploying Application to Marketplace......................................................................................241 F5debug - Windows Phone Apps...............................................................................................248
  7. 7. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 7
  8. 8. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 8 Windows Phone Overview Introduction In this chapter we are going to see what Windows Phone 7 is and what are the hardware and software requirements for developing a Windows Phone 7 Application and we are also going to see the software development kit used to develop the application with Visual Studio 2010 IDE. Windows Phone 7 applications are built on existing tools from Microsoft like the Visual Studio 2010 IDE, Expression Blend, Silverlight and XAML code. Windows Phone 7 provides 2 types of frameworks upon which we can develop the applications and the types are as follows  Silverlight Framework – With this framework we can develop event based XAML applications for enterprise and consumer based application development.  XNA Games Framework – As the name suggests, with this framework we can develop rich games (2D and 3D) targeting the entertainment category. With Windows Phone 7 we can develop applications accessing the framework internally, though we have restrictions over developing applications targeting the native application development which is a bit disappointment. We can develop native applications with Windows Phone 7 using VC++ but with some restrictions over using multi-tasking and its features. We can also make use of the .Net Compact framework which has support over Windows Phone 7 Development. Before we start developing Windows Phone 7 applications, we need to have a look at the requirements to set up the development environment. Microsoft has suggested the software and hardware requirements which need to be considered when we start developing the application. The hardware requirements are mainly for the device manufactures to certify the hardware required to have better performance for the application that runs on the devices. As far as the software development is concerned we need to have the latest updates running so that we can make use of the framework more effectively and to have a better application developed using the latest features. Initially it was Windows Mobile (6.0, 6.5) where Microsoft provided developers, the ability to play around with the development of applications for mobile. We need to first know that Windows Mobile and Windows Phone 7 are 2 different platforms even though both run on top of the CE Kernel as far as the APIs are concerned. Windows Mobile and Windows Phone 7 do not have support to run applications between the different platforms.
  9. 9. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 9 Hardware Requirements Below are some of the hardware requirements the device manufactures needed to take care of while designing the device. These are the minimum requirements that should be considered and can have variations to have a better performing device. As a developer we will not have much control over these requirements, but developers can target the application development based on the device with the hardware requirements specified. When considering Windows Mobile we can say Windows Phone 7 has a higher configuration for device manufactures as below.  Multi Touch (4 Ways) Capacitive screen  DirectX 9 Acceleration  Accelerometer  Global Positioning System(GPS)  5 megapixel camera with flash  8 Gig Bytes Storage  256 MB of RAM  Button Controls The items mentioned above are the minimum requirements, so a device can have a maximum capacity to perform better. When we consider setting up the development environment for the Windows Phone 7 Software Development Kit, we need to consider the requirements below to setup the software. The Windows Phone 7 SDK is supported with one of the below OS’s with all the versions except the express version i.e. the Starter Versions  Windows Vista (All Editions)  Windows Phone 7 (All Editions) Some of the OS which are not supported with the Windows Phone 7 SDK installations are as below.  Windows XP  Windows 8  Windows Server  Windows Virtual Machines Also we need to have the below hardware requirements for the development environment  Minimum 4GB Hard disk Space  Minimum 3GB Ram  DirectX 10 or above capable graphics card with a WDDM 1.1 driver
  10. 10. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 10 Software Requirements Once we are ready with the hardware setup of the environment we need to install the required software to start with the development of Windows Phone 7 Applications. To start with, Microsoft has provided all of the required and supported software with the SDK, which we can just download from the link Windows Phone SDK 7.1 This SDK will install the development environment, providing options for the developers to develop applications and games on both Windows Phone 7.0 and Windows Phone 7.5. The above Windows Phone SDK 7.1 installs a list of products, which are in the list below.  Microsoft Visual Studio 2010 Express for Windows Phone  Windows Phone Emulator  Windows Phone SDK 7.1 Assemblies  Silverlight 4 SDK and DRT  Windows Phone SDK 7.1 Extensions for XNA Game Studio 4.0  Microsoft Expression Blend SDK for Windows Phone 7  Microsoft Expression Blend SDK for Windows Phone OS 7.1  WCF Data Services Client for Window Phone  Microsoft Advertising SDK for Windows Phone Once the installation of the Windows Phone 7.1 SDK is complete, we can see new templates are added to the Visual Studio 2010 IDE (Silverlight for Windows Phone 7 and XNA Games Studio). We are set to start with the application development. Windows Phone 7 Architecture The architecture of Windows Phone 7 is made on top of 4 main components, where each component, internally has many items to be seen in depth, which we will see in our upcoming chapters. Taking a quick look at the below figure will give us some idea on the architecture.
  11. 11. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 11 The 4 main components on which the Windows Phone 7 Architecture is built are as follows  Runtimes – Silverlight and XNA frameworks provide us with an excellent environment for the developers to build an optimized application.  Tools – Visual Studio IDE, Expression Blend and the tools provide the developers with flexibility to design and develop user rich applications.  Cloud Services – Windows & SQL Azure, Notification Services, and Location Services provide developers with usage of data across the frameworks with support over other 3rd party services as well.  Portal Services – Windows Phone Market Place provides developers with upload and certifying the application to the market. Where Silverlight Framework fits in Windows Phone 7? Silverlight is basically used for light weight business applications and normal 2D game development using XAML (Extensible Application Markup Language) Programming. Developers will have flexibility in using this framework along with most used UI tools like Microsoft Blend, Adobe Photoshop etc. to create a vector based process that can be easily transported to XAML. This is really not a new topic compared to the XNA development since Silverlight is already in market for developing rich browser applications and it provides an option of creating applications with XAML which is highly advantageous for creating a vector based applications. So it gives the developers full control of the layout, design, structure and also the data binding components. Silverlight application development for Enterprise or Consumers looks like the image below.
  12. 12. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 12 Where XNA Framework fits in Windows Phone 7? XNA is basically used for developing rich games where the framework comes with a game engine (with 3D) which helps game developers to provide rich 3D games. Unlike Silverlight, XNA is not much known across the developers since it has been used to develop Xbox games using Managed code. Why Microsoft provided the XNA engine with the windows phone 7 is mainly because of integration of Xbox live integration with Windows Phone 7. The XNA engine provides the rich user experience that every developer can take advantage in providing next generation games with 2D and 3D game loop engines. XNA Game Studio application development for entertainment or for the enterprise looks like the image below.
  13. 13. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 13 How Windows Azure Cloud fits in Windows Phone 7? When we create an application with Windows Phone 7, we need to save some data for future retrieval which is going to be a bit tougher here. Windows Phone 7 doesn’t provide direct connectivity with a database to save the data. To overcome this we need to use AZURE. Windows Azure provides the platform of Cloud Computing for storing and retrieving data from different locations using Windows Phone 7. For example, say today we create a small application in Windows Phone 7 using Silverlight. Day to- day when the development increases and we finally get an excellent product, then the number of user visit gets increased which eventually requires an enterprise database to save the details. So in this case we can use the Azure availability of extending the size of the database as per the need since it is maintained in the cloud. Microsoft has provided us with an additional advantage of using Bing Maps which is given free of cost, only for Windows Phone 7. Additionally Push notification services are also provided in the cloud using which we can send notifications to the mobile, such as Text which is eventually a better process for the business needs.
  14. 14. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 14 Windows Phone 7 Development Life Cycle As developers of Windows Phone 7 applications, we need to register with App hub using the below link http://create.msdn.com/en-US/ by giving our Windows Live credentials which act like a single sign on for all the process which Microsoft provides. The main idea behind registering with App hub is, once we register and develop an application in Windows Phone 7 we can use our registered handset as a physical device to test our application. App Hub provides developers with up to 3 devices that can be registered and tested it in real-time. Now let us understand the steps involved in setting up our account. Steps to Register with the APP HUB Market Place: Step 1 – Register with App Hub. As mentioned above, App hub is the Microsoft place where we need to register and use for testing our application in real-time. Please follow the steps below to register in App Hub. Step 2 – Market Place Certification Procedures. Once we are registered with App Hub, before proceeding with the development, consider reading the certification process document in order to avoid rejection of the product at the market level. Please refer to the below link for the Application Certification process checklist and validation. http://go.microsoft.com/?linkid=9730558 Once the development is completed and the validation process is checked and passed by the Market, then the application will be available online for downloads. Microsoft reserves the rights to give 5 free applications downloads and unlimited number of paid application downloads. Microsoft charges an amount of $99 for the market place registration to submit the developed application. For each download, Microsoft takes 30% of the fees paid and the developer will get 70% for his development. Summary We have seen in this chapter a complete overview on what Windows Phone 7 development is and the hardware and software requirements for developing a Windows Phone 7 Application in detail. In our upcoming chapters, we will see some of the interesting features of Windows Phone 7 development.
  15. 15. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 15 Hello World Silverlight Application Introduction In this chapter we are going to see how to create a Silverlight Windows Phone 7 Application using the Visual Studio IDE. In our earlier chapter we have seen the software and the hardware requirement in order to develop a Windows Phone application. Here in this chapter we will create a Hello World Application and try to run it in the Windows Phone 7 Emulator to check the working model of the application. Let us see the steps involved in designing the Hello World application using the Visual Studio 2010 IDE. Steps As we discussed in our earlier chapter, after installing the Windows Phone 7 SDK, we can see the new template options available with the Visual Studio 2010. The new templates are for creating Silverlight for Windows Phone Application and the other one is for XNA Game Studio 4.0, which will help us to develop the respective application as per the requirement as shown in the screen below.
  16. 16. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 16 In this book we are going to concentrate more on the Silverlight for Windows Phone application development for enterprise and commercial application builders. Also we will see how to create a XNA Game studio application as well so that it will give us some idea on the difference between the two projects. Let us create a Silverlight for Windows Phone 7 Hello world application. To start with, select the Windows Phone Application and provide a name for the project as shown in the screen below. Clicking on OK will create the application; we can see a popup window asking us to select the version of Windows Phone 7 OS. We will go with selecting the latest platform, Windows Phone OS 7.1 as shown in the screen below.
  17. 17. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 17 Clicking on OK will open the project in Visual Studio. We can see the Windows Phone 7 interface in the designer view and the XAML code below. Now drag and drop controls from the toolbox to get some user input and show the output Hello World. Alternatively, we can write the XAML code to get the controls based on the requirement. Once we have the controls on the designer, our screen looks like below.
  18. 18. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 18 The XAML code for the above design is given in the code block below. Give it a look to get an idea on the type of controls used and the properties assigned for each control to get a better user interface. We can copy and paste this below XAML code to any Windows Phone 7 Page to get the design. Here we have added 4 Text blocks, 2 text boxes for inputs and a button control to trigger some event. Also, if you have noticed we have changed the header message to F5DEBUG APPLICATION, in upper case, which is the standard we should consider while developing our applications. XAML Code: <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="F5Debug" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Height="30" HorizontalAlignment="Left" Margin="25,106,0,0" Name="textBlock1" Text="First Name" VerticalAlignment="Top" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="140,84,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="310" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="25,167,0,0" Name="textBlock2" Text="Last Name" VerticalAlignment="Top" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="140,145,0,0" Name="textBox2" Text="" VerticalAlignment="Top" Width="310" /> <Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="39,241,0,0" Name="SUBMIT" VerticalAlignment="Top" Width="377" Click="SUBMIT_Click" /> <TextBlock Height="51" HorizontalAlignment="Left" Margin="25,354,0,0" Name="textBlock3" Text="" VerticalAlignment="Top" Width="413" /> <TextBlock Height="50" HorizontalAlignment="Left" Margin="159,28,0,0" Name="textBlock4" Text="HELLO WORLD" VerticalAlignment="Top" Width="173" /> </Grid> Now that we are done with the design, we need to go to the code behind Submit button Event and write the code belo, which get the user input from the 2 text boxes (First Name and Last Name ) to provide a welcome message to the user. C# Code: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows;
  19. 19. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 19 using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace F5debugWp7HelloWorld { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } private void SUBMIT_Click(object sender, RoutedEventArgs e) { string strFname = textBox1.Text.ToString(); string strLname = textBox2.Text.ToString(); textBlock3.Text = "Welcome " + strFname.ToString() + " " + strLname.ToString(); } } }
  20. 20. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 20 Now build the application and execute the project. Check the output by pressing F5 from the keyboard directly or by pressing the play button from the IDE tool bar and we can see the output in the Windows Phone 7 Emulator as shown in the screen below. Note – We need to check if the target to run the application is pointing to Windows Phone Emulator and not Windows Phone Device. Now we can enter the test inputs and click on the Submit button to get the welcome message as shown in the screen below.
  21. 21. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 21 Summary In this chapter we have seen the steps involved in creating a Hello World application in Windows Phone 7 with Silverlight.
  22. 22. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 22 Using Expression Blend Introduction In this chapter we are going to see how to design the user interface of a Windows Phone 7 Application using Expression Blend. Expression Blend is one of the products of the Expression Suite of applications, which is used to design rich user interface for a XAML based application. Basically we can design any Silverlight or WP7 application which are XAML based and now we can use this product to design the Windows Phone 7 Application as well. Expression Studio is a licensed version, but for developing Windows Phone 7 applications, Expression Blend is available for free with the Windows Phone 7 SDK we initially downloaded when we made the development environment ready (Check my first chapter on Overview of Windows Phone 7 Development). Let us see the steps involved in using Expression Blend to make rich user experienced designs for Windows Phone 7 Applications. Steps Let us take the sample which we used in the last chapter. Open Visual Studio 2010 and open the project and we can see the application like below.
  23. 23. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 23 Now we will design this page using Expression Blend. To start with, first locate the page in the Solution Explorer of Visual Studio 2010 and then right click and select Open in Expression Blend as shown in the screen below. Clicking on Open in Expression Blend will load the Expression Blend IDE and we can see the page opened as shown in the screen below.
  24. 24. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 24 Now we need to select the button (SUBMIT) from the Object and Timeline pane on the left side and right click to select the Edit template option to create an empty template as shown in the screen below. Now we can see a pop up window, which has the option to create the empty Control template resource for the button. Just click on OK to proceed further without changing any options.
  25. 25. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 25 Now select the GRID from the Objects and Timeline pane and right click to change the layout. From the list of layouts, select Border as shown in the screen below. Now we need to customize the design of the button. Go to the Appearance section and change the border thickness and corner radius as shown in the screen below.
  26. 26. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 26 Now change the background color by selecting the Brushes section. Change the color as per the requirement and also we have option to customize by providing the color code directly as shown in the screen below. Similarly we need to change the setting for the Border Brush by selecting from the color pallet or by providing the color code as shown in the screen below.
  27. 27. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 27 Now we need to switch to the Assets panel and select the text block tool from the controls pane under the Border element of the template, as shown in the screen below. Now we need to customize the design for the text block by selecting the appearance and layout sections on the right side panel and changing the alignments, as shown in the screen below.
  28. 28. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 28 Now this step is very important. To change the content of the text property, select the Common Property category and click on the Advanced Property option to change the template binding to Content, as shown in the screen below. Now we are done with our design and the user interface. We can see the button customized and looks like a rich user interface, as shown in the screen below.
  29. 29. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 29 Now go back to the Visual Studio IDE and load the project, we can see a alert window that some of the resources are changed outside Visual Studio and if we need to restore those changes. Click on Yes to All and proceed further as shown in the screen below. Now build and execute the application by pressing F5 button from the keyboard or by directly selecting the Build solution. We can see the application loaded on to the Windows Phone 7 Emulator and we can see the output as shown in the screen below.
  30. 30. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 30 Summary In this chapter we have seen the steps involved in using Expression Blend to design a rich user interface for a Windows Phone 7 Application and load it into the Windows Phone Emulator.
  31. 31. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 31 Working with Application Bar Introduction In this chapter we are going to see how to use Application Bar effectively for Windows Phone 7 Application development. In our earlier chapters, we have seen how to create an application using Visual Studio 2010 and do some rich user interface design changes with Microsoft Expression Blend. In this chapter we will also create a new application and configure the application bar to make effective use of it. The Application Bar is a set of Icons that can be configured at the bottom of an application for each page or for multiple pages. These buttons can be used to navigate to frequently used pages across the application, which makes navigation for users quick and easy. It automatically adjusts its icons and buttons as the screen orientation changes. The text based menu items are displayed as a list rather than the icons being shown on the screen. To access the menu items, we can directly click the ellipsis at the right corner of the application bar. The menu items are by default taken in lower case to have a consistent end user experience. Now let us see the steps involved in adding an Application Bar to a new project and configuring the application bar with icons and menu items. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application named F5debugWp7ApplicationBar, as shown in the screen below.
  32. 32. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 32 We can now see the project is created and ready to start with our development task. As we follow some standards, we can change the page header and make some small modifications so that the page looks unique. Once we are done with the changes, to add the application bar, go to the XAML Page and we can see a commented section, as shown in the screen below.
  33. 33. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 33 We just need to uncomment this section to have the application bar ready with some default buttons and menus, which we can configure as per our requirements. Once we uncomment this section we can see that we have 2 application bar icons added and 2 menu items added with the default values. Now we will change it to 3 Application bar icons and 3 Menu items. Before we start adding the code for it, we need to have the Application bar icons ready. By default when we install the Windows Phone 7 SDK, we have the icons installed to the local development machine which will be available in the below locations. DriveNameProgram FilesMicrosoft SDKsWindows Phonev7.1Iconsdark DriveNameProgram Files (x86)Microsoft SDKsWindows Phonev7.1Iconsdark We can see the list of ICONS available below. Now in the uncommitted application bar code, add the code for 3 buttons and 3 menu items as shown in the screen below. Before that, add the icons that are required to use in the application bar to a new Images folder.
  34. 34. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 34 Now we need to build the application icons. To do that, go to the properties of the each image and change the Build Action from Content from Resources. Do the same for all the icons which have been added to the images folder. Once we are done with the above step, go to the XAML code and make the changes for each button by adding the appropriate icon and the button text, as shown in the below XAML code. <shell:ApplicationBarIconButton IconUri="/Images/appbar.next.rest.png" Text="Back"; <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add"; <shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="Front"; Now do the same for the menu items by adding the menu details, as specified in the code below.
  35. 35. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 35 <code><shell:ApplicationBarMenuItem Text="Home"/> <shell:ApplicationBarMenuItem Text="Submit"/> <shell:ApplicationBarMenuItem Text="Help"/></code> Once we are done with the above 2 code changes, our final application bar code will look like below. <code><phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton IconUri="/appbar.next.rest.png" Text="Back"/> <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add"/> <shell:ApplicationBarIconButton IconUri="/appbar.back.rest.png" Text="Front"/> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="Home"/> <shell:ApplicationBarMenuItem Text="Submit"/> <shell:ApplicationBarMenuItem Text="Help"/> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar></code> Now we can run the application to see if the application bar is configured correctly and the icons are visible. To build and execute the application, just press F5 or select the build solution option from the tool box. We can see the application is loaded into the Windows Phone 7 Emulator below. Now we need to have an event handler to trigger each button event. To do that, add the event handler code in the XAML and add the event triggering code to the code behind, as shown in the code below.
  36. 36. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 36 XAML Code: <code><phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton IconUri="/Images/appbar.next.rest.png" Text="Back" Click="NextButton_Click"/> <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="Add" Click="AddButton_Click"/> <shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="Front" Click="BackButton_Click"/> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="Home" Click="HomeMenuutton_Click"/> <shell:ApplicationBarMenuItem Text="Submit" Click="SubmitMenuButton_Click"/> <shell:ApplicationBarMenuItem Text="Help" Click="HelpMenuButton_Click"/> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar></code> C# Code: <code>private void NextButton_Click(object sender, EventArgs e) { MessageBox.Show("Next Application Bar Is Clicked!!!"); }</code> private void AddButton_Click(object sender, EventArgs e) { MessageBox.Show("Add Application Bar Is Clicked!!!"); } private void BackButton_Click(object sender, EventArgs e) { MessageBox.Show("Back Application Bar Is Clicked!!!"); } private void HomeMenuutton_Click(object sender, EventArgs e) { MessageBox.Show("Home Menu Is Clicked!!!"); } private void SubmitMenuButton_Click(object sender, EventArgs e) { MessageBox.Show("Submit Menu Is Clicked!!!"); } private void HelpMenuButton_Click(object sender, EventArgs e) { MessageBox.Show("Help Menu Is Clicked!!!"); }
  37. 37. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 37 We have just added code to trigger a Message Box stating which button is clicked. Once we are done with the above code, press F5 to build and execute the application and click on the Application Bar button to see the expected output, as shown in the screen below. Summary In this chapter we have seen how to use the Application Bar and the steps to configure the application bar with menu items. The Application Bar can be of use in different scenarios and used across the pages. We can also use Application Bar globally.
  38. 38. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 38 Working with Alarms/Reminders Introduction In this chapter we are going to how to use the Alarms and Reminders notifications in a Windows Phone 7 Application. A notification is a message that pops up on the screen to the end users at a specified time, scheduled initially. We can make the pop up with some customized message for user friendly requirements. Basically we can make 2 types of notifications, an Alarm and a Reminder. An Alarm is used to play a music file when a notification is launched, as scheduled by the end users. A Reminder notification is similar to the Alarm notification, expect we can have some text information to show the end user and also we can provide a navigation URI of a page to be opened by clicking on the reminder UI. We can also include some query string parameters to pass information that should be used within the page or the application to which the navigation is pointing to. Microsoft has a limitation of using 50 Alarm or Reminder notifications within a single application. Alarms and Reminders use the Alarm Class and Reminder Class respectively. We will see in this chapter how to use these classes to create alarms and reminders that can be used in real time. We will create a new Windows Phone 7 project and provide options to add an alarm and reminder. Let us see the steps involved in adding alarm and reminder notifications. Steps To create an Alarm application, Open Visual Studio 2010 and create a new Windows Phone for Silverlight application with a valid project name and location to which the project should be saved, as shown in the screen below.
  39. 39. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 39 Now let us add 2 pages, one for adding an alarm content page and other for adding a reminder content page. Once we added 2 pages in the main page, we need to add 2 buttons in the main page from which the 2 new pages will be triggered as shown in the screen below.. We have added 2 pages, AddAlarm.XAML and AddReminder.XAML. On the button click event, we need to navigate to these 2 pages, as shown in the code behind.
  40. 40. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 40 XAML Code <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="F5DEBUG" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Alarm" Height="161" HorizontalAlignment="Left" Margin="65,108,0,0" Name="btnAlarm" VerticalAlignment="Top" Width="330" Click="btnAlarm_Click"/> <Button Content="Reminder" Height="161" HorizontalAlignment="Left" Margin="65,306,0,0" Name="btnReminder" VerticalAlignment="Top" Width="330" Click="btnReminder_Click"/> </Grid> </Grid> C# Code private void btnAlarm_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/AddAlarm.xaml", UriKind.Relative)); } private void btnReminder_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/AddReminder.xaml", UriKind.Relative)); } ALARM Page: Now we need to add the content to the AddAlarm.XAML page. To add an alarm, we need to make use of the Alarm class which is inherited from the ScheduledNotification class. Now add the controls to the AddAlarm.XAML Page, as shown in the screen below.
  41. 41. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 41 XAML Code: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,94,0,0" Name="ttName" Text="Name" VerticalAlignment="Top" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="126,68,0,0" Name="txtName" Text="" VerticalAlignment="Top" Width="306" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,172,0,0" Name="ttContent" Text="Content" VerticalAlignment="Top" /> <TextBox Height="132" HorizontalAlignment="Left" Margin="126,146,0,0" Name="txtContent" Text="" VerticalAlignment="Top" Width="306" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,310,0,0" Name="ttBegintime" Text="Begin Time" VerticalAlignment="Top" /> <toolkit:DatePicker Name="datePicker1" Height="67" Margin="126,286,145,254" /> <Button Content="Add" Height="72" HorizontalAlignment="Left" Margin="54,470,0,0" Name="btnAdd" VerticalAlignment="Top" Width="160" Click="btnAdd_Click" /> <Button Content="Clear" Height="72" HorizontalAlignment="Left" Margin="220,470,0,0" Name="btnClear" VerticalAlignment="Top" Width="160" Click="btnClear_Click" /> <toolkit:TimePicker HorizontalAlignment="Left" Margin="317,286,0,0" Name="timePicker1" VerticalAlignment="Top" Width="115" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,383,0,0" Name="textBlock1" Text="Expiration" VerticalAlignment="Top" /> <toolkit:DatePicker Height="67" Margin="126,359,145,181" Name="datePicker2" /> <toolkit:TimePicker HorizontalAlignment="Left" Margin="317,359,0,0" Name="timePicker2" VerticalAlignment="Top" Width="115" /> </Grid>
  42. 42. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 42 C# Code: private void btnAdd_Click(object sender, RoutedEventArgs e) { AddAlaram(); } void AddAlaram() { Alarm alarm = new Alarm(txtName.Text.ToString()); alarm.Content = txtContent.ToString(); DateTime date = (DateTime)datePicker1.Value; DateTime time = (DateTime)timePicker1.Value; DateTime beginTime = date + time.TimeOfDay; alarm.BeginTime = beginTime; DateTime date1 = (DateTime)datePicker1.Value; DateTime time1 = (DateTime)timePicker1.Value; DateTime exptime = date1 + time1.TimeOfDay; alarm.ExpirationTime = exptime; alarm.RecurrenceType = RecurrenceInterval.Daily; ScheduledActionService.Add(alarm); } In the above code, we have some properties which are to be considered before we write our requirement on top of it. The properties are as follows  Name – Unique Name for the Alarm.  Title – This is default name, and we cannot set this property manually.  Content – This property is to set some content for the alarm.  Begin Time – Beginning of the alarm.  Expiration Time – Expiration time of the alarm.  Recurrence Type – Recurrence type of the alarm.  Sound – Sound file to play for the alarm. Now run the application and see the alarm configuration, as shown in the screen below.
  43. 43. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 43 REMINDER Page: Now let us start with designing the Reminder page. Before that we will add a new page called AddReminder.XAML. The use of this page is to create a reminder trigger which will have the option to navigate to a URI with passing some parameters. We will pass values to the pages from the Reminder page. We will see how to do that with this page. Add contents from the tool box for the Reminder page, as shown in the screen below and the code. XAML Code: Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Height="30" HorizontalAlignment="Left" Margin="21,32,0,0" Name="ttName" Text="Name" VerticalAlignment="Top" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="121,6,0,0" Name="txtName" Text="" VerticalAlignment="Top" Width="306" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="21,178,0,0" Name="ttContent" Text="Content" VerticalAlignment="Top" /> <TextBox Height="132" HorizontalAlignment="Left" Margin="121,152,0,0" Name="txtContent" Text="" VerticalAlignment="Top" Width="306" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="21,316,0,0" Name="ttBegintime" Text="Begin Time" VerticalAlignment="Top" /> <toolkit:DatePicker Height="67" Margin="121,292,150,248" Name="datePicker1" /> <Button Content="Add" Height="72" HorizontalAlignment="Left" Margin="49,476,0,0" Name="btnAdd" VerticalAlignment="Top" Width="160" />
  44. 44. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 44 <Button Content="Clear" Height="72" HorizontalAlignment="Left" Margin="215,476,0,0" Name="btnClear" VerticalAlignment="Top" Width="160" /> <toolkit:TimePicker HorizontalAlignment="Left" Margin="312,292,0,0" Name="timePicker1" VerticalAlignment="Top" Width="115" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="21,389,0,0" Name="textBlock1" Text="Expiration" VerticalAlignment="Top" /> <toolkit:DatePicker Height="67" Margin="121,365,150,175" Name="datePicker2" /> <toolkit:TimePicker HorizontalAlignment="Left" Margin="312,365,0,0" Name="timePicker2" VerticalAlignment="Top" Width="115" /> <TextBlock Height="30" HorizontalAlignment="Left" Margin="21,100,0,0" Name="ttTitle" Text="Title" VerticalAlignment="Top" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="121,74,0,0" Name="txtTitle" Text="" VerticalAlignment="Top" Width="306" /> </Grid> C# Code: private void btnAdd_Click(object sender, RoutedEventArgs e) { AddReminder(); } void AddReminder() { Reminder reminder = new Reminder(txtName.Text.ToString()); reminder.Title = txtTitle.Text.ToString(); reminder.Content = txtContent.Text.ToString();
  45. 45. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 45 DateTime date = (DateTime)datePicker1.Value; DateTime time = (DateTime)timePicker1.Value; DateTime beginTime = date + time.TimeOfDay; reminder.BeginTime = beginTime; DateTime date1 = (DateTime)datePicker1.Value; DateTime time1 = (DateTime)timePicker1.Value; DateTime exptime = date1 + time1.TimeOfDay; // reminder.ExpirationTime = exptime; reminder.RecurrenceType = RecurrenceInterval.Daily; string struri = "?param=Reminder App Passed"; Uri navigationUri = new Uri("/ReminderAppPage.xaml" + struri, UriKind.Relative); reminder.NavigationUri = navigationUri; ScheduledActionService.Add(reminder); } In the above code, we have some properties which are to be considered before we write our requirement on top of the reminder properties. Some of the main properties are as follows  Name – Unique Name for the Reminder.  Title – This is default name, and we cannot set this property manually.  Content – This property is to set some content for the reminder.  Begin Time – Beginning of the Reminder.  Expiration Time – Expiration time of the Reminder.  Recurrence Type – Recurrence type of the Reminder.  Navigation URI – User will be navigated to this page when clicking on the Reminder application. We have added a parameter to be passed with the navigation URI as a query string. To get the query string value, we need to write the code below in the new page (AddReminder.XAML), as shown in the screen below. C# Code: protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); string paramValue = ""; NavigationContext.QueryString.TryGetValue("param", out paramValue); textBlock1.Text = paramValue; } Now we can run the application and see the Reminder configuration as shown in the screen below.
  46. 46. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 46 Summary In this chapter we have seen how to make use of the inbuilt Scheduled Notification mechanism to build applications which notifies end users with some custom messages. Alarms and Reminders play a major role for notifications to end users, as per the requirements.
  47. 47. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 47 Working with Contacts Introduction In this chapter we are going to see how to work with inbuilt contacts data and use it across our requirement to manipulate the data. Windows Phone 7.1 provides a read only access to the data available locally across the device. We can query the data and select the users based on the search filters and also we can do multiple manipulations in order to perform some operation with the user’s contact information. Let us see the steps involved in using contacts for querying data. To launch the contacts, we need to use the AddressChooserTask which is used to select contacts. The queried result can be collected in the AddressResult object and can be used to list it, as per the requirements. Let us start with creating a new application and start using the AddressChooserTask. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project and provide a valid project name, as shown in the screen below.
  48. 48. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 48 Now we will add a button which triggers an event to query the data and get the contacts in a list. Add the below XAML code, or we can directly drag and drop the controls, as shown in the screen below. XAML Code: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Get Contacts" Height="83" HorizontalAlignment="Left" Margin="30,16,0,0" Name="btnContacts" VerticalAlignment="Top" Width="402" Click="btnContacts_Click" /> <ListBox Name="lstcontacts" ItemsSource="{Binding}" Margin="47,188,36,52" > <ListBox.ItemTemplate> <DataTemplate> <TextBlock Name="txtResults" Text="{Binding Path=DisplayName, Mode=OneWay}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <TextBlock Height="41" HorizontalAlignment="Left" Margin="47,118,0,0" Name="txtResults" Text="List of Contacts" VerticalAlignment="Top" Width="373" /> </Grid> Now we will add some code in the code behind page for querying the data from the contacts database. To do that, go to the button click event and write the code below. Basically, the Windows Phone 7 Emulator has some default contacts which can be tested by pulling the list in this chapter. We need to add the namespace in order to access the data.
  49. 49. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 49 using Microsoft.Phone.UserData; Now in the button click event add the code below. From the code we can see the Contact class been used to query the details. Here we will be using the SearchAsyc method to do the search with the object and provide the result set to the list, as shown in the code below. C# Code: private void btnContacts_Click(object sender, RoutedEventArgs e) { Contacts cContacts = new Contacts(); cContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(ContactsSearch); cContacts.SearchAsync(String.Empty, FilterKind.DisplayName, null); } void ContactsSearch(object sender, ContactsSearchEventArgs e) { try { lstcontacts.DataContext = e.Results; } catch (System.Exception) { txtResults.Text = "No Results Available"; } if (lstcontacts.Items.Any()) { txtResults.Text = "Below is the List of Contacts"; } else { txtResults.Text = "No Results Available"; } } In the above code, we are querying the contacts class object and bind it to the list box using the data context and do some small user information with the message. In the SearchAsync method, we provide different filters that can be used to access the data. Below is the list of filters that can be provided, based on the requirement.  Search All Contacts – SearchAsync(String.Empty, FilterKind.None, null)  Get Pinned Contacts – SearchAsync(String.Empty, FilterKind.PinnedToStart, null)  Search by Display Name – SearchAsync(“Karthik”, FilterKind.DisplayName, null)  Search by Email ID – SearchAsync(“Karthik@f5debug.net”, FilterKind.EmailAddress, null)  Search by Phone No – SearchAsync(“123-456-7890″, FilterKind.PhoneNumber, null)
  50. 50. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 50 Now we are done with the application. In the IDE, press F5 or click on Build and execute the solution. We can see the end result by pressing the button once the application is loaded as shown below. The list of contacts which are shown in the above screen is the default contacts available with the Emulator for testing purposes. We can use these contacts to do the testing or delete them based on the requirement. Summary In this chapter we have seen how to perform a contact data search using the AddressChooserTask and play around with the contact selected to list or to manipulate the contact.
  51. 51. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 51 Working with Calendar Introduction In this chapter, we are going to see how to use the Calendar application to access the calendar data and use it across the development as and when needed. In our earlier chapters, we have seen how to use the contact and access contact data; we are going to use the same process for accessing the calendar objects. In order to use the calendar object, we are going to use a reference of the Appointments object and do an Async search to get the results and show it on a collection of Appointment objects. The end result in the appointments object can be used in different ways, as per the requirement, by binding to different controls. The Appointment class is to interact with user appointment data and is inherited from the Microsoft.Phone.UserData namespace. Let us see the steps involved in using calendar objects and listing the appointments. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application with a valid project name, as shown in the screen below.
  52. 52. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 52 Now in order to fetch the details of the calendar appointments and show it to the end users, we will add controls from the toolbox, as shown in the screen below. We can just drag and drop the controls from the tool box, write XAML code or copy paste XAML code. XAML Code: <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="calendar" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Get Appointment" Height="83" HorizontalAlignment="Left" Margin="30,16,0,0" Name="btnAppointment" VerticalAlignment="Top" Width="402" Click="btnAppointment_Click" /> <ListBox Name="lstAppointment" ItemsSource="{Binding}" Margin="47,188,36,52" > <ListBox.ItemTemplate> <DataTemplate> <TextBlock Name="txtResults" Text="{Binding Path=DisplayName, Mode=OneWay}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <TextBlock Height="41" HorizontalAlignment="Left" Margin="47,118,0,0" Name="txtAppointments" Text="List of Appointments" VerticalAlignment="Top" Width="373" /> </Grid></Grid>
  53. 53. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 53 Now we need to add code to list the calendar appointments in the list view. First add the following namespace. using Microsoft.Phone.UserData; Now add the button click event code. Here we are going to create an object of the Appointment class and do an AsyncSearch. We need to provide the start time and end time to fetch the appointment details and also should provide the maximum count. Copy and paste the code below to the code behind for the button click event. C# Code: private void btnAppointment_Click(object sender, RoutedEventArgs e) { Appointments aAppointment = new Appointments(); aAppointment.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(GetAppointments); DateTime starttime = DateTime.Now; DateTime endtime = starttime.AddDays(10);
  54. 54. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 54 int maxAppointment = 20; aAppointment.SearchAsync(starttime, endtime, maxAppointment, null); } void GetAppointments(object sender, AppointmentsSearchEventArgs e) { try { lstAppointment.DataContext = e.Results; } catch (System.Exception) { txtAppointments.Text = "No Appointments Found!!!"; } if (lstAppointment.Items.Any()) { txtAppointments.Text = "Below is the List of Appointments"; } else { txtAppointments.Text = "No Appointments Found!!!"; } } The above code will pull the information from the appointments object and bind it to the data context of the list box. If there are no appointments available, we can see an empty result as well. To check the application just run the application by pressing F5 directly from the keyboard or by selecting build and execute solution from the tool bar. We can see the screen below.
  55. 55. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 55 Since we are in the emulator and we don’t have any appointments, saved list is empty. If any appointments are saved in the physical device we will get the complete list of appointments for the next 10 days here in the list box. Summary In this chapter we have seen how to use the calendar object to fetch appointment details and list them out. We can customize the appointments object to bind with different data binding options, as per the requirements.
  56. 56. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 56 Working with Camera Introduction In this chapter, we are going to see how to use the Camera options in developing applications with Windows Phone 7. In order to access the camera features, we are going to use the Launchers and Choosers which have the inbuilt API’s to perform each task based on the requirement. To manipulate the camera photos and storage with the device, we are going to use the CameraCaptureTask. This task is used to launch the default camera application to take some snap shot for any third party application which is trying to use the camera to save images locally or to isolated storage (Isolated storage enables managed applications to create and maintain local storage. Isolated storage in Windows Phone is similar to isolated storage in Silverlight.) Here in this chapter we will see how to take a picture using the camera and save it locally. We need to have some understanding of the Launchers and Choosers task since we need to select the task based on our requirement. Let us use the CameraCaptureTask and complete the process step by step using Visual Studio for Windows Phone 7. Steps Let us Open Visual Studio 2010 and create a new Silverlight for Windows Phone project with a valid project name, as shown in the screen below.
  57. 57. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 57 Now to invoke the CameraCapture task and save the image locally, we add 2 controls: a button and an image viewer control. The button control is to invoke the CameraCapture task and get the camera image. The image viewer control is to display the image which we took using the camera application. Drag and drop the images from the toolbox or write the XAML code, as shown below. XAML Code: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Invoke Camera" Height="72" HorizontalAlignment="Left" Margin="36,30,0,0" Name="btnCamera" VerticalAlignment="Top" Width="389" Click="btnCamera_Click" /> <Image Height="377" HorizontalAlignment="Left" Margin="36,187,0,0" Name="imgCaptured" Stretch="Fill" VerticalAlignment="Top" Width="389" /> <TextBlock Height="39" HorizontalAlignment="Left" Margin="36,129,0,0" Name="txtResult" Text="" VerticalAlignment="Top" Width="389" /> </Grid>
  58. 58. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 58 Now we are done with our design, our next task is to invoke the camera application and capture an image. Once captured, we are going to assign the image to the Image Viewer control. To invoke the CameraCaptureTask, we need to include the below two namespaces using Microsoft.Phone.Tasks; using Microsoft.Phone; Now let us add the code behind with the required code. First, we add class level variables which are used to invoke the camera task. Add the below class level variables within the class scope. We are creating an object of the CameraCaptureTask, using the code below. C# Code: private CameraCaptureTask ccTask; Now we need to invoke the Camera on the button click event. To do that, let us first complete the object creation in the MainPage constructor and in the button event handler, invoke the camera, as shown in the code below.
  59. 59. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 59 C# Code: public MainPage() { InitializeComponent(); ccTask = new CameraCaptureTask(); } private void btnCamera_Click(object sender, RoutedEventArgs e) { ccTask.Show(); } Now practically the camera application is invoked and with the inbuilt options we can capture the picture. To save the picture, we need to have a mechanism which can be done with the help of CameraCaptureTask Completed args. To do that, first let us write some code to get the captured image and assign it to the image viewer control and then we will see when to trigger this option. Write the code below in a separate method which gets the PhotoResult and decodes it to a byte array to be shown on the image viewer control. C# Code: private void ccTaskCompleted(object sender, PhotoResult pr) { byte[] imgLocal; if (pr.ChosenPhoto != null) { imgLocal = new byte[(int)pr.ChosenPhoto.Length]; pr.ChosenPhoto.Read(imgLocal, 0, imgLocal.Length); pr.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin); var bitmapImage = PictureDecoder.DecodeJpeg(pr.ChosenPhoto); this.imgCaptured.Source = bitmapImage; } } Now we are done with our code to show the captured image in the ImageViewer control (imgCaptured). Now to trigger this code so that the image captured can be retrieved, we need to do this at the CameraCapturedTask completed event. To do that, we need to go back to the MainPage constructor at the top and add the code below.
  60. 60. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 60 C# Code: public MainPage() { InitializeComponent(); ccTask = new CameraCaptureTask(); ccTask.Completed += ccTaskCompleted; } So the CameraCaptureTask completed will trigger the method to do the necessary steps to show the image in the image control. Now we are ready to build and check the output of the application. To do that, press F5 directly from the keyboard or by pressing the build and execute option from the Visual Studio Tool Bar. Once the application is built and executed successfully, we can see the output in the Windows Phone 7 Emulator as shown below. Now to invoke the camera, click on the InvokeCamera button and we can see the Camera Application is invoked. We will see an empty screen with the camera buttons, as shown in the screen below.
  61. 61. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 61 Now click on the button at the top right corner so that we can capture some image using the Windows Phone 7 emulator. Since we are using the emulator, we will see a white screen with a rectangle in it. We can click on the Accept button at the bottom to capture the image, as shown in the screen below. If we want to take a new image, we can click on Retake to capture again.
  62. 62. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 62 Now click on the Accept button and we can see the image captured is assigned to the image viewer control on the main page, as shown in the screen below. We can see a dull image since we are using the Windows Phone 7 emulator; if we deploy the application on to the real device we can get a very good resolution of the picture. Summary In this chapter we have seen how to use a Camera Application to capture images and use them in the development of our application, as per the requirements. Also, we have seen the Launchers and Choosers CameraCaptureTask to build the application to capture the picture.
  63. 63. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 63 Working with Panorama Control Introduction In this chapter, we are going to see the very interesting Panorama Control in Windows Phone 7. Panorama controls are used to slide through big content without having to completely hide the previous content. We can consider sliding through a horizontal page with different contents and blocks. We can use this Panorama control to show a rich user interface by dividing the contents to different blocks and assigning different items horizontally. Panorama controls are used to browse back and forth the page items within the specified content block to get a rich user experience. The Panorama control is the base, which can contain PanoramaItem controls, which will host individual contents. Basically, we will have only one Panorama control within which we can have multiple PanoramaItem, to have contents blocked out one by one. The Panorama control can be added and configured directly from the XAML code or we can do it programmatically. The control is layered into 4 layers as shown below.  Background – This is the base layer, the background of the panorama control.  Title – This is the top layer used to display the title of the page.  Header – This layer is used to display the Panorama Item block title.  Content – This layer will be used to show the Panorama Item content. Ok it’s time for the demo, let us see steps involved in creating a Panorama control based application and add some content to see the rich user interface experience it offers. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid project name, as shown in the screen below.
  64. 64. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 64 Now we can see a beautiful interface with the default design and the background, shown below. We will customize the application design in our next steps.
  65. 65. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 65 First let us delete the default values and add the PanoramaItems and the data bindings one by one. Go to the XAML code and select the tag <controls:PanoramaItem>. We can see 2 items, just select the complete code and delete it. We can now see the screen looks empty, as shown in the screen below. Now change the Panorama control Title and background. To do that, go to the XAML code and change the Title to F5Debug and to change the background, let us add a new background to the project solution and map the path to the ImageBrush tag, as shown in the code below. Once we are done with the above 2 changes, we can see our screen looks like below. XAML Code: <controls:Panorama Title="f5debug wp7 tutorials"> <controls:Panorama.Background> <ImageBrush ImageSource="Bcg1.jpg"/> </controls:Panorama.Background> </controls:Panorama>
  66. 66. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 66 Now we need to add the PanoramaItems to the control. To do that, we need to add the code below, containing the listing of data, as per the requirements. Here we have added 3 PanoramaItems (Posts, Ebook and Comments) and a default grid on which we will be adding our controls to show to the end user. Once we added the 3 items we can see our screen looks like below and the code will appear as shown in the below listing. XAML Code: <controls:Panorama Title="f5debug wp7 tutorials"> <controls:Panorama.Background> <ImageBrush ImageSource="Bcg1.jpg"/> </controls:Panorama.Background> <controls:PanoramaItem Header="Posts"> <Grid/> </controls:PanoramaItem> <controls:PanoramaItem Header="Ebook"> <Grid/> </controls:PanoramaItem> <controls:PanoramaItem Header="Comments"> <Grid/> </controls:PanoramaItem> </controls:Panorama>
  67. 67. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 67 Now we need to add some controls to each of the items to show some information to the end users. To add the controls, we can just drag and drop from the toolbox or by directly writing to the XAML Code. Let us do some customization to get a good user experience with controls as shown in the XAML Code below. Once we are done with our code we can see the screen looks like below. XAML Code: <controls:Panorama Title="f5debug wp7 tutorials"> <controls:Panorama.Background> <ImageBrush ImageSource="Bcg1.jpg"/> </controls:Panorama.Background> <controls:PanoramaItem Header="Posts"> <Grid> <Image Height="174" Source="f5Image.jpg" HorizontalAlignment="Left" Margin="78,47,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="254" /> <TextBlock Height="164" HorizontalAlignment="Left" Margin="22,275,0,0" TextWrapping="Wrap" Name="textBlock1" Text="This is the F5debug blog posts sections, You can get the latest post updates here!!!" VerticalAlignment="Top" Width="369" /> </Grid> </controls:PanoramaItem> <controls:PanoramaItem Header="Ebook"> <Grid> <Image Height="310" Source="ssis-cover-page.jpg" HorizontalAlignment="Left" Margin="79,25,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="258" /> <TextBlock Height="92" HorizontalAlignment="Left" Margin="28,367,0,0" TextWrapping="Wrap" Name="textBlock2" Text="SQL Server Integration Services (SSIS) – Step by Step Tutorial Version 2.0" VerticalAlignment="Top" Width="351" />
  68. 68. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 68 </Grid> </controls:PanoramaItem> <controls:PanoramaItem Header="Comments"> <Grid> <TextBlock Height="206" FontSize="40" HorizontalAlignment="Left" Margin="82,121,0,0" TextWrapping="Wrap" Name="textBlock3" Text="F5debug Comments Section" VerticalAlignment="Top" Width="273" /> </Grid> </controls:PanoramaItem> </controls:Panorama> Now we are done with our design and the coding section. To test our application, press F5 directly from the keyboard or Build and Execute from the Visual Studio IDE toolbar. We can see the application loaded into the Windows Phone 7 Emulator, as shown in the screen below.
  69. 69. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 69 Now scroll the screen horizontally and we can see the second Panorama items displayed to the user, this basically avoids the loading of multiple pages which require single user interaction as shown in the screen below. Summary In this chapter we have seen how to use the Panorama Control and to design a rich user interface by adding items and changing the background to have a unique interface.
  70. 70. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 70 Working with Pivot Control Introduction In this chapter, we are going to see how to use the Pivot Control in a Windows Phone 7 Application. In our previous chapter, we have used the Panorama control to build a rich user interface. Using the Pivot control we can easily maintain pages or data views without having the need of loading multiple pages. We can easily filter large data sets into multiple pages. With this control, we can slide back and forth and provide the end user with related data in a much easier view using any of the available controls. The Pivot control is the base application control and inside that we will have a Pivotitem control where we can have multiple items inside a Pivot control. It is recommended to have one pivot control within a page, which in turn can have multiple Pivotitems. The Pivot Control is layered into 2 layers; with each layer contains a Grid inside, as the layout root  Pivot Headers – This layer is for showing the header title.  Pivot Items – This layer is for showing a single Pivotitem to display data. Let us see the steps involved in creating a Pivot control application for Windows Phone 7 using Visual Studio 2010. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 project with a valid project name, as shown in the screen below.
  71. 71. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 71 We can see the Windows Phone 7 interface with the Pivot Control added in the screen below. Also, we can see the default pivot items listed in the page which we can edit, as per the requirement
  72. 72. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 72 If we can see the XAML code, the pivot control is added by default with default pivot items. We can delete the pivot items inside the pivot control and we can see the empty Pivot control. We will customize it by adding our own PivotItems, let us do the same design which we did for the Panorama sample. One difference, we do not have an option to change the background. Once we add the default Pivot Items, we can see the screen looks like below. Now we need to add some controls to each of the items to show some information to the end users. To add the controls, just drag and drop from the toolbox or by directly writing XAML Code. Let us do some customization to get a good user experience with the controls, as shown in the XAML Code below. Once we are done with our code we can see the screen as shown below. XAML Code: <controls:Pivot Title="F5DEBUG WP7 TUTORIALS"> <controls:PivotItem Header="Post"> <Grid> <Image Height="174" Source="f5.jpg" HorizontalAlignment="Left" Margin="78,47,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="254" /> <TextBlock Height="164" HorizontalAlignment="Left" Margin="29,301,0,0" TextWrapping="Wrap" Name="textBlock1" Text="This is the F5debug blog posts sections, You can get the latest post updates here!!!" VerticalAlignment="Top" Width="369" /> </Grid> </controls:PivotItem>
  73. 73. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 73 <controls:PivotItem Header="Ebook"> <Grid> <Image Height="310" Source="ssis-cover-page.jpg" HorizontalAlignment="Left" Margin="79,25,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="258" /> <TextBlock Height="120" TextWrapping="Wrap" HorizontalAlignment="Left" Margin="31,409,0,0" Name="textBlock2" Text="SQL Server Integration Services (SSIS) – Step by Step Tutorial Version 2.0" VerticalAlignment="Top" Width="372" /> </Grid> </controls:PivotItem> <controls:PivotItem Header="Comments"> <Grid> <TextBlock Height="206" FontSize="40" HorizontalAlignment="Left" Margin="82,121,0,0" TextWrapping="Wrap" Name="textBlock3" Text="F5debug Comments Section" VerticalAlignment="Top" Width="273" /> </Grid> </controls:PivotItem> </controls:Pivot> Now we are done with our design and the coding section. To test our application, press F5 directly from the keyboard or Build and Execute from the Visual Studio IDE toolbar and we can see the pivot control application loaded into the Windows Phone 7 Emulator as shown below.
  74. 74. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 74 Now we can directly click on the header title or scroll it horizontally to navigate to the second pivot item, as shown in the screen below. Summary In this chapter, we have seen how to use the pivot control from scratch and design a good user interface that looks similar to the Panorama control but with some differences which we have seen in the output.
  75. 75. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 75 Working with Media Introduction In this chapter, we are going to see how to use the media framework, which helps application developers to stream video and audio files and to use the integrated Music and Video Hubs to select media files. In our previous chapters, we have seen the different controls to design a rich user interface application and in this topic we will see much more interesting aspects on handling media files which will be very effective for using a Mobile device. Media in Windows Phone 7 uses the MediaElement API to incorporate the audio and video files using the inbuilt device media player in Silverlight for Windows Phone 7. In this chapter we will see how to play a video file using the MediaElement API. Let us see the steps involved in Media development in Windows Phone 7 applications using the MediaElement API. Steps Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 application project by providing a valid project name, as shown in the screen below.
  76. 76. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 76 Now let us customize the Mainpage.xaml by adding a button control and a MediaElement to play the video file, as shown in the screen below. Also we have customized the header grid to have a unique design for the chapters in this book. XAML Code: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Play Video" Height="72" HorizontalAlignment="Left" Margin="12,30,0,0" Name="button1" VerticalAlignment="Top" Width="427" /> <MediaElement Height="356" HorizontalAlignment="Left" Margin="34,144,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="386" /> </Grid> Now let us add a sample video file to the project, which we will load on the click of a button. We have added a sample .WMV file to the root folder of the project. Once we have added the file, go to the button click event (Play Video button) and write the code below to stream the video file, as shown in the screen below.
  77. 77. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 77 XAML Code: <phone:PhoneApplicationPage x:Class="F5debugWp7Media.MainPage" xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.micros oft.com/winfx/2006/xaml/presentation"</a> xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winf x/2006/xaml"</a> xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="<a href="http://schemas.microsoft.com/expression/blend/2008&quot;">http://schemas.microsoft.com /expression/blend/2008"</a> xmlns:mc="<a href="http://schemas.openxmlformats.org/markup- compatibility/2006&quot;">http://schemas.openxmlformats.org/markup-compatibility/2006"</a> mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <!--LayoutRoot is the root grid where all page content is placed--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="video player" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Play Video" Height="72" HorizontalAlignment="Left" Margin="12,30,0,0" Name="button1" VerticalAlignment="Top" Width="427" Click="button1_Click" /> <MediaElement Height="356" HorizontalAlignment="Left" Margin="34,144,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="386" /> </Grid> </Grid> </phone:PhoneApplicationPage>
  78. 78. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 78 C# Code: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace F5debugWp7Media { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { mediaElement1.Source = new Uri("Bear.wmv", UriKind.Relative); mediaElement1.Play(); } } }
  79. 79. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 79 Now we are done with our code. Let us build and execute the application by pressing the F5 button from the keyboard or by selecting the Build and Execute option from the toolbar. We can see the output of the application shown in the screen below.
  80. 80. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 80 Now we can see the video streaming, with the option to restart and reset the video at any point of time. We can also customize it to select the file randomly and play as we normally do using the playlist, which we will see in depth in our upcoming chapters. Summary In this chapter, we have seen how to use the Media Element to stream video files and use it effectively. Also we have seen the different options to restart, reset the videos to make it user friendly.
  81. 81. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 81 Working with Toast Notifications Introduction In this chapter, we are going to see how to use Toast Notifications in Windows Phone 7. Windows Phone 7 application development supports push notifications, which provides developers a much more convenient option to transfer message to a Windows Phone 7 device from a web service whenever a new event occurs. Push notifications are of 3 types, which are as follows  Toast Notification – This notification is launched at the top of the screen with a custom message such as an email alert or weather alert. The notification will be displayed for 10 second unless the user dismisses the alert. If the user clicks on the alert then the application which sends the notification will be launched  Tile Notification – This notification is used to display a dynamic representation of the application state. We can control the image, text and badge count of the notification.  Raw Notification – This notification is used only when the application is running on the foreground and if the application services are running in background. The notification will not be delivered and it gets discarded which is not delivered to the Windows Phone device. We will see each notification in depth and see a demo application for each notification in our upcoming chapters. Let us see the step by step process on how to create a TOAST application; we need to create a client application to send the notification to the device which we will be covering in this chapter. Steps Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7 application with a valid project name, as shown in the screen below.
  82. 82. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 82 Now add a button to create the push channel, which will be required to create a Toast notification. If there are any already available notification events available, it will use the same or else it will create a new notification event and then connect through the channel. Add the below XAML code to get the channel notification to trigger. XAML Code: <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="Toast Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left" Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click" /> </Grid> </Grid>
  83. 83. Windows Phone Development Step by Step Tutorial Karthikeyan Anbarasan, Microsoft MVP © 2012 www.F5debug.Net Page 83 Now we need to go to the code behind and start the process of establishing the Notification channel to get the event trigger. To do that, we first need to add the below two using statements. using Microsoft.Phone.Notification; using System.Diagnostics; Now we need to write the code to get the open channel details, which will be used to send the Toast Notification. To do that, we will use the output window to get the channel details. Use the code given below in the code behind for creating the channel. private void getChannelURI(Uri value) { Dispatcher.BeginInvoke(() => { Debug.WriteLine("URI: " + value.ToString()); }); Debug.WriteLine("URI: " + value.ToString()); } Now we need to handle the BindToShellToast of HttpNotificationChannel to bind the toast notifications. To do that, add the code below. private static void ShellBinding(HttpNotificationChannel httpChannel) { try { httpChannel.BindToShellToast(); } catch (Exception) { //Catach if required. } } Now we need to add the code below to check if the application is running correctly and get the toast notification message in order to log it for administration purposes. void Channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { Dispatcher.BeginInvoke(() => {

×