Launchers



Hands-On LabLaunchersLab version:1.0.0Last updated: DATE \@ "M/d/yyyy" 12/13/2011CONTENTS TOC \h \z \t "Heading 3,2,pp Topic,1,PP Procedure start,3" Overview PAGEREF _Toc305936991 \h 3Exercise 1: Introduction to the Windows Phone Launchers PAGEREF _Toc305936992 \h 7Task 1 – Using Launchers PAGEREF _Toc305936993 \h 7Summary PAGEREF _Toc305936994 \h 45OverviewThe launchers and choosers framework enables Windows Phone applications to provide common functions such as placing phone calls, sending emails, and taking pictures for their users.The Windows Phone application model isolates every application in its own work area for both execution (including memory isolation) and file storage. Windows Phone applications are not able to directly access common information stores such as the contacts list or to directly invoke other applications such as phoning or messaging. To support scenarios requiring common tasks such as phoning or messaging, the Windows Phone provides a set of launcher and chooser APIs that enables applications to access these useful phone features indirectly. The launcher and chooser APIs invoke distinct built-in applications that replace the currently running application. The launchers and choosers framework provides the end user with a seamless experience while masking the application switching that occurs in the background.The framework components are as follows:Launcher - A “fire and forget” action, where a specific Windows Phone functionality is launched, for example, sending an SMS message, opening a webpage, or placing a phone callBelow is the complete list of launchers that Windows Phone 7 Codenamed “Mango” supports:LaunchersConnectionSettingsTask - Enables to launch system settings application to control various connection settingsEmailComposeTask - Enables an application to launch the email application with a new message already displayed, so users can send email messages from within an applicationMarketplaceDetailTask - Enables an application to launch the Windows Phone Marketplace client application and display the details page for the specified productMarketplaceHubTask - Enables an application to launch the Windows Phone Marketplace client applicationMarketplaceReviewTask - Enables an application to launch the Windows Phone Marketplace client application and display the review page for the specified productMarketplaceSearchTask - Enables an application to launch the Windows Phone Marketplace client application and display the search results from the specified search parametersMediaPlayerLauncher - Enables an application to launch the media playerPhoneCallTask - Enables an application to launch the Phone application, so users can make a phone call from within an applicationSaveContactTask - Enables an application to launch the contacts application and provide initial data for new contact, so users can save the data from within an application to a new contactSaveEmailAddressTask - Enables an application to launch the contacts application, so users can save an email address from within an application to a new or existing contactSavePhoneNumberTask - Enables an application to launch the contacts application so users can save a phone number from within an application to a new or existing contactSearchTask - Enables an application to launch the Web Search applicationShareLinkTask - Enables an application to post a link with title and message via user’s social network accountShareStatusTask - Enables an application to post status update via user’s social network accountSmsComposeTask – Enables an application to launch the SMS applicationWebBrowserTask - Enables an application to launch the Web Browser applicationWhile it is always a good practice to think about application tombstoning during Window Phone development, one should consider tombstoning even more seriously when dealing with launchers and choosers.When does an application get tombstoned?Generally speaking, an application gets tombstoned [that is, it is placed in the back stack] when a user forward navigates away from it. While there are a few exceptions to this general rule, applications in the background may be tombstoned at any time if the system requires additional resources to carry out the current foreground activity.An application will not be automatically tombstoned when it launches an experience that feels to the user like an extension of the original application. These experiences are native flows that help the user complete some task, like choosing a photo. Avoiding tombstoning in these cases ensures a smooth flow between the application and the experience it has called [for example, no delay between choosing a photo and returning to the application that uses it].Below is the list of native experiences that, when invoked, do not trigger an automatic tombstone in the calling application:PhotoChooserTaskCameraCaptureTaskMediaPlayerLauncherEmailAddressChooserTaskPhoneNumberChooserTaskThere are three scenarios in which an application in the background will immediately be tombstoned:User forward navigates away from an application [for example, user presses the Start key]Application invokes launchers or choosers not listed aboveSystem requires more resources to carry out a foreground activityNote: All the above information regarding tombstoning is true for Windows? Phone 7.0. On Windows? Phone 7.1 launchers and choosers never initiate tombstoning, but it may be initiated nonetheless if the device requires additional resources. For more information on the new 7.1 application execution model please refer to documentation.ObjectivesUpon completion of this lab, you will:Be familiar with the launchers and choosers concept as implemented in the Windows Phone 7 application modelUnderstand how and when to use launchers and choosersHave created a Silverlight application that uses the wide array of available launchers and choosersPrerequisitesThe following is required to complete this hands-on lab:Microsoft Visual Studio 2010 Express for Windows Phone or Microsoft Visual Studio 2010Windows Phone Codenamed “Mango” Developer ToolsNote: You can download all of these tools together in a single package from hands-on lab is comprised of the following exercises:Introduction to the Windows Phone LaunchersEstimated time to complete this lab: 30 minutes.Exercise 1: Introduction to the Windows Phone LaunchersIn this exercise, you open the starter solution and complete the following tasks:Add and navigate to multiple pagesExplore a different launcher on each pageThe starting point for this exercise is the solution located in the lab installation folder under the Source\Begin folder.Task 1 – Using LaunchersA launcher is an API that launches one of the built-in applications through which a user completes a task and in which no data is returned to the calling application. An example of this is the PhoneCallTask. An application can provide this launcher with a phone number and a display name with which to invoke the phone. When the phone application is displayed, the user can select whether to initiate a call using the supplied parameters. When the user closes the phone application, the calling application is usually activated again, but the phone application does not return any data about or resulting from the user’s actions. When an application invokes a launcher, it does not get a return value.Open SavePhoneNumberPage.xaml.cs.Add the following code to the SavePhoneNumberPage class:C#//Regex patterns provided by string phoneNumberPattern = @"^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$";Add the following using statements:C#using System.Text.RegularExpressions;using Microsoft.Phone.Tasks;using System.Diagnostics;using System.Windows.Navigation;Override the OnNavigatedFrom and OnNavigatedTo functions in order to save the phone number into the page's state so it can be displayed again in case the application is tombstoned.C#protected override void OnNavigatedFrom(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedFrom function of SavePhoneNumberPage\t ***"); if (State.ContainsKey(inputStateKey)) State.Remove(inputStateKey); State.Add(inputStateKey, txtInput.Text); base.OnNavigatedFrom(e);}protected override void OnNavigatedTo(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedTo function of SavePhoneNumberPage\t ***"); if (State.ContainsKey(inputStateKey)) { string input = (string)State[inputStateKey]; txtInput.Text = input; State.Remove(inputStateKey); } base.OnNavigatedTo(e);}Add the input state key constant to the SavePhoneNumberPage class.C#const string inputStateKey = "input";Add a SavePhoneNumberTask variable to the SavePhoneNumberPage class.C#SavePhoneNumberTask savePhoneNumberTask;Add the following highlighted code to initialize the savePhoneNumberTask variable in the class constructor and output debug information. C#public SavePhoneNumberPage(){ InitializeComponent(); Debug.WriteLine("***\t In constructor of SavePhoneNumberPage\t ***"); savePhoneNumberTask = new SavePhoneNumberTask(); pleted += new EventHandler<TaskEventArgs>(savePhoneNumberTask_Completed);}Add the handler function for the completion event. C#void savePhoneNumberTask_Completed(object sender, TaskEventArgs e){ Debug.WriteLine("***\t In savePhoneNumberTask_Completed function of SavePhoneNumberPage\t ***"); if (e.TaskResult == TaskResult.OK) MessageBox.Show("Phone number saved successfully", "Success", MessageBoxButton.OK); else if (e.TaskResult == TaskResult.Cancel) MessageBox.Show("Phone number was not saved - operation was cancelled", "Contact not selected", MessageBoxButton.OK); else MessageBox.Show("Error while saving phone number:\n" + e.Error.Message, "Fail", MessageBoxButton.OK);}Use the regular expression to validate user input. If input passes validation, use the SavePhoneNumberTask to save the validated phone number. SavePhoneNumberTask enables an application to launch the contacts application. Use this to allow users to save a phone number from the calling application to a new or existing contact.C#private void btnSavePhone_Click(object sender, RoutedEventArgs e){ if (Regex.IsMatch(txtInput.Text, phoneNumberPattern, RegexOptions.IgnoreCase)) { if (null != savePhoneNumberTask) { savePhoneNumberTask.PhoneNumber = txtInput.Text; savePhoneNumberTask.Show(); } } else { MessageBox.Show("Specified value is not a valid phone number\nValid phone number looks like the following:\n1-(123)-123-1234, 123 123 1234, 1-800-ALPHNUM", "Invalid Input", MessageBoxButton.OK); } }Press F5 to compile and run the application. Navigate to the Save Phone Number page and type a valid phone number. To execute the Launcher click Save Phone Number. Add the phone number to a new or existing contact using the standard Windows? Phone 7 interface: Figure 1Adding a phone number to existing or new contactOptionally, give the contact a name.Save the contact and click Back ():Figure 2Launcher return notificationNote: The inserted phone number should appear in the input text box even though the application was sent to the background during the PhoneSaveTask operation. Analyze the debug output to gain a better understanding of this process.Repeat this step to add a new contact. Note: The emulator preserves contacts data only when it is running. Please do not close the emulator between the steps. This enables viewing the contact’s information later on in the lab.Press SHIFT+F5 to stop the debugger and return to editing mode.Open SaveEmailAddressPage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to save the email address into the page's state so it can be displayed again in case the application has been tombstoned .Add a SaveEmailAddressTask variable to the SaveEmailAddressPage class.C#SaveEmailAddressTask saveEmailAddressTask;Add the following highlighted code to initialize the saveEmailAddressTask variable in the class constructor. C#public SaveEmailAddressPage(){ InitializeComponent(); Debug.WriteLine("***\t In constructor of SaveEmailAddressPage\t ***"); saveEmailAddressTask = new SaveEmailAddressTask(); pleted += new EventHandler<TaskEventArgs>(saveEmailAddressTask_Completed);}Replace the handler function for the completion event. C#void saveEmailAddressTask_Completed(object sender, TaskEventArgs e){ Debug.WriteLine("***\t In saveEmailAddressTask_Completed function of SaveEmailAddressPage\t ***"); if (e.TaskResult == TaskResult.OK) MessageBox.Show("Email address saved successfully", "Success", MessageBoxButton.OK); else if (e.TaskResult == TaskResult.Cancel) MessageBox.Show("Email address was not saved - operation was cancelled", "Contact not selected", MessageBoxButton.OK); else MessageBox.Show("Error while saving email address:\n" + e.Error.Message, "Fail", MessageBoxButton.OK);}Use the regular expression to validate user input. If input passes validation, use the SaveEmailAddressTask to save the validated email address. SaveEmailAddressTask enables an application to launch the contacts application. Use this to allow users to save an email address from within the calling application to a new or existing contact.C#private void btnSaveEmail_Click(object sender, RoutedEventArgs e){ if (Regex.IsMatch(txtInput.Text, emailAddressPattern, RegexOptions.IgnoreCase)) { if (null != saveEmailAddressTask) { saveEmailAddressTask.Email = txtInput.Text; saveEmailAddressTask.Show(); } } else { MessageBox.Show("Specified value is not a valid email address\nValid email address looks like the following:\nsunil.rathore@, sun1programmer@", "Invalid Input", MessageBoxButton.OK); } }Press F5 to compile and run the application. Navigate to the Save Email page and type a valid email address. To execute the Launcher, click Save Email Address. Add the email address to a new or existing contact using the standard Windows? Phone 7 interface: Figure 3Adding an email address to existing or new contactSave the contact and click Back ():Press SHIFT+F5 to stop the debugger and return to editing mode.Open SearchTaskPage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to save the search term into the page's state so it can be displayed again in case the application has been tombstoned:To execute the search functionality this lab uses SearchTask. SearchTask enables an application to launch the Web Search application. Locate the btnSearch_Click event handler function and add the following code to the function body:C#private void btnSearch_Click(object sender, RoutedEventArgs e){ SearchTask searchTask = new SearchTask(); searchTask.SearchQuery = txtInput.Text; searchTask.Show();}Compile and run the application. Navigate to the Search page and input a search query: Figure 4Search PageClick Search Everywhere. It is possible, that the first search execution displays a screen asking to allow location information usage. Click Allow. The emulator connects to the Web and brings back the defined query results:Figure 5Web ResultsPress SHIFT+F5 to stop the debugging and return to editing mode in Visual Studio.Open WebSearchPage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to save the search term into the page's state so it can be displayed again in case the application has been tombstoned.Silverlight has a WebBrowser control that could be used as any other Silverlight control in the application. In addition Windows Phone has a WebBrowser launcher enabling Internet Explorer to be started directly from the application. To use it, this lab uses WebBrowserTask. WebBrowserTask enables an application to launch the Web browser application. Locate the btnGo_Click event handler function and add the following code to the function body:C#private void btnGo_Click(object sender, RoutedEventArgs e){ WebBrowserTask webBrowserTask = new WebBrowserTask(); const string url = "{0}&a=results"; webBrowserTask.URL = string.Format(url, txtInput.Text); webBrowserTask.Show();}Press F5 to compile and run the application.Navigate to the Search with Bing page and input a search query.The Launcher starts Internet Explorer and navigates to Bing web page:Figure 6Windows? Phone 7.1 IESwitch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open VideoPlayerPage.xaml.cs.Override the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.C#protected override void OnNavigatedFrom(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedFrom function of VideoPlayerPage\t ***"); base.OnNavigatedFrom(e);}protected override void OnNavigatedTo(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedTo function of VideoPlayerPage\t ***"); base.OnNavigatedTo(e);}From the Source\Assets folder of this lab, add an existing video file to the project’s Media folder.At the Add Existing Item dialog browse to the Assets folder of this lab, select the video file, and from the Add button drop down list select Add As Link.Figure 7Selecting the video fileMake sure the video file was added as a Content resource. To check it, click on the added file in Solution Explorer and press F4 to show the file properties.Figure 8Checking the Build Action of the added video fileAdd an event handler function to handle the button click event. The function will use the MediaPlayerLauncher which allows an application to launch the media player to play a video file. Add the following code to the class:C#private void btnPlayVideo_Click(object sender, RoutedEventArgs e){ MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher(); mediaPlayerLauncher.Location = MediaLocationType.Install; //means is a resource of the app, otherwise it will try to resolve it in Data (IsolatedStorage) for application mediaPlayerLauncher.Media = new Uri("Media/Bear.wmv", UriKind.Relative); mediaPlayerLauncher.Show();}Press F5 to compile and run the application.Navigate to the Video Player page and play the video.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open SaveRingtonePage.xaml.cs.Add the following using statements to the class:C#using System.IO.IsolatedStorage;using System.IO;Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to supply debug information when the application is tombstoned.Add a sound file that will serve as a ringtone to the project. Perform steps 48-50 inclusive a second time, but instead of adding “Bear.wmv” add “Ring.mp3”.Add the following highlighted code to create the debug information in the class constructor, and to deploy the sound file that we will use as the new ringtone to isolated storage. C#public SaveRingtonePage(){ InitializeComponent(); Debug.WriteLine("***\t In constructor of SaveRingtonePage\t ***"); PlaceAssetInIsolatedStorage();}Add the following additional methods for storing the ringtone in isolated storage:C#private static void PlaceAssetInIsolatedStorage(){ using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { Stream str = Application.GetResourceStream(new Uri("Media/Ring.mp3", UriKind.Relative)).Stream; IsolatedStorageFileStream outFile = iso.CreateFile("Ring.mp3"); outFile.Write(ReadToEnd(str), 0, (int)str.Length); str.Close(); outFile.Close(); }} private static byte[] ReadToEnd(System.IO.Stream stream){ long originalPosition = stream.Position; stream.Position = 0; try { byte[] readBuffer = new byte[4096]; int totalBytesRead = 0; int bytesRead; while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += bytesRead; if (totalBytesRead == readBuffer.Length) { int nextByte = stream.ReadByte(); if (nextByte != -1) { byte[] temp = new byte[readBuffer.Length * 2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); readBuffer = temp; totalBytesRead++; } } } byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { stream.Position = originalPosition; }}To allow the user to associate a ringtone with a contact, we will use the SaveRingtoneTask. Locate the btnSaveRingtone_Click event handler function and add the following code to the function body:C#private void btnSaveRingtone_Click(object sender, RoutedEventArgs e){ SaveRingtoneTask ringtoneTask = new SaveRingtoneTask(); ringtoneTask.Source = new Uri("isostore:/Ring.mp3", UriKind.Absolute); ringtoneTask.Show();}Press F5 to compile and run the application.Navigate to the “Save Ringtone” page and press the screens only button: “Save Ringtone”It will take you to the phone’s built-in ringtone saving screen, allowing you to specify a filename for the saved ringtone and to set it as the active ringtone:Figure 9The built-in ringtone saving screenSwitch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open SaveContactPage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.To allow the user to save information from application’s page into phone contacts, we will use the SaveContactTask. Locate the btnSaveContact_Click event handler function and add the following code to the function body (continue the “if” statement provided by starter solution):C#else{????SaveContactTask?saveContactTask?=?new?SaveContactTask();?????pany?=?txtCompany.Text;?????saveContactTask.FirstName?=?txtFirstName.Text;????saveContactTask.LastName?=?txtLastName.Text;????saveContactTask.JobTitle?=?txtJobTitle.Text;????saveContactTask.WorkEmail?=?txtWorkEmail.Text;????saveContactTask.Website?=?txtWebsite.Text;????saveContactTask.Nickname?=?txtNickname.Text;????pleted?+=?(s,?args)?=>????{????????if?(null?==?args.Error)?????????{?????????????MessageBox.Show(string.Format("Contact?{0}saved!",? (args.TaskResult?==?TaskResult.Cancel???"not?"?:?"")));?????????}?????????else?????????????MessageBox.Show("Error?saving?contact!");????};????saveContactTask.Show();}Press F5 to compile and run the application.Figure 10Saving contact informationNavigate to the Save New Contact page, provide required information and click “Save New Contact” button. Save the new contact and click Back ().Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ComposeEmailPage.xaml.cs.Use the following code to place an additional class in the file. We will use this class to store input data provided by the user:C#public class EmailInputData{ public string To { get; set; } public string Cc { get; set; } public string Bcc { get; set; } public string Subject { get; set; } public string Body { get; set; }}Override the OnNavigatedFrom and OnNavigatedTo functions in order to save the email data into the page's state so it can be displayed again in case the application has been tombstoned.C#protected override void OnNavigatedFrom(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedFrom function of ComposeEmailPage\t ***"); if (State.ContainsKey(inputStateKey)) State.Remove(inputStateKey); EmailInputData inputData = new EmailInputData { To = txtTo.Text, Cc = txtCc.Text, Bcc = txtBcc.Text, Subject = txtSubject.Text, Body = txtBody.Text }; State.Add(inputStateKey, inputData); base.OnNavigatedFrom(e);} protected override void OnNavigatedTo(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedTo function of ComposeEmailPage\t ***"); if (State.ContainsKey(inputStateKey)) { EmailInputData inputData = (EmailInputData)State[inputStateKey]; txtTo.Text = inputData.To; txtCc.Text = ; txtBcc.Text = inputData.Bcc; txtSubject.Text = inputData.Subject; txtBody.Text = inputData.Body; State.Remove(inputStateKey); } base.OnNavigatedTo(e);}To allow the user to compose an email, we will use the EmailComposeTask. EmailComposeTask enables an application to launch the built in email composer, using data supplied by the user to initialize the email message composed. Locate the btnCreateEmail_Click event handler function and add the following code to the function body:C#private void btnCreateEmail_Click(object sender, RoutedEventArgs e){ if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Emulator) { MessageBox.Show("This operation is not supported in the emulator. Please use an actual device."); return; } EmailComposeTask composeTask = new EmailComposeTask(); composeTask.To = txtTo.Text; = txtCc.Text; composeTask.Bcc = txtBcc.Text; composeTask.Subject = txtSubject.Text; composeTask.Body = txtBody.Text; composeTask.Show();}Note: Notice that we put code at the top of the handler method to prevent the task from being used on the Windows? Phone 7 emulator. We did this since the task cannot operate properly without setting an email account in the device and the emulator does not support setting up an email account.Be sure to set up an email account in your device for the next steps to work properly.Press F5 to compile and run the application.Navigate to the Compose Email page and fill out the desired fields: Figure 11Composing an emailPressing the “Create Email” button will take you to the phone’s built-in email composer, showing an email which contains the data supplied.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ShowMapPage.xaml.cs.Use the following code to place an additional class in the file. We will use this class to store input data provided by the user:C#public class MapInputData{ public bool CenterOnCoordinate { get; set; } public string Longitude { get; set; } public string Latitude { get; set; } public string Location { get; set; } public string ZoomLevel { get; set; }}Override the OnNavigatedFrom and OnNavigatedTo functions in order to save the map data into the page's state so it can be displayed again in case the application has been tombstoned.C#protected override void OnNavigatedFrom(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedFrom function of ShowMapPage\t ***"); if (State.ContainsKey(inputStateKey)) State.Remove(inputStateKey); MapInputData inputData = new MapInputData { CenterOnCoordinate = radioCoordinate.IsChecked.Value, Longitude = txtLongitude.Text, Latitude = txtLatitude.Text, Location = txtLocation.Text, ZoomLevel = txtZoom.Text }; State.Add(inputStateKey, inputData); base.OnNavigatedFrom(e);} protected override void OnNavigatedTo(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedTo function of ShowMapPage\t ***"); if (State.ContainsKey(inputStateKey)) { MapInputData inputData = (MapInputData)State[inputStateKey]; if (inputData.CenterOnCoordinate) { radioCoordinate.IsChecked = true; } else { radioLocation.IsChecked = true; } txtLocation.Text = inputData.Location; txtLatitude.Text = inputData.Latitude; txtLongitude.Text = inputData.Longitude; txtZoom.Text = inputData.ZoomLevel; State.Remove(inputStateKey); } base.OnNavigatedTo(e);}To allow the user to view the map, we will use the BingMapsTask. BingMapsTask enables an application to launch the built in maps application, using data supplied by the user to initialize the map’s position. Locate the btnShowMap_Click event handler function and add the following code to the function body:C#private void btnShowMap_Click(object sender, RoutedEventArgs e){ BingMapsTask mapTask = new BingMapsTask(); if (radioCoordinate.IsChecked.Value) { double longitude; double latitude; if (!double.TryParse(txtLongitude.Text, out longitude) || Math.Abs(longitude) > 180) { MessageBox.Show("Please supply a longitude between -180 and 180"); return; } if (!double.TryParse(txtLatitude.Text, out latitude) || Math.Abs(latitude) > 90) { MessageBox.Show("Please supply a longitude between -90 and 90"); return; } mapTask.Center = new GeoCoordinate(latitude, longitude); } else { mapTask.SearchTerm = txtLocation.Text; if (String.IsNullOrEmpty(mapTask.SearchTerm)) { MessageBox.Show("Please provide a location."); return; } } int zoomLevel; if (!int.TryParse(txtZoom.Text, out zoomLevel) || zoomLevel < 1 || zoomLevel > 19) { MessageBox.Show("Please supply a zoom level which is a whole number between 1 and 19."); return; } mapTask.ZoomLevel = zoomLevel; mapTask.Show();}Press F5 to compile and run the application.Navigate to the Show Map page and select a location using a search term or a coordinate: Figure 12Selecting a map locationPressing the “Show Map” button will take you to the phone’s built-in maps application, centered at the designated location:Figure 13The map centered at the designated locationNote: If you have not yet allowed the phone to use location information you may be prompted to do so now.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open DirectionsPage.xaml.cs.Use the following code to place an additional class in the file. We will use this class to store input data provided by the user:C#public class DirectionsInputData{ public string Origin { get; set; } public string Destination { get; set; }}Override the OnNavigatedFrom and OnNavigatedTo functions in order to save the directions data into the page's state so it can be displayed again in case the application has been tombstoned.C#protected override void OnNavigatedFrom(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedFrom function of DirectionsPage\t ***"); if (State.ContainsKey(inputStateKey)) State.Remove(inputStateKey); DirectionsInputData inputData = new DirectionsInputData { Origin = txtOrigin.Text, Destination = txtDestination.Text }; State.Add(inputStateKey, inputData); base.OnNavigatedFrom(e);} protected override void OnNavigatedTo(NavigationEventArgs e){ Debug.WriteLine("***\t In OnNavigatedTo function of DirectionsPage\t ***"); if (State.ContainsKey(inputStateKey)) { DirectionsInputData inputData = (DirectionsInputData)State[inputStateKey]; txtOrigin.Text = inputData.Origin; txtDestination.Text = inputData.Destination; State.Remove(inputStateKey); } base.OnNavigatedTo(e);}To allow the user to view directions, we will use the BingMapsDirectionsTask. BingMapsDirectionsTask enables an application to launch the built in maps application, using data supplied by the user to show directions between two locations. Locate the btnGetDirections_Click event handler function and add the following code to the function body:C#private void btnGetDirections_Click(object sender, RoutedEventArgs e){ BingMapsDirectionsTask directionsTask = new BingMapsDirectionsTask(); if (String.IsNullOrEmpty(txtOrigin.Text)) { MessageBox.Show("Please supply an origin."); return; } if (String.IsNullOrEmpty(txtDestination.Text)) { MessageBox.Show("Please supply a destination."); return; } directionsTask.Start = new LabeledMapLocation(txtOrigin.Text, null); directionsTask.End = new LabeledMapLocation(txtDestination.Text, null); directionsTask.Show();}Press F5 to compile and run the application.Navigate to the Directions page and select two locations between which you wish to get directions: Figure 14Selecting origin and destinationPressing the “Get Directions” button will take you to the phone’s built-in maps application, showing the desired directions.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ShareStatusPage.xaml.csNote we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.To share user’s status, we will use ShareStatusTask. Locate the btnShareStatus_Click event handler and add the following code to the function body:C#if?(txtStatus.Text.Length?>?0){????ShareStatusTask?shareStatusTask?=?new?ShareStatusTask();????shareStatusTask.Status?=?txtStatus.Text;????shareStatusTask.Show();}else????MessageBox.Show("Cannot?share?empty?status.\nPlease?enter?your?status?and?try?again",?"Share?Status?-?Error",?MessageBoxButton.OK);Press F5 to compile and run the application.Note: Status sharing functionality doesn’t works on emulator or if the device has no social accounts (Windows Live, Facebook, LinkedIn, Twitter) configured.Navigate to the Share Status page (in Social pivot page), provide new status and press the button to share it.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ShareLinkPage.xaml.csNote we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.To share link, we will use ShareLinkTask. Locate the btnSharelink_Click event handler and add the following code to the function body:C#if?(txtLink.Text.Length?>?0?&&?Uri.IsWellFormedUriString(txtLink.Text,?UriKind.Absolute)){????ShareLinkTask?shareLinkTask?=?new?ShareLinkTask();????shareLinkTask.Message?=?txtMessage.Text;????shareLinkTask.Title?=?txtTitle.Text;????shareLinkTask.LinkUri?=?new?Uri(txtLink.Text,?UriKind.Absolute);????shareLinkTask.Show();}else????MessageBox.Show("Cannot?share?link?or?link?is?invalid.\nPlease?check?your?input?and?try?again",?"Share?Link?-?Error",?MessageBoxButton.OK);Press F5 to compile and run the application.Note: Status sharing functionality doesn’t work on emulator or if the device has no social accounts (Windows Live, Facebook, LinkedIn, Twitter) configured.Navigate to the Share Link page (in Social pivot page), provide new link and press the button to share it.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ShowMarketplacePage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.To allow the user to view the marketplace, we will use the MarketplaceHubTask. MarketplaceHubTask enables an application to launch the built in marketplace browser. Locate the btnShowMarketplace_Click event handler function and add the following code to the function body:C#private void btnShowMarketplace_Click(object sender, RoutedEventArgs e){ MarketplaceHubTask marketplaceTask = new MarketplaceHubTask(); marketplaceTask.Show();}Press F5 to compile and run the application.Navigate to the Show marketplace page and press the button to go to the marketplace hub.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open ConnectionSettingsPage.xaml.csAdd the following code at the bottom of the page, before the end of namespace:C#public?class?ConnectionSettings{????public?string?Name?{?get;?set;?}????public?ConnectionSettingsType?TypeID?{?get;?set;?}}Now, add the following class-level variable which will be used as a source for page list box (at the top of ConnectionSettingsPage class):C#List<ConnectionSettings>?connectionTypes;Add the list initialization code to the class:C#private?void?InitializeConnectionTypes(){????connectionTypes?=?new?List<ConnectionSettings>();????connectionTypes.Add(new?ConnectionSettings()?{?TypeID?=?ConnectionSettingsType.AirplaneMode,?Name?=?"Airplane?Mode"?});????connectionTypes.Add(new?ConnectionSettings()?{?TypeID?=?ConnectionSettingsType.Bluetooth,?Name?=?"Bluetooth"?});????connectionTypes.Add(new?ConnectionSettings()?{?TypeID?=?ConnectionSettingsType.Cellular,?Name?=?"Cellular"?});????connectionTypes.Add(new?ConnectionSettings()?{?TypeID?=?ConnectionSettingsType.WiFi,?Name?=?"WiFi"?}); ????lstConnectionTypes.DataContext?=?connectionTypes;????lstConnectionTypes.SelectedIndex?=?0;}Call the function created before from class constructor - add the following code line after InitializeComponent() function:C#InitializeConnectionTypes();To allow the user to open system connection settings, we will use the ConnectionSettingsTask. ConnectionSettingsTask enables an application to launch the built in connection settings application, showing specific settings that matches defined settings type. Locate the btnConnectionSettings_Click event handler function and add the following code to the function body:C#ConnectionSettingsTask?connectionSettingsTask?=?new?ConnectionSettingsTask();connectionSettingsTask.ConnectionSettingsType?=? (lstConnectionTypes.SelectedItem?as?ConnectionSettings).TypeID;connectionSettingsTask.Show();This code snippet defines which connection settings will be presented (defined by getting selection in the listbox) and starts the launcher.Press F5 to compile and run the application.Navigate to the Connection settings page at Settings hub, select connection settings type and press the button to go to the relevant system settings page.Figure 15Connection settingsSwitch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open SearchMarketplacePage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to save the search term into the page's state so it can be displayed again in case the application has been tombstoned.To allow the user to search the marketplace, we will use the MarketplaceSearchTask. MarketplaceSearchTask enables an application to launch the built in marketplace application, showing only content that matches the search term. Locate the btnSearchMarketplace_Click event handler function and add the following code to the function body:C#private void btnSearchMarketplace_Click(object sender, RoutedEventArgs e){ MarketplaceSearchTask marketplaceTask = new MarketplaceSearchTask(); marketplaceTask.SearchTerms = txtSearchTerm.Text; marketplaceTask.Show();}Press F5 to compile and run the application.Navigate to the marketplace search page and enter a search term.Pressing the “Search Marketplace” button will launch the built-in marketplace application and search for content using the term provided:Figure 16Content matching the search termSwitch back to Visual Studio and press SHIFT+F5 to stop the debugger.Open MarketplaceDetailsPage.xaml.cs.Note we overrode the OnNavigatedFrom and OnNavigatedTo functions in order to add debug information when the application is being tombstoned.To allow the user to view the details for a marketplace app, we will use the MarketplaceDetailTask. MarketplaceDetailTask enables an application to launch the built in marketplace application to display a specific app’s details. Locate the btnMarketplaceDetails_Click event handler function and add the following code to the function body:C#private void btnMarketplaceDetails_Click(object sender, RoutedEventArgs e){ MarketplaceDetailTask marketplaceTask = new MarketplaceDetailTask(); marketplaceTask.ContentIdentifier = "35323b0f-84d8-df11-a844-00237de2db9e"; marketplaceTask.Show();}Press F5 to compile and run the application.Navigate to the marketplace details page and press the button to see the marketplace details for “The Harvest?”.Note: Marketplace and multimedia related actions do not work if the device is connected to a computer, even while debugging.Switch back to Visual Studio and press SHIFT+F5 to stop the debugger.This step concludes the exercise.Note: The solution for this exercise is located at this lab’s Source\End folder.SummaryThis lab illustrated the use of launchers in Windows Phone 7. Each of the application’s many pages serves as an example for using a specific launcher. Using these examples you should be able to easily utilize launchers in your future applications. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download

To fulfill the demand for quickly locating and searching documents.

It is intelligent file search solution for home and business.

Literature Lottery