47
Hands-On Lab Accessing Windows Phone 7 Devices Lab version: 1.0.0 Last updated: 5/5/2022 Page | 1 ©2011 Microsoft Corporation. All rights reserved.

Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Hands-On LabAccessing Windows Phone 7 DevicesLab version: 1.0.0

Last updated: 5/23/2023

Page | 1

©2011 Microsoft Corporation. All rights reserved.

Page 2: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

CONTENTS

Overview.....................................................................................................................................................3

Exercise 1: Capture Pictures Using the Camera Chooser.............................................................................5

Task 1 – Capturing an Image................................................................................................................5

Task 2 – Displaying a Captured Image...............................................................................................12

Exercise 2: Load and Store Pictures...........................................................................................................14

Task 1 – Saving and Loading Pictures to and from Isolated Storage..................................................14

Task 2 – Saving Pictures to the Pictures Hub.....................................................................................23

Exercise 3: Using the Location Device and Bing Maps...............................................................................25

Task 1 – Integrating GPS with Bing Maps...........................................................................................25

Task 2 – Assigning Pictures with Geographical Locations..................................................................32

Task 3 – Displaying Captured Pictures on a Bing Map.......................................................................36

Summary...................................................................................................................................................40

Page | 2

©2011 Microsoft Corporation. All rights reserved.

Page 3: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Overview

The Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers can leverage these devices to build location-aware applications and take live photos.

This lab walks you through the steps required to integrate your applications with the phone’s camera. The goal is to build an application that lets you capture pictures, give them a title, and save them to the application local store.

The lab also gives you the option to “fake” location and, when saving pictures to a local store, associate its latitude-longitude (lat-long) geo-coordinates, and create a view in which you can see the pictures on a map.

Objectives

At the end of the lab you will:

Be familiar with the Windows Phone 7 Camera Chooser API

Understand how to use the WP7 Location Device

Have saved pictures to the pictures hub

Have stored and loaded pictures and metadata from the Isolated Storage

Used Bing Maps control and services to fetch and display location data

Have created a simple map-based application with captured pictures

Prerequisites

The following is required to complete this hands-on lab:

Microsoft Visual Studio 2010 Express for Windows Phone or Microsoft Visual Studio 2010 (Microsoft Visual Studio 2010 Express for Windows Phone is part of the Windows Phone Developer Tools installation).

Windows Phone Developer Tools:

◦ http://go.microsoft.com/?linkid=9772716

◦ Silverlight for Windows Phone Toolkit (you can use the assemblies located in the assets folder): http://silverlight.codeplex.com/

Active Internet Connection

Page | 3

©2011 Microsoft Corporation. All rights reserved.

Page 4: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Note: If any of Microsoft.Phone.Controls.Toolkit or Microsoft.Expression.Interactions references are broken, you can remove them and add them again from the Assets folder which is part of this lab and can be found in <lab-folder>\Source\Assets\Libraries.

Exercises

This hands-on lab comprises the following exercises:

1. Capture pictures using Camera Chooser

2. Load and Store pictures

3. Using Location device and Bing Maps

Estimated time to complete this lab: 60 minutes.

Page | 4

©2011 Microsoft Corporation. All rights reserved.

Page 5: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Exercise 1: Capture Pictures Using the Camera Chooser

In this exercise you will:

Use the camera capture function to capture live pictures

Display captured pictures with their details

Task 1 – Capturing an Image

In this task you will use the camera capture chooser to capture a live image from both the WP7 emulator and device, and handle tombstoning situations while working with choosers.

Before you begin, please open the Source\Ex1 – CapturePictures\Begin.sln solution file, and review the code. The project is comprised of Models, Pages, Resources, the Application class, and the assets library.

Models in this case are passive data entities with no business logic. They are all derived from the NotifyingObject base class located in the AccessingWP7Devices.Assets project. The notifying object base class implements the .NET INotifyPropertyChanged interface for change notification, and provides minimal storage with generic get/set methods for holding the object’s state in a regular dictionary. In addition to models, there is a PictureRepository singleton object for handling and holding pictures. Currently the only thing it does is load the sample pictures, ResourcePicture, from the application resources into the pictures collection.

The Picture class represents a base class for captured pictures that you’ll create next, as well as for sample pictures located as resource in the resources folder.

To gain familiarity with the project, please build, deploy, and run it on the phone emulator.

Page | 5

©2011 Microsoft Corporation. All rights reserved.

Page 6: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 1First Run

The first page displays captured pictures. In our case, these are sample pictures for illustration. Clicking the camera app bar icon launches the Camera Capture built-in application, that lets you take pictures. You’ll implement this as your first task. Clicking the map app bar icon navigates to the Bing Map page. Next you’ll add a pictures layer and set your real location on this map. Clicking the picture app bar icon navigates to the pictures slide show, where you can start a slide show of the pictures you’ve captured.

1. To capture a picture, use the camera capture chooser. Open the PictureListPage.xaml.cs file and add a new field for holding the camera capture task.

Note: To ensure that your application receives the result of the Chooser task when your application is reactivated, the Chooser object must be defined within a global scope of the page and you must initialize the Chooser and assign the Completed event delegate in the page’s constructor.

You can read more about the Launchers and Choosers in the Hands-on-Lab.

C#

private readonly CameraCaptureTask _cameraTask;

Page | 6

©2011 Microsoft Corporation. All rights reserved.

Page 7: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

2. Initialize the camera task in the page’s constructor and register its Completed event. Replace the constructor with the following:

C#

public PictureListPage(){ DataContext = PictureRepository.Instance;

InitializeComponent();

_cameraTask = new CameraCaptureTask(); _cameraTask.Completed += cameraTask_Completed;}

private void cameraTask_Completed(object sender, PhotoResult e){}

Note: We want to display the camera task as first option when the camera app bar icon Is clicked.

3. In the ApplicationBarNewPicture_Click event handler, call the camera chooser Show method.

C#

private void ApplicationBarNewPicture_Click(object sender, EventArgs e){ _cameraTask.Show();}

Note: The camera capture task completion event argument contains both the captured picture temporary file name and a temporary picture stream. To create a picture using these properties and holding additional metadata you should create a special model class.

4. Add a new class called CapturedPicture to the project’s Model folder.

5. Add the DataContract attribute to the class so you can serialize it later for tombstoning.

C#

[DataContract]public class CapturedPicture{}

Page | 7

©2011 Microsoft Corporation. All rights reserved.

Page 8: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

6. Create a public property of the type byte[], named ImageBytes for holding the picture bytes and decorate it using the DataMember attribute.

7. Create a public property of the type string, named FileName for holding the picture file name and add the DataMember attribute.

C#

[DataContract]public class CapturedPicture{ [DataMember] public byte[] ImageBytes { get; set; }

[DataMember] public string FileName { get; set; }}

8. Derive the CapturedPicture class from the Picture base class and override the CreateBitmapSource method to return a new WriteableBitmap using the picture bytes.

Note: To create a WriteableBitmap from a stream use the PictureDecoder.DecodeJpeg helper method.

C#

[DataContract]public class CapturedPicture : Picture{ ... protected override BitmapSource CreateBitmapSource() { BitmapSource source = null; if (ImageBytes != null) { using (var stream = new MemoryStream(ImageBytes)) { source = PictureDecoder.DecodeJpeg(stream); }

Page | 8

©2011 Microsoft Corporation. All rights reserved.

Page 9: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

}

return source; } }

9. Create a default constructor and a constructor that has two parameters: one for the file name and the second for the picture stream. Set the ImageBytes property with the stream bytes. Set the FileName property with the short file name without the path. Set the Picture.DateTaken property to DateTime.Now as a long date string.

C#

[DataContract]public class CapturedPicture : Picture{ ... public CapturedPicture() { }

public CapturedPicture(string capturedFileName, Stream capturedImageStream) { ImageBytes = ReadImageBytes(capturedImageStream); DateTaken = DateTime.Now.ToLongDateString(); FileName = System.IO.Path.GetFileName(capturedFileName); }

private byte[] ReadImageBytes(Stream imageStream) { byte[] imageBytes = new byte[imageStream.Length]; imageStream.Read(imageBytes, 0, imageBytes.Length); return imageBytes; }}

10. Now you are ready to handle the camera capture task. In the cameraTask_Completed event handler located in the PictureListPage class, check to confirm that the task completed successfully; if so, create an instance of the type CapturedPicture using the event arguments OriginalFileName and ChosenPhoto.

C#

private void cameraTask_Completed(object sender, PhotoResult e){ if (e.TaskResult == TaskResult.OK)

Page | 9

©2011 Microsoft Corporation. All rights reserved.

Page 10: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

{ var capturedPicture = new CapturedPicture(e.OriginalFileName, e.ChosenPhoto); }}

Note: Opening a chooser causes the application to be deactivated. When a chooser finishes its job, the application is reactivated. Hence we should save the transient state (the captured picture in this case) before leaving the chooser and reload it when the application is reactivated.

11. To save the CapturedPicture instance, use the TransientState.Set<T> method. The TransientState type is a helper class located in the assets project. It simply wraps calls to the Microsoft.Phone.Shell.PhoneApplicationService helper class, which handles the phone’s transient state, with generic get/set methods.

C#

private void cameraTask_Completed(object sender, PhotoResult e){ if (e.TaskResult == TaskResult.OK) { var capturedPicture = new CapturedPicture(e.OriginalFileName, e.ChosenPhoto); TransientState.Set("capturedPicture", capturedPicture); }}

Note: Clicking “Back” while the camera chooser is active, closes the chooser and navigates back to the application directly to the last page visible by the user. In such cases, there may be no picture at all. If so, we want to stay on the same page if we have a picture to display. Otherwise, we want to navigate to the captured picture details page.

12. To load the captured picture at the moment the page is loaded, override the Page.OnNavigatedTo method and use the TransientState helper class to restore the captured picture state.

Note: When calling the TransientState.Get<T> method, make sure you pass ‘false’ as the last argument so that the captured picture is not removed from the state. You’ll extract it again later.

C#

protected override void OnNavigatedTo(NavigationEventArgs e)

Page | 10

©2011 Microsoft Corporation. All rights reserved.

Page 11: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

{ var capturedPicture = TransientState.Get<CapturedPicture>("capturedPicture"); base.OnNavigatedTo(e);}

13. Now that you’ve extracted the captured picture from the transient state, check if it is not null, then pass this state to the CapturedPicturePage page just before navigating to it (use TransientState.Set<T> and the CapturedPicturePage.ModelStateKey key that is expected by CapturedPicturePage); then navigate to the CapturedPicturePage.xaml page.

Note: You can use the NavigationServiceExtensions.Navigate<TPage> extension method with the relevant page type to easily navigate to the required page.

C#

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){ var capturedPicture = TransientState.Get<CapturedPicture>("capturedPicture"); if (capturedPicture != null) { TransientState.Set<CapturedPicture>(CapturedPicturePage.ModelStateKey, capturedPicture); NavigationService.Navigate<CapturedPicturePage>(); }

base.OnNavigatedTo(e);}

14. To test the results, build and run the application. Click the camera icon in the app bar to open the camera capture chooser. Take a shot and click accept. The CapturedPicturePage opens.

Page | 11

©2011 Microsoft Corporation. All rights reserved.

Page 12: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 2Capture a Picture

15. To test the phone’s Back button while the camera chooser is opened, go back to the main page, capture a picture, and now click Back. This should return to the main page.

Task 2 – Displaying a Captured Image

In this task you will create a simple view for displaying the captured picture, and provide a place for collecting user notes and displaying the date the picture was taken.

1. To display the captured picture you should first extract the captured picture from the transient state, stored in Task 1. Open the CapturedPicturePage.xaml.cs file and add a new get property (this property will not have any setter) of the type CapturedPicture named Model.

C#

private CapturedPicture Model{ get;}

2. Implement the Model property by getting the value from the page’s DataContext. You’ll use this later to bind the page’s control with the picture. First check if DataContext is null; if so try to extract the picture from the transient state set by the previous page. If it is still null, set the DataContext with a fresh instance of the type CapturedPicture.

Page | 12

©2011 Microsoft Corporation. All rights reserved.

Page 13: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

C#

private CapturedPicture Model{ get { if (DataContext == null) { var model = TransientState.Get<CapturedPicture>(ModelStateKey); if (model == null) { model = new CapturedPicture(); TransientState.Set(ModelStateKey, model); }

DataContext = model; }

return DataContext as CapturedPicture; }}

3. Override the Page.OnNavigatedTo and call the Model property. You will add code to this method later.

C#

protected override void OnNavigatedTo(NavigationEventArgs e){ var model = Model;

base.OnNavigatedTo(e);}

4. To test tombstoning, edit the note, lose focus, and then click the Windows button Followed by the Back button. You should notice that the picture and its details have been restored.

This concludes the exercise.

Note: You can find the complete solution for this exercise at Source\Ex1 - CapturePictures\End.

Page | 13

©2011 Microsoft Corporation. All rights reserved.

Page 14: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Exercise 2: Load and Store Pictures

In this exercise you will:

Save and load captured pictures to and from local isolated storage

Save captured pictures to the phone’s pictures hub

Task 1 – Saving and Loading Pictures to and from Isolated Storage

Isolated storage enables managed applications to create and maintain local storage. The mobile architecture is similar to Silverlight-based applications on Windows. All I/O operations are restricted to isolated storage and do not have direct access to the underlying operating system file system. Ultimately, this helps to provide security and prevents unauthorized access and data corruption.

Application developers have the ability to store data locally on the phone, again leveraging all the benefits of isolated storage, including protecting data from other applications

Before you begin, please open the Source\Ex2 – LoadAndStorePictures\Begin.sln solution file, and review the code. The project is comprised of Models, Pages, Resources, the Application class, and the assets library.

In this task you will learn how to use isolated storage to save and load captured pictures content and relevant details.

1. To save a captured picture in isolated storage, open the CapturedPicturePage.xaml.cs file and locate the ApplicationBarSavePicture_Click event handler, which handles the save app bar button click event.

2. Use the NotificationBox class located in the assets project to display a custom message to the user to ask where to save the captured picture. To display a message, call the NotificationBox.Show static method with Title, Message, and one MessageBoxCommand for handling the isolated storage.

C#

private void ApplicationBarSavePicture_Click(object sender, EventArgs e){ NotificationBox.Show( "Save picture", "Where would you like to save the picture?", SaveToLocalStorage);}

private NotificationBoxCommand SaveToLocalStorage{ get

Page | 14

©2011 Microsoft Corporation. All rights reserved.

Page 15: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

{ return new NotificationBoxCommand("local store", () => { }); }}

3. Implement the NotificationBoxCommand by adding the captured picture instance to the PictureRepository singleton pictures list located in the Models folder.

C#

private NotificationBoxCommand SaveToLocalStorage{ get { return new NotificationBoxCommand("local store", () => { PictureRepository.Instance.Pictures.Add(Model); }); }}

Note: You’re going to use serialization to store and load an object from Isolated Storage. There are several options for serializing an object in WP7: XML, Json and Binary. In our case we’ll use Binary serialization as it yields the best performance when using a real device.

4. To support binary serialization, open the Picture.cs file and implement the ISerializable interface located in the assets project, as virtual methods. In the Serialize method, store the Position, Address, Note, and DateTaken properties. Use the BinaryWriterExtensions located in the assets project for saving strings.

C#

public virtual void Serialize(BinaryWriter writer){ var position = Position ?? GeoCoordinate.Unknown; writer.Write(position.Latitude); writer.Write(position.Longitude); writer.WriteString(Address); writer.WriteString(Note); writer.WriteString(DateTaken);}

5. In the Deserialize method, read the data in the same order you’ve written it.

Page | 15

©2011 Microsoft Corporation. All rights reserved.

Page 16: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

C#

public virtual void Deserialize(BinaryReader reader){ double latitude = reader.ReadDouble(); double longitude = reader.ReadDouble(); Position = new GeoCoordinate(latitude, longitude); Address = reader.ReadString(); Note = reader.ReadString(); DateTaken = reader.ReadString();}

6. Open the CapturedPicture.cs file and override both Serialize and Deserialize methods.

C#

public override void Serialize(BinaryWriter writer){}

public override void Deserialize(BinaryReader reader){}

7. In the Serialize method, first call the base class Serialize, and then write the ImageBytes.Length, ImageBytes, and FileName properties. Use the BinaryWriterExtensions located in the assets project for saving strings.

C#

public override void Serialize(BinaryWriter writer){ base.Serialize(writer); writer.Write(ImageBytes.Length); writer.Write(ImageBytes); writer.WriteString(FileName);}

8. In the Deserialize method, first call the base class Deserialize, and then read the data in the same order you’ve written it.

C#

public override void Deserialize(BinaryReader reader){ base.Deserialize(reader); int bytesCount = reader.ReadInt32(); ImageBytes = reader.ReadBytes(bytesCount);

Page | 16

©2011 Microsoft Corporation. All rights reserved.

Page 17: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

FileName = reader.ReadString();}

9. Add a new empty method called SaveToLocalStorage to the PictureRepository that handles the save operation. This method gets two parameters: the captured picture instance and the name of the pictures folder in the isolated storage.

C#

public void SaveToLocalStorage(CapturedPicture capturedPicture, string directory){}

10. Open the CapturedPicturePage.xaml.cs file and call the SaveToLocalStorage method from the NotificationBoxCommand and navigate back to the previous page.

C#

private NotificationBoxCommand SaveToLocalStorage{ get { return new NotificationBoxCommand("local store", () => { // Cache image in repository. PictureRepository.Instance.Pictures.Add(Model); PictureRepository.Instance.SaveToLocalStorage(Model, PictureRepository.IsolatedStoragePath);

NavigationService.GoBack(); }); }}

11. Open the file named PictureRepository.cs under Models folder. In the SaveToLocalStorage method call IsolatedStorageFile.GetUserStoreForApplication to get an isolated storage file.

C#

public void SaveToLocalStorage(CapturedPicture capturedPicture, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication();}

Page | 17

©2011 Microsoft Corporation. All rights reserved.

Page 18: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

12. Call the IsolatedStorageFile.EnsureDirectory extension method located in the Common IsolatedStorageFileExtensions class to confirm that the pictures folder exists.

C#

public void SaveToLocalStorage(CapturedPicture capturedPicture, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(directory);}

13. Combine the pictures folder and captured picture file name and use this path to create a new file in the isolated storage by calling IsolatedStorageFile.CreateFile inside a using clause.

C#

public void SaveToLocalStorage(CapturedPicture capturedPicture, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(directory);

string filePath = Path.Combine(directory, capturedPicture.FileName); using (var fileStream = isoFile.CreateFile(filePath)) { }}

14. Inside the using clause, create a BinaryWriter instance for serializing the CapturedPicture instance and then call the CapturedPicture.Serialize method to serialize the captured picture.

C#

public void SaveToLocalStorage(CapturedPicture capturedPicture, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(directory);

Page | 18

©2011 Microsoft Corporation. All rights reserved.

Page 19: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

string filePath = Path.Combine(directory, capturedPicture.FileName); using (var fileStream = isoFile.CreateFile(filePath)) { using (var writer = new BinaryWriter(fileStream)) { capturedPicture.Serialize(writer); } }}

15. To load all saved pictures and add them to the pictures list page, add a new empty method called LoadFromLocalStorage to the PictureRepository class. This method gets two parameters: the picture file name and the pictures directory, and one return value: the captured picture.

C#

public CapturedPicture LoadFromLocalStorage(string fileName, string directory){}

16. To open the file, add a call to the IsolatedStorageFile.GetUserStoreForApplication in the LoadFromLocalStorage empty method.

C#

public CapturedPicture LoadFromLocalStorage(string fileName, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication();}

17. Combine the directory and file name, and use the path to open the picture file from the isolated storage by using the IsolatedStorageFile.OpenFile method inside a using clause.

C#

public CapturedPicture LoadFromLocalStorage(string fileName, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication();

string filePath = Path.Combine(directory, fileName);

Page | 19

©2011 Microsoft Corporation. All rights reserved.

Page 20: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

using (var fileStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) {

}}

18. Inside the using clause, create a BinaryReader instance for deserializing the CapturedPicture instance. In the using clause, create a new instance of the type CapturedPicture called CapturedPicture.Deserialize to deserialize the captured picture and return it.

C#

public CapturedPicture LoadFromLocalStorage(string fileName, string directory){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication();

string filePath = Path.Combine(directory, fileName); using (var fileStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(fileStream)) { var capturedPicture = new CapturedPicture(); capturedPicture.Deserialize(reader); return capturedPicture; } }}

19. To load all the pictures at start time, add another method called LoadAllPicturesFromIsolatedStorage to the PictureRepository class.

C#

private void LoadAllPicturesFromIsolatedStorage(){}

20. To the LoadAllPicturesFromIsolatedStorage empty method, add call to the IsolatedStorageFile.GetUserStoreForApplication to open an isolated storage file.

C#

private void LoadAllPicturesFromIsolatedStorage()

Page | 20

©2011 Microsoft Corporation. All rights reserved.

Page 21: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

{ var isoFile = IsolatedStorageFile.GetUserStoreForApplication();}

21. Call the IsolatedStorageFile.EnsureDirectory extension method located in the Common IsolatedStorageFileExtensions class to confirm that the pictures folder exists.

C#

private void LoadAllPicturesFromIsolatedStorage(){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(IsolatedStoragePath);}

22. Call the IsolatedStorageFile.GetFileNames using the pictures directory and *.jpg as a filter to get all saved pictures.

C#

private void LoadAllPicturesFromIsolatedStorage(){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(IsolatedStoragePath);

var pictureFiles = isoFile.GetFileNames(Path.Combine(IsolatedStoragePath, "*.jpg")); }

23. Iterate through all the picture files in the list and load each using the LoadFromLocalStorage you created earlier.

C#

private void LoadAllPicturesFromIsolatedStorage(){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(IsolatedStoragePath);

var pictureFiles = isoFile.GetFileNames(Path.Combine(IsolatedStoragePath, "*.jpg")); foreach (var pictureFile in pictureFiles) {

Page | 21

©2011 Microsoft Corporation. All rights reserved.

Page 22: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

var picture = LoadFromLocalStorage(pictureFile, IsolatedStoragePath); }}

24. Add each captured picture instance to the pictures collection.

C#

private void LoadAllPicturesFromIsolatedStorage(){ var isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoFile.EnsureDirectory(IsolatedStoragePath);

var pictureFiles = isoFile.GetFileNames(Path.Combine(IsolatedStoragePath, "*.jpg")); foreach (var pictureFile in pictureFiles) { var picture = LoadFromLocalStorage(pictureFile, IsolatedStoragePath); _pictures.Add(picture); }}

25. Call the LoadAllPicturesFromIsolatedStorage method from the PictureRepository constructor.

C#

private PictureRepository(){ LoadSampleImages(); LoadAllPicturesFromIsolatedStorage();}

26. To test the result, build and run the application. Then capture an image, write a note, click the save app button, and then click the ‘local store’ message button. This should save the image and navigate back to the picture list. You should see the picture at the bottom of the list. Click Back to close the application, and then run it again. The picture you’ve just saved should appear at the bottom of the list.

Page | 22

©2011 Microsoft Corporation. All rights reserved.

Page 23: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 3Save and Load from Isolated Storage

Task 2 – Saving Pictures to the Pictures Hub

In this task you will learn how to use the XNA library to save the captured pictures content to the phone’s pictures hub.

Note: The pictures hub doesn’t exist on the WP7 emulator. To test the result of this task you must deploy and run it on a real WP7 device.

1. To save the captured picture to the pictures hub, open the PictureRepository singleton class and add a new method named SaveToPicturesHub that has one parameter of the type CapturedPicture.

C#

public void SaveToPicturesHub(CapturedPicture picture){ }

2. Add a reference to the Microsoft.Xna.Framework .

3. In the SaveToPicturesHub empty method, create a new instance of type Microsoft.Xna.Framework.Media.MediaLibrary and call the MediaLibrary.SavePicture method with the captured picture file name and image bytes.

Page | 23

©2011 Microsoft Corporation. All rights reserved.

Page 24: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

C#

public void SaveToPicturesHub(CapturedPicture picture){ var mediaLibrary = new MediaLibrary(); mediaLibrary.SavePicture(picture.FileName, picture.ImageBytes);}

4. To invoke this method from the notification box added in previous task, open the CapturedPicturePage.xaml.cs file and locate the ApplicationBarSavePicture_Click event handler.

5. Add additional NotificationBoxCommand to the notification box which invokes the SaveToPicturesHub method you’ve just added and navigates back afterward.

C#

private void ApplicationBarSavePicture_Click(object sender, EventArgs e){ NotificationBox.Show( "Save picture", "Where would you like to save the picture?", SaveToPicturesHub, SaveToLocalStorage);}

private NotificationBoxCommand SaveToPicturesHub{ get { return new NotificationBoxCommand("pictures hub", () => { PictureRepository.Instance.SaveToPicturesHub(Model);

NavigationService.GoBack(); }); }}

6. To test the results on a real device, make sure that the WP7 device is connected and Zune software is running. In Visual Studio, select ‘Windows Phone 7 Device’ for the debug/deploy target, build and deploy the application, disconnect the device and run the application . Take a picture, click the save app bar button, and choose pictures hub. Exit the phone application, navigate to the pictures hub and you should find your new picture there.

Page | 24

©2011 Microsoft Corporation. All rights reserved.

Page 25: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Note: If you’ve installed the Windows Phone Developer Tools October 2010 Update , there is a tool called WPConnect.exe located in %ProgramFiles%\Microsoft SDKs\Windows Phone\v7.0\Tools\WPConnect. The Windows Phone Connect Tool allows you to establish serial or USB connectivity to the device without running the Zune software. This topic will provide guidance for installing the tool and using it to debug your Windows Phone applications. More information about this tool can be found here.

This concludes the exercise.

Note: You can find the complete solution for this exercise at Source\Ex2 - LoadAndStorePictures\End.

Page | 25

©2011 Microsoft Corporation. All rights reserved.

Page 26: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Exercise 3: Using the Location Device and Bing Maps

In this exercise you will:

Use the WP7 location device (GPS) to track and find your current location and display it on the map

Resolve your current location and street address

Display captured pictures on the exact location on the map

Note: This exercise requires a valid Bing Maps Application ID to access Bing Maps Services and the Bing Map Silverlight control for Windows Phone. Please refer to the Using Bing Maps lab to learn how to use the Bing Map control, access Bing Map Services and get Bing Maps Application ID. Before you begin, please open the App.xaml.cs file and set the BingId field with a valid application ID.

Task 1 – Integrating GPS with Bing Maps

In this task you’ll learn how to access the WP7 location device to track your current location and display it on the Bing Map.

To create an application which can be easily tested on the WP7 emulator you’ll use a GPS helper provided by this lab that works with both the GPS Emulator provided with this lab and the WP7 GPS device.

Before you begin, please open the Source\Ex3 – UsingLocationDevice\Begin.sln solution file, and review the code. The project is comprised of Models, Pages, Resources, the Application class, and the assets library.

1. Add the GpsHelper.cs file located in <lab-assets-directory>\Source to the project’s Common folder and review it.

The GpsHelper class is a singleton object that abstracts the location device by exposing a property of type IGeoPositionWatcher named Watcher. This property is initialized by calling the GpsHelper.WarmUp static method or by accessing the singleton instance. Depending on whether the GPS_EMULATOR symbol is defined or not, the GpsHelper selects the WP7 GPS or the GPS Emulator Client. Both implement the IGeoPositionWatcher interface which is an abstraction of the WP7 location device.

2. You’ll start by testing the phone application using the WP7 emulator and the GPS emulator provided with this lab. Make sure that the GpsHelper.cs file you’ve added contains #define GPS_EMULATOR as its first line. This tells the GpsHelper class to work with the GPS Emulator Client and not the real device.

Page | 26

©2011 Microsoft Corporation. All rights reserved.

Page 27: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

3. To warm-up the GPS device, call the GpsHelper.WarmUp static method from both the Application_Launching and Application_Activated event handlers located in the App.xaml.cs file.

Note: The reason for calling the WarmUp method from both the activated and launching event handlers is that the launching event handler is called only for fresh application instance and the activated event handler is called when returning back from tombstoning. Either way, the ctor is not a good place to put such a call.

C#

private void Application_Launching(object sender, LaunchingEventArgs e){ GpsHelper.WarmUp();}

private void Application_Activated(object sender, ActivatedEventArgs e){ GpsHelper.WarmUp();}

4. To display your location on the map, first you should add some properties to the MapModel class located in the Models folder. The MapModel class holds the MapPage data and exposes it for Data Binding. To the MapModel class add a new property called MyLocation of the type GeoCoordinate and add the DataMember attribute for tombstoning. This property will be used to bind the map to the location provided by the location device.

C#

[DataMember]public GeoCoordinate MyLocation{ get; set;}

5. Implement the property getter by calling the base.GetValue method that is defined in the NotifyingObject base class; implement the setter by calling the base.SetValue method. This method which is defined in the NotifyingObject base class notifies when a property is changed.

C#

[DataMember]

Page | 27

©2011 Microsoft Corporation. All rights reserved.

Page 28: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

public GeoCoordinate MyLocation{ get { return GetValue(() => MyLocation); } set { SetValue(() => MyLocation, value); }}

6. To keep tracking your location on the map, add a new property called TrackLocation of the type bool, add the DataMember attribute for tombstoning, and implement both the setter and the getter in order to use the SetValue/GetValue methodsrespectively.

C#

[DataMember]public bool TrackLocation{ get { return GetValue(() => TrackLocation); } set { SetValue(() => TrackLocation, value); }}

7. Update the MyLocation property setter to set the Center property with the new location when TrackLocation is true. The Center property centers the map to the specified location.

C#

[DataMember]public GeoCoordinate MyLocation{ get { return GetValue(() => MyLocation); } set { SetValue(() => MyLocation, value); if (TrackLocation) { Center = value; } }}

8. To display your location on the map and synchronize it with the location device, open MapPage.xaml.cs, override both OnNavigatedTo and OnNavigatedFrom, and register/unregister the GpsHelper.Instance.Watcher.PositionChanged respectively.

C#

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {

Page | 28

©2011 Microsoft Corporation. All rights reserved.

Page 29: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

GpsHelper.Instance.Watcher.PositionChanged += Watcher_PositionChanged;

base.OnNavigatedTo(e); }

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { GpsHelper.Instance.Watcher.PositionChanged -= Watcher_PositionChanged;

base.OnNavigatedFrom(e); }

private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e){ }

9. Implement the event handler to get the position from the event argument, and update the model’s MyLocation property.

C#private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e){ var position = e.Position.Location; if (position != GeoCoordinate.Unknown) { Model.MyLocation = e.Position.Location; }}

10. To start the map with a default location while loading, localize the InitializeLocation method and add the following highlighted lines.

C#

private void InitializeLocation(){ var defaultCoordinate = new GeoCoordinate(47.639631, -122.127713); Model.MyLocation = defaultCoordinate; Model.Center = defaultCoordinate; }

Page | 29

©2011 Microsoft Corporation. All rights reserved.

Page 30: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

11. To center the map on the current location, locate the ApplicationBarMyLocation_Click event handler and set the model’s Center property to the model’s MyLocation.

C#

private void ApplicationBarMyLocation_Click(object sender, EventArgs e){ Model.Center = Model.MyLocation;}

12. To keep tracking your location, locate the ApplicationBarTrackLocation_Click and inverse the Boolean value of the model’s TrackLocation property.

C#

private void ApplicationBarTrackLocation_Click(object sender, EventArgs e){ Model.TrackLocation = !Model.TrackLocation;}

13. Open MapPage.xaml and add a new MapLayer with one Pushpin to the map control. This pushpin is used to display your current location on the map.

XAML

<maps:MapLayer> <maps:Pushpin /></maps:MapLayer>

14. Bind the Pushpin.Location to the model’s MyLocation property (the model is already set with the page’s DataContext).

XAML

<maps:MapLayer> <maps:Pushpin Location="{Binding MyLocation}" /></maps:MapLayer>

15. Set the Pushpin.Style to the static resource keyed MyLocationPushpinStyle.

XAML

<maps:MapLayer>

Page | 30

©2011 Microsoft Corporation. All rights reserved.

Page 31: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

<maps:Pushpin Style="{StaticResource MyLocationPushpinStyle}" Location="{Binding MyLocation}" /></maps:MapLayer>

16. Compile and run. To test the results, open the GPS Emulator and then:

Go to the map by clicking the map app-bar icon.You should see a blinking red point; if not, click the target app bar icon to center the map. This is the location provided by the emulator

Change the position in the emulator and you should see the change reflected on the phone’s map

To center the map on your location, click the target icon Create a route using the GPS Emulator Click “Start” Click the route app-bar icon

You should see the map tracking your location

Figure 4The GPS Emulator

Page | 31

©2011 Microsoft Corporation. All rights reserved.

Page 32: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 5Location on Map

Page | 32

©2011 Microsoft Corporation. All rights reserved.

Page 33: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 6GPS Emulator Route

Task 2 – Assigning Pictures with Geographical Locations

In this task you will assign each captured picture with the exact geographical location provided by the location device and resolve the street address using the Bing Maps Service.

1. To set each picture with its geographical location, open the CapturedPicturePage.xaml.cs and create a new private method called ResolvePictureAddress, which has one parameter of the type CapturedPicture.

C#

private void ResolvePictureAddress(CapturedPicture picture){

}

Page | 33

©2011 Microsoft Corporation. All rights reserved.

Page 34: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

2. In the ResolvePictureAddress method use the GpsHelper to check if the GPS device is ready, and if so update the CapturedPicture position with the current location. If the GPS device is not ready, set the position to GeoCoordinate.Unknown.

C#

private void ResolvePictureAddress(CapturedPicture picture){ if (GpsHelper.Instance.Watcher.Status == GeoPositionStatus.Ready) { picture.Position = GpsHelper.Instance.Watcher.Position.Location; } else { picture.Position = GeoCoordinate.Unknown; }}

3. Now that the picture has a location, use the GeocodeHelper to resolve the street address by calling the GeocodeHelper.ReverseGeocodeAddress static method.

C#

private void ResolvePictureAddress(CapturedPicture picture){ if (GpsHelper.Instance.Watcher.Status == GeoPositionStatus.Ready) { picture.Position = GpsHelper.Instance.Watcher.Position.Location; GeocodeHelper.ReverseGeocodeAddress( Dispatcher, _credentialsProvider, picture.Position, result => picture.Address = result.Address.FormattedAddress); } else { picture.Position = GeoCoordinate.Unknown; }}

4. Locate the OnNavigatedTo override. In this method, confirm that the Model is not null and call the ResolvePictureAddress.

Page | 34

©2011 Microsoft Corporation. All rights reserved.

Page 35: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

C#

protected override void OnNavigatedTo(NavigationEventArgs e){ var model = Model; if (model != null) { ResolvePictureAddress(model); }

base.OnNavigatedTo(e);}

5. To display the picture location and address, open the CapturedPicturePage.xaml and add two TextBlocks to the StackPanel, right after the Image control.

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <Image Grid.Column="1" Grid.Row="1" Stretch="Uniform" Source="{Binding Source}" HorizontalAlignment="Left" Width="178" Margin="16" />

<TextBlock Margin="19,5,19,5" Opacity="0.5" /> <TextBlock Margin="19,5,19,5" Opacity="0.5"/>

<TextBlock Text="{Binding DateTaken}" Margin="19,5,19,5" Opacity="0.5"/> <TextBox AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Note, Mode=TwoWay}" Height="110" Margin="8,5,8,5" /> </StackPanel></Grid>

6. Bind the first TextBlock to the picture’s Position property.

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <Image Grid.Column="1" Grid.Row="1" Stretch="Uniform" Source="{Binding Source}" HorizontalAlignment="Left" Width="178" Margin="16" /> <TextBlock Text="{Binding Position}" Margin="19,5,19,5" Opacity="0.5" /> <TextBlock Text="{Binding Address}" Margin="19,5,19,5" Opacity="0.5"/>

Page | 35

©2011 Microsoft Corporation. All rights reserved.

Page 36: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

<TextBlock Text="{Binding DateTaken}" Margin="19,5,19,5" Opacity="0.5"/> <TextBox AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Note, Mode=TwoWay}" Height="110" Margin="8,5,8,5" /> </StackPanel></Grid>

7. Bind the second TextBlock to the picture’s Address property.

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <Image Grid.Column="1" Grid.Row="1" Stretch="Uniform" Source="{Binding Source}" HorizontalAlignment="Left" Width="178" Margin="16" /> <TextBlock Text="{Binding Position}" Margin="19,5,19,5" Opacity="0.5" /> <TextBlock Text="{Binding Address}" Margin="19,5,19,5" Opacity="0.5"/> <TextBlock Text="{Binding DateTaken}" Margin="19,5,19,5" Opacity="0.5"/> <TextBox AcceptsReturn="True" TextWrapping="Wrap" Text="{Binding Note, Mode=TwoWay}" Height="110" Margin="8,5,8,5" /> </StackPanel></Grid>

8. To test the results, make sure that you’re connected to the Internet, run the GPS Emulator as Administrator, then build and run the project. Capture a picture. You should see the geographical location initialized by the GPS Emulator and the street address provided by Bing Maps Services.

Page | 36

©2011 Microsoft Corporation. All rights reserved.

Page 37: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Figure 7Picture with Location and Address

Task 3 – Displaying Captured Pictures on a Bing Map

In this task, you’ll create a picture layer on the Bing Map to display each captured picture at the exact geographical location of capture.

1. To display pictures on the map, first you should add a collection of relevant pictures that has the valid location for the MapModel class. Open MapModel.cs and add a new read-only field of the type IList<Picture> named pictures.

C#

[DataContract]public class MapModel : NotifyingObject{ ... private IList<Picture> _pictures; ...}

2. Create a public get-only property of type IEnumerable<Picture> named Pictures that initializes the pictures field and populates it with pictures that have valid geographical locations (not equal to GeoCoordinate.Unknown), and then returns it.

C#

[DataContract]public class MapModel : NotifyingObject

Page | 37

©2011 Microsoft Corporation. All rights reserved.

Page 38: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

{ ... private IList<Picture> _pictures; public IEnumerable<Picture> Pictures { get { if (_pictures == null) { var pictures = from picture in PictureRepository.Instance.Pictures where picture.Position != GeoCoordinate.Unknown select picture;

_pictures = pictures.ToArray(); }

return _pictures; } } ...}

3. To add a new pictures layer to the map, open MapPage.xaml and add a new map layer of type MapItemsControl just before the my-location layer. MapItemsControl supports collection binding.

XAML

<maps:Map ...> <maps:MapItemsControl x:Name="picturesLayer"> </maps:MapItemsControl> </maps:Map>

4. Register to the MapItemsControl.MouseLeftButtonUp event with the picturesLayer_MouseLeftButtonUp event handler already located in the MapPage. This centers the relevant picture on first touch and scales it on second touch.

XAML

<maps:MapItemsControl x:Name="picturesLayer" MouseLeftButtonUp="picturesLayer_MouseLeftButtonUp"></maps:MapItemsControl>

Page | 38

©2011 Microsoft Corporation. All rights reserved.

Page 39: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

5. Bind MapItemsControl.ItemsSource to the model’s Pictures property.

XAML

<maps:MapItemsControl x:Name="picturesLayer" ItemsSource="{Binding Pictures}" MouseLeftButtonUp="picturesLayer_MouseLeftButtonUp"></maps:MapItemsControl>

6. Create an item template for displaying each picture as Pushpin contains one child of type Image.

XAML

<maps:MapItemsControl x:Name="picturesLayer" ItemsSource="{Binding Pictures}" MouseLeftButtonUp="picturesLayer_MouseLeftButtonUp"> <maps:MapItemsControl.ItemTemplate> <DataTemplate> <maps:Pushpin> <Image Width="64" /> </maps:Pushpin> </DataTemplate> </maps:MapItemsControl.ItemTemplate></maps:MapItemsControl>

7. Bind the Pushpin.Location to the picture’s Position property.

XAML

<maps:MapItemsControl x:Name="picturesLayer" ItemsSource="{Binding Pictures}" MouseLeftButtonUp="picturesLayer_MouseLeftButtonUp"> <maps:MapItemsControl.ItemTemplate> <DataTemplate> <maps:Pushpin Location="{Binding Position}"> <Image Width="64" /> </maps:Pushpin> </DataTemplate> </maps:MapItemsControl.ItemTemplate></maps:MapItemsControl>

8. Bind the Image.Source property to the picture’s Source property.

XAML

Page | 39

©2011 Microsoft Corporation. All rights reserved.

Page 40: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

<maps:MapItemsControl x:Name="picturesLayer" ItemsSource="{Binding Pictures}" MouseLeftButtonUp="picturesLayer_MouseLeftButtonUp"> <maps:MapItemsControl.ItemTemplate> <DataTemplate> <maps:Pushpin Location="{Binding Position}"> <Image Width="64" Source="{Binding Source}" /> </maps:Pushpin> </DataTemplate> </maps:MapItemsControl.ItemTemplate></maps:MapItemsControl>

9. To test the results, make sure that you’re connected to the Internet, run the GPS Emulator as Administrator, then build and run the project. Capture a picture, save it to local store, and go to the map and center the map to the current location. You should see your pictures at the exact geographical location on the map.

Figure 8My pictures on Bing Map

This concludes the exercise and the lab.

Note: You can find the complete solution for this exercise at Source\Ex3 - UsingLocationDevice\End.

Page | 40

©2011 Microsoft Corporation. All rights reserved.

Page 41: Accessing Windows Phone 7 Devicesaz12722.vo.msecnd.net/.../AccessingWP7Devices.docx · Web viewThe Windows Phone 7 is equipped with a Camera and GPS (global positioning system). Developers

Summary

During this lab, you learned how to use the Windows Phone 7 camera chooser to capture live pictures. You learned how to access the WP7 location device to locate your real geographical position and introduced with the GPS Emulator to test your location aware applications with the WP7 emulator. You resolved street address of your captured pictures based on the exact location provided by the location device and displayed them on the Bing Map.

Page | 41

©2011 Microsoft Corporation. All rights reserved.