Follow me on Twitter or the Puppy gets it          @benriga
Reading Contactsand Calendars
<Capabilities>  <Capability Name="ID_CAP_LOCATION"/>  <Capability Name="ID_CAP_MEDIALIB"/>  ... other capabilities here  <...
Other contact     CalendarData provider                                 Contact name Contact picture                      ...
using Microsoft.Phone.UserData;...Contacts cons;private void loadButton_Click(object sender,                              ...
void cons_SearchCompleted(object sender,                             ContactsSearchEventArgs e){    //Bind the results to ...
<ListBox Name="ContactsListBox"         ItemsSource="{Binding}" Height="347"         Margin="24,0,0,0" >    <ListBox.ItemT...
// enumerate the results we got back and get the sourceforeach (Contact contact in e.Results){    foreach (Account account...
Demo 1:Contact Display
cons.SearchAsync("Ro", FilterKind.DisplayName,                        "Contacts Load");// Find all the contacts with names...
apps.SearchAsync( new DateTime(2000, 1, 1),                  new DateTime(2012, 1, 1),                  "Appointment searc...
Creating a Contact
18
using Microsoft.Phone.Tasks;...SaveContactTask saveContact; //Declare with page scopepublic MainPage(){    saveContact = n...
void saveContact_Completed(object sender,                                 SaveContactResult e){    if (e.TaskResult == Tas...
21
Demo 2:Make a Contact                 22
23
Action                                   Chooser TaskGet addresses, phone numbers and email   AddressChooserTask,addresses...
Action                                     TaskOpen a web page                            WebBrowserTaskSearch the Marketp...
Using the Camera                   27
28
cameraTask = new CameraCaptureTask();cameraTask.Completed += new EventHandler<PhotoResult>                                ...
void cameraCapture_Completed(object sender, PhotoResult e){    if (e.TaskResult == TaskResult.OK)    {        photoImage.S...
Demo 3:Take a Picture                 31
32
using Microsoft.Devices;...PhotoCamera camera;...camera = new PhotoCamera();//Set the VideoBrush source to the cameraviewf...
<Rectangle Width="320" Height="240"                       HorizontalAlignment="Left" >    <Rectangle.Fill>        <VideoBr...
private void PhotoButton_Click(object sender,                                   RoutedEventArgs e){    camera.CaptureImage...
using Microsoft.Xna.Framework.Media;...void camera_CaptureImageAvailable(object sender,                                Con...
using System.Windows.Media.Imaging;...void camera_CaptureImageAvailable(object sender,                                Cont...
using System.IO;using System.IO.IsolatedStorage;...using (IsolatedStorageFile isStore =     IsolatedStorageFile.GetUserSto...
Demo 4:In-AppCamera          39
40
internal int FunkyColor(int color){    int a = color >> 24;    int r = (color & 0x00ff0000) >>   16;    int g = (color & 0...
camera = new Microsoft.Devices.PhotoCamera();// Create the destination for the processed imagewb = new WriteableBitmap(640...
void camera_Initialized(object sender,               CameraOperationCompletedEventArgs e){    pumpARGBFrames = true;    AR...
int[] ARGBPx = new int[640 * 480];...captureEvent.WaitOne();pauseFramesEvent.WaitOne(); //Thread sync with camera//Copies ...
private WriteableBitmap wb;...pauseFramesEvent.Reset();Deployment.Current.Dispatcher.BeginInvoke(delegate(){    //Copy to ...
Demo 6:FunkyCamera          46
Using the Microphone
http://msdn.microsoft.com/en-us/library/gg442302.aspx
Using Sensors
using Microsoft.Devices.Sensors;
if (Gyroscope.IsSupported){    // we have a gyro on the phone}
54
using Microsoft.Devices.Sensors;...Motion motion;...motion = new Motion();motion.TimeBetweenUpdates =                     ...
// Try to start the Motion API.try{    motion.Start();}catch (Exception){    MessageBox.Show("unable to start the Motion A...
private void CurrentValueChanged(MotionReading e){  if (motion.IsDataValid)  {  // Show the numeric values for attitude.  ...
Video Content
<MediaElement Name= "MediaPlayback"                  Source= "myvideo.wmv" AutoPlay="True"/>        http://msdn.microsoft....
<MediaElement Name= "MediaPlayback"Source="http://mschannel9.vo.msecnd.net/o9/mix/09/wmv/key01.wmv"AutoPlay="True"/>
private void pauseButton_Click(object sender,                                        RoutedEventArgs e){    MediaPlayback....
http://smf.codeplex.com/releases/view/63434#DownloadId=222617
63
http://aka.ms/mbl-phone/starthttp://aka.ms/mbl-phone/toolshttp://aka.ms/mbl-phone/mangohttp://aka.ms/mbl-phone/register
Follow me on Twitter or the Puppy gets it          @benriga
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
Upcoming SlideShare
Loading in …5
×

Windows Phone Launchers and Choosers

9,081 views

Published on

With Launchers and Choosers in Windows Phone, 3rd party apps integrate more closely into the underlying operating system while allowing end-users to perform common tasks. With Launchers and Choosers you will provide more functionality to your end-users while still maintaining that consistent user experience that will make your app feel like a native app. In this session we’ll cover how to use Windows Phone resources including camera, video and Bing maps. We’ll also cover accessing contacts and calendar as well as sensors (including accelerometer, compass, gyroscope and motion).

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
9,081
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
35
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • TopicsAt the completion of this module, students will be able to:Program a search of the Contacts database on the phoneDescribe the difference between Launchers and ChoosersWrite code to start a Launcher taskWrite code to start a Chooser task and to get the response back from itCode an application that will process the video stream coming from the cameraDescribe the sensors and video support in Windows Phone OS 7.1
  • Reading Contacts and CalendarsThis section of this module shows how to select data from the phone Contacts and Calendar databases. 
  • Your ObligationsThe Contacts data on a phone is a valuable data store that contains data that is private to the user of the phone. Your application must request permission from the user to access the phone’s contacts data store, and if you do not do this, your application will fail certification.Refer to the Application Certification Policies: http://msdn.microsoft.com/en-us/library/hh184841(v=VS.92).aspxThe documentation refers to policy 2.11, which is not yet in place.   
  • Application CapabilitiesThere are two specific capabilities that your application must request in the WMAppManifest.xml file. It is important to request the correct capabilities for the features that your application uses, and this is particularly important for user data such as contacts and appointments.If a capability is not requested that is required, the application will fail when submitted.If a capability is requested that is not used the user may get asked to approve an access that is not required.  
  • Contacts and Calendar ProvidersA Windows Phone user can link their phone to many different sources of contact data, such as from Exchange accounts, Facebook, Twitter etc. The Contacts list on the phone is an aggregated view of all the contacts from all the different data sources the user has configured. In addition, a user may choose to link together different Contacts list entries that all relate to the same physical person, and in that case the Contacts properties shown in the built in Contacts application is a combined view of the linked contact records.The exact Contact properties you can get when you do a search of the user data store is dependent on the original source of the contact data. The limitations are not technical, but to do with licensing and privacy issues.
  • Data SourcesWindows Phone provides an aggregated view of the user’s contact data across the user&apos;s different accounts. Information can come from sources such as data entered in the phone itself, social networking sites, and other data service providers. Not all data from all service providers is exposed publicly through the contacts and calendar API.The restrictions on data from certain sources is not technical, it’s down to licensing reasons and the desire of certain data providers to limit access to calls to their own APIs.
  • Reading ContactsThis is the code for a “Load Contacts” button click event. You can of course access contacts data anywhere in your applications. It is an abridged version of the code in the example to come.The process for accessing contact data is to get a reference to the Contacts object, perform an asynchronous search on it, and then capture the results as a collection of Contact objects. You can use the results in different ways.Using the code shown here, the operation is not filtered, and will return all the contacts. However, you can put filters on the search.Note: Contact data can vary widely in size. Be prepared for very large contact lists by providing a message to the user when you are loading data.    
  • Displaying ContactsIn the demo we’re about to see, the collection of Contact objects we get back from the search is set to be the DataContext of a ListBox control. The data template for the ListBox uses data binding to show the DisplayName property of each Contact in the listbox.The collection of Contact objects you get back is an IEnumerable, so you can use a foreach construction to loop through the Results enumeration; that’s fine too.    
  • Data BindingThis is the XAML that displays the list. Here you can see that the TextBlock in the DataTemplate uses data binding syntax to display the Displayname property of each Contact in the results.Notice too that this is OneWay data binding (as the Mode property on the Binding statement says). You could not use TwoWay data binding here and allow users of your app to update Contact records, since the Contact data you get back is READ ONLY.    
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • Displaying AppointmentsThis works in exactly the same way as for contacts. There is an example application you can use if you wish, but there are no appointments on the emulator, so it doesn’t really show much.There are different overloads for SearchAsync that give slightly different filtering options for Appointments:You can select all appointments that occur between a specified start date and time and end date and time. You can additionally filter the search only to appointments from a specific data source.You can limit the number of results returned   
  • Creating a ContactIn this section, we introduce the Launchers and Choosers, which allow apps to invoke some of the built-in experiences of the phone.
  • Creating a ContactYou cannot design a page in your application to allow users to input details for a Contact, and then programmatically create a Contact. You can however launch the SaveContactTask which shows the built-in ‘Edit Contact’ experience of the phone which can be prefilled with some data you supply in code. Ultimately, the user must tap the ‘Save’ button to save the contact, after which control passes back to your program. Windows Phone allows you to launch a number of similar built-in experiences using a set of APIs called the Launchers and Choosers. By restricting app developers to interaction with phone user data and experiences in this way, Windows Phone ensures consistency for the user – if an app allows the user to create a Contact, it will always be done in the same way, using the familiar ‘Edit Contact’ page used by the built-in Contacts app. This is another reinforcement of the “user is king” paradigm. The phone will not allow an application to do substantive things (like create a contact) without the user being involved.  
  • Launchers and ChoosersImportant points about the application lifecycle:The application loses its foreground status when a Launcher or a Chooser is fired up, so is deactivated and becomes dormant.In the case of a Chooser, the application will be resumed automatically when the user has made their choice and exits or quits the chooser.In the case of a Launcher the application will be resumed if the user navigates back after they have used the launched item.In either case the application must be designed to handle dormant/tombstone issues if you are to use Launchers and Choosers.When your app shows a launcher or chooser, they are switching to one of the built-in applications. In the middle of that, they could decide to press the Windows button and go to run something else. Your app may never be resumed, so you must consider dormant/tombstoned issues when using launchers and choosers.   
  • Creating a ChooserIn this sample, we have a first name and last name that are going to be used as the basis of our new contact.These will get populated into the chooser that displays.Make the point that we can fill in all the contact fields for the new contact, but the user can change these in the dialog if they wish.IMPORTANT: When using Choosers, you must declare the task object (SaveContactTask) with page scope as shown here. You must instantiate the object and assign the Completed event handler in the page constructor. Then call the Show() method when you are ready to launch the Chooser task.These steps are necessary to correctly handle Tombstoning of your app, should that occur because the user has gone off and run many other apps after the Chooser is launched.   
  • Chooser CompletionMake the point that saving a contact is not really worthy of the name “chooser”, since the only choice the user makes is whether or not to save the contact; but they don’t really choose anything. Nonetheless, the SaveContactTask behaves in the same way as the other Chooser tasks and does return some data to the application.It is useful to know if the user has saved the contact or not, and that is what is returned.Note however that if the user changes the name of the contact (or any other details) and then saves the changed contact data, your application has no way of knowing this has been done. So it is not a guarantee that the item has been saved with exactly the properties that your application set before launching the task. The only way to be sure is to retrieve the contact details after it has been saved and check it against the information you provided.   
  • Application SwitchingThis is a very important point. We already mentioned it once, but we are going to mention it again.Because it is a very important point.Calling a Launcher or a chooser represents a handoff of control, which you may never get back.When the chooser is called an application is made dormant, so the Deactivated methods will be called. When the chooser completes the application is activated and must restore any state information. Then, once the application has been restarted, only then will the chooser Completed event handler method be called in the application.This will mean you will have to be mindful of application state when using launchers and choosers.   
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • Other Save TasksThe other ‘Save’ Choosers are the SaveEmailAddressTask, SavePhoneNumberTask and SaveRingtoneTask. They all work in a similar fashion to the SaveContacttask.There is no way to create an appointment at the moment.But an application can create an alarm for that application which will fire at a particular time (covered later in this module).   
  • Chooser TasksThe slide shows a complete list of all the Choosers available in Windows Phone Mango.There are complete examples of how to program each of these tasks in the Windows Phone developer documentation on MSDN: http://msdn.microsoft.com/en-us/library/ff769556(v=VS.92).aspx    
  • Launcher TasksThese are all the Launchers. Launchers are similar to Choosers in that you are invoking one of the phone built-in experiences from your application. However, Launchers differ from Choosers in that they do not have a Completed event and do not return any data to your application.As with Choosers, your app is deactivated and made dormant when the Launcher is atartedyou’re your app will be reactivated when – or if – the user backs out of the launched experience and navigates back to your app.There are complete examples of how to program each of these tasks on MSDN  
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • Using the Camera 
  • The Windows Phone CameraYour app can show the CameraCaptureTask Chooser to invoke the built-in Camera app. Whe the user takes the picture, the resulting image file is returned to your application through the arguments to the Completed event.Alternatively, you can write code to access the camera hardware directly and capture a video stream from the camera. The ability to capture a video stream is new to Mango.   
  • Capturing a photoThe CameraCaptureTask is a Chooser so uses the standard Completed event behaviour that we have seen before.One gotcha that most developers will encounter when testing software that uses this: it will not work if the phone is connected to the Zune software. You have to close Zune and launch WPConnect instead (mentioned previously in session 1).   
  • Capture completeNote that photos captured in this way are not added to the camera roll in the Media Library on the device, but you can write code to save it to the media Library of you wish, or just use it in your app, or store in your apps isolated storage for later use.   
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • In application captureWindows Phone supports programmatic access to the camera on a device, offering a rich set of APIs for developers to create their applications. Some features include: Creating a camera application with a viewfinder and capturing still photosProviding real-time access to raw frames from the cameraAdjusting the resolution of the captured photoImplementing functionality such as focus and flashDetecting and querying the device camera capabilities such as flash Accessing the camera hardware shutter button for capturing photos and triggering auto-focusNote that a camera is not required hardware for all Windows Phone devices. It is important that you consider this when designing and implementing your application. Your application should always check to see whether a camera is available (use PhotoCamera.IsCameraTypeSupported)and fail gracefully if it is not. 
  • The PhotoCamera classThe PhotoCamera is the class that abstracts the camera behaviours. It lives in the Microsoft.Devices namespace.The code shown here sets the source of a Silverlight VideoBrush element to be the camera. This is how you implement a viewfinder window for your app (shown in next slide). The code also hooks the CaptureImageAvailable event so you can execute code to process a captured image.    
  • Displaying the ViewfinderThis XAML displays a viewfinder on the screen. The VideoBrush element in here is assigned to the camera by the call of SetSource as shown on the previous slide.   
  • Initiating the CaptureIn this sample, we have a button on the screen that the user presses to take a picture. The code shown is the click event handler for the button, which causes an image to be captured from the camera.When the photograph has been taken the CaptureImageAvailable event will fire. You can also write your code to use the hardware camera button on the phone – needless to say that is the better approach. See MSDN documentation for details of how to do that.    
  • Saving the imageThe code shows how to save the captured image to the camera roll in the phone’s media library. Note that the MediaLibrary class lives in the XNA framework, so you must add the XNA library references into your Silverlight app to use them. The filename is made of the number of ticks in the date plus the jpg extension.Make the point that this action must take place on the UI thread, which is what the Dispatcher.BeginInvoke is for. Note that a PhoneApplicationPage object exposes a Dispatcher property you can use to execute code on the UI thread. However, in class libraries, you can also get access to the Dispatcher using Deployment.Current.Dispatcher as shown here.   
  • Displaying the imageYou can also display the image in an &lt;Image&gt; element on the screen.To do that, you must create a BitmapImage object from the captured image stream, and then set the Source property of the &lt;Image&gt; to the BitmapImage object, as shown here.   
  • Saving to isolated StorageNote that this code carries on from the previous slide.The variable b is the BitmapImage object we created in the previous slide. The variable filename holds the name of the file being created in isolated storage. This code saves the image as a JPG file in isolated storage.   
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • Working with Image DataIn addition to capturing pictures, you can use the device camera to capture video. You can perform real-time processing on the video stream, useful in applications that use Augmented Reality, or for things such as auto-scanning of barcodes.We are going to use this to build a funky camera, which will funkify the video stream. 
  • Funky Image ProcessingThis is the ‘brains’ of the funky image processing. We can get the argb value as an int for every pixel in a captured frame of video and process it.This method is going to get called for each pixel in the screen. It simply extracts the alpha, red, blue and green values from the pixel color and adds an offset to each.   
  • Starting the Camera (1 of 2)This is part of the setup.You instantiate a PhotoCamera object and assign an event handler for the Initialized event.You would call this code after the Silverlight page is loaded.   
  • Starting the Camera (2 of 2)This bit starts the message pump running.In the handler for the PhotoCameraInitialized event, we create a new thread called ARGBFramesThread and start it running. The logic to execute on the thread is in the PumpARGBFrames method.Emphasise that the video frame processing is running on a new thread, alongside the application.    
  • Getting the Image DataThis code is the body of the PumpARGBFrames method that is running on the background thread. It uses a couple of synchronization objects called captureEvent and pauseFramesEvent to do some thread synchronisation to make sure that the thread and the camera work smoothly together and don’t get stuck.When the camera has captured a frame, this code is freed to run. It calls the GetPreviewBufferArgb32 method of the PhotoCamera object to get the image as an array of ints, and then calls our FunkyColor method that you saw earlier to ‘funkify’ it.Make the point that this code is all in the sample that they can have in a minute   
  • Drawing the Image DataAfter we have funkified the frame, the code draws it onto the screen. Note that because the WriteableBitmap object that the code writes to is used as the source of an &lt;Image&gt; element that is on the Silverlight page, and thus controlled by the UI thread, we have to use a Dispatcher to perform this copy. The Dispatcher executes the code you pass to the BeginInvoke method on the UI thread.   
  • For demonstration notes please look in the “Demonstration” folder and open the corresponding Word document.
  • Using the Microphone 
  • The Windows Phone MicrophoneYou can get audio input from the Windows Phone microphone in a Silverlight application by using the Microsoft.Xna.Framework.Audio.Microphone class.The Microphone sample walkthrough at the url shown is very good and takes you through everything you need to know.Unfortunately, we don’t have time on this course to cover it in detail here.   
  • Using Sensors 
  • Sensors AvailableWindows Phone supports multiple sensors that allow applications to determine the orientation and motion of the device. These sensors enable the development of applications where the physical device itself is a means of user input. Typical uses for this functionality include motion-controlled games and augmented reality applications. For many of these purposes, the combined motion API, which combines and processes input from all sensors, is the simplest way to obtain motion and orientation information. For applications that require it, Windows Phone also provides APIs to retrieve data from the individual sensors. 
  • The Sensors LibraryYou will need to add a reference to the Microsoft.Devices.Sensors library to your project. The sensors library is not automatically included in a new project created from the project templates in Visual Studio.   
  • Determining Sensor AvailabilityYou must always check to see if the sensor is there before you use it. Pre mango phones all had a compass but there was no developer API that allowed apps to use it. In Mango, this data is now available to apps. Newer phones may also have a gyroscope, but this is optional for the OEM whether they include this, so check before you try to use it. All phones have an Accelerometer, so if a Gyroscope is not available, you can use the Accelerometer instead as a fallback.   
  • The Motion SensorFor most applications, the combined motion API, which combines and processes input from all sensors, is the simplest way to obtain motion and orientation information. There are physical limitations that can make it difficult to determine the actual orientation and motion of a device from the raw data from the sensors by Windows Phone. For example, readings from the accelerometer include the force of gravity applied to the device in addition to the force resulting from the motion of the device. The gyroscope sensor measures rotational velocity, not position, and so it is subject to drift. Also, there are complex geometrical calculations that are needed to translate the raw data from these sensors into the true orientation of the device. For typical applications that use this type of data, such as augmented reality applications, using the Motion class is recommended.  
  • Motion DataThe Motion class handles the low-level sensor calculation and allows applications to easily obtain the device’s attitude (yaw, pitch, and roll), rotational acceleration, and linear acceleration both due to gravity and user movement. There is a very good range of data here.Note that the angles are in radians, which can catch people out.Make the point that although all phones have a compass in hardware it is not guaranteed that they will have low level drivers that will allow it to work even when Mango is added. Currently, Windows Phone Marketplace uses the compass sensor to determine if the Motion API is supported on a device. If a user views an application that uses the Motion API and their device lacks a compass, they will receive a warning that the application requires a compass sensor.Also, the Motion sensor does not work with the emulator, which only emulates the accelerometer.   
  • Using a SensorYou can select the rate at which you want the sensor to try and update. Note that the sensor itself will have a particular speed, so making this time very short (less than 20 ms) will not make much difference, but it will slow the phone down.  
  • Using the Motion SensorTo get the new sensor readings, simply handle the CurrentValueChanged eventPoint out that in Silverlight, event driven content is fine, but in XNA there is an expectation that sensors will be polled, which is not the case in respect of the Motion sensor. In an XNA game, we must store the values that we get from handling the CurrentValueChanged event, and then read the stored values when the Update method runs (30 times per second).There are examples of how to do this with the Accelerometer (which works the same way) in the XNA deck.   
  • Video Content 
  • Video on the PhoneVideo playback is very easy on the Windows phone platform.You can use the MediaPlayerLauncher class to embed audio or video. For a more customizable UI, you can use the Silverlight MediaElement API, which is easy to program.There are many supported codecs – see the MSDN documentation. Windows Phone can play media encoded as WAV, WMA, WMV, MP3, MP4, 3G2, 3GP, AAC and others.    
  • Streaming Video on the PhoneYou can handle streaming video using the MediaElement API. Simply set the Source property to a URL.The code snippet starts the video playing automatically. You can add Stop, Start, Pause functionality into your UI and control playback of the MediaElement.  
  • Controlling PlaybackYou can interactively control media playback by using the Play, Pause, and Stop methods of a MediaElement object.The code snippet on the previous slide had AutoPlay=”true” which starts the video playing automatically. You can add Stop, Start, Pause functionality into your UI and control playback of the MediaElement.   
  • Smooth StreamingMicrosoft Media Platform: Player Framework (MMPPF) is Microsoft&apos;s open source media player framework - a component of the Microsoft Media Platform. This project was formerly known as the Silverlight Media Framework (SMF). MMPPF enables developers to quickly deploy a robust, scalable, customizable media player for IIS Smooth Streaming delivery. The MMPPF now includes full support for Windows Phone 7 so developers can incorporate high-end video playback experiences in their Windows Phone 7 applications. 
  • ReviewIn this module, you learned about:Launchers and Choosers, which allow your applications to invoke some of the built-in experiences on the phone and incorporate them into your applicationsLaunchers simply invoke a built-in experienceChoosers launch a built-in experience and get some data passed back when completeApplications can use the CameraCaptureTask chooser to add picture taking capability to their apps, or can use the Photocamera object to get direct programmatic access to the camera hardware and allows direct manipulation of the video streamWindows Phone supports playing of video content   
  • Windows Phone Launchers and Choosers

    1. 1. Follow me on Twitter or the Puppy gets it @benriga
    2. 2. Reading Contactsand Calendars
    3. 3. <Capabilities> <Capability Name="ID_CAP_LOCATION"/> <Capability Name="ID_CAP_MEDIALIB"/> ... other capabilities here <Capability Name="ID_CAP_CONTACTS"/> <Capability Name="ID_CAP_APPOINTMENTS"/></Capabilities>
    4. 4. Other contact CalendarData provider Contact name Contact picture data appointmentsWindows Phone Device Yes Yes Yes YesWindows Live Social Yes Yes Yes YesWindows Live Rolodex Yes Yes Yes YesExchange Accounts(Contacts from local address book only, not Yes Yes Yes YesGlobal Address List.)Mobile Operator Address Book Yes Yes Yes NoFacebook Yes Yes No NoWindows Live Aggregated Networks No No No No(Twitter, LinkedIn, etc.)
    5. 5. using Microsoft.Phone.UserData;...Contacts cons;private void loadButton_Click(object sender, RoutedEventArgs e){ cons = new Contacts(); cons.SearchCompleted += new EventHandler <ContactsSearchEventArgs>(cons_SearchCompleted); cons.SearchAsync(String.Empty,FilterKind.None, "Contacts Load");}
    6. 6. void cons_SearchCompleted(object sender, ContactsSearchEventArgs e){ //Bind the results to the user interface. ContactsListBox.DataContext = e.Results;}
    7. 7. <ListBox Name="ContactsListBox" ItemsSource="{Binding}" Height="347" Margin="24,0,0,0" > <ListBox.ItemTemplate> <DataTemplate> <TextBlock Name="ContactResults" Text="{Binding Path=DisplayName, Mode=OneWay}" /> </DataTemplate> </ListBox.ItemTemplate></ListBox>
    8. 8. // enumerate the results we got back and get the sourceforeach (Contact contact in e.Results){ foreach (Account account in contact.Accounts) { Debug.WriteLine(contact.DisplayName + ": " + account.Name); }}
    9. 9. Demo 1:Contact Display
    10. 10. cons.SearchAsync("Ro", FilterKind.DisplayName, "Contacts Load");// Find all the contacts with names beginning "Ro"
    11. 11. apps.SearchAsync( new DateTime(2000, 1, 1), new DateTime(2012, 1, 1), "Appointment search");
    12. 12. Creating a Contact
    13. 13. 18
    14. 14. using Microsoft.Phone.Tasks;...SaveContactTask saveContact; //Declare with page scopepublic MainPage(){ saveContact = new SaveContactTask(); saveContact.Completed += new EventHandler <SaveContactResult>(saveContact_Completed);}private void MakeContactButton_Click(object sender, RoutedEventArgs e){ saveContact.FirstName = FirstNameTextBox.Text; saveContact.LastName = LastNameTextBox.Text; saveContact.Show();}
    15. 15. void saveContact_Completed(object sender, SaveContactResult e){ if (e.TaskResult == TaskResult.OK) { MessageBox.Show("Saved OK"); }}
    16. 16. 21
    17. 17. Demo 2:Make a Contact 22
    18. 18. 23
    19. 19. Action Chooser TaskGet addresses, phone numbers and email AddressChooserTask,addresses PhoneNumberChooserTask, EmailAddressChooserTaskSelect a picture from the media store PhotoChooserTaskCapture a picture using the camera CameraCaptureTaskInvite players to a multi-game session GameInviteTask(XBL only)Save email addresses or phone numbers SaveEmailAddressTask, SavePhoneNumberTaskSave ringtones SaveRingtoneTask
    20. 20. Action TaskOpen a web page WebBrowserTaskSearch the Marketplace and find applications MarketplaceSearchTask, MarketPlaceHubTaskShow Marketplace App Details and Review MarketplaceDetailTask,Apps MarketplaceReviewTaskPlace a phone call PhoneCallTaskSend an email EmailComposeTaskSend an SMS message SMSComposeTaskPlay media MediaPlayerTaskStart a search using Bing SearchTaskShow maps and directions from Bing Maps BingMapsTask, BingMapsDirectionsTask
    21. 21. Using the Camera 27
    22. 22. 28
    23. 23. cameraTask = new CameraCaptureTask();cameraTask.Completed += new EventHandler<PhotoResult> (cameraTask_Completed);cameraTask.Show();
    24. 24. void cameraCapture_Completed(object sender, PhotoResult e){ if (e.TaskResult == TaskResult.OK) { photoImage.Source = new BitmapImage( new Uri(e.OriginalFileName)); }}
    25. 25. Demo 3:Take a Picture 31
    26. 26. 32
    27. 27. using Microsoft.Devices;...PhotoCamera camera;...camera = new PhotoCamera();//Set the VideoBrush source to the cameraviewfinderBrush.SetSource(camera);camera.CaptureImageAvailable +=new EventHandler<ContentReadyEventArgs> (camera_CaptureImageAvailable);
    28. 28. <Rectangle Width="320" Height="240" HorizontalAlignment="Left" > <Rectangle.Fill> <VideoBrush x:Name="viewfinderBrush" /> </Rectangle.Fill></Rectangle>
    29. 29. private void PhotoButton_Click(object sender, RoutedEventArgs e){ camera.CaptureImage();}
    30. 30. using Microsoft.Xna.Framework.Media;...void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e){ Deployment.Current.Dispatcher.BeginInvoke(delegate() { string fileName = DateTime.Now.Ticks.ToString() + ".jpg"; MediaLibrary library = new MediaLibrary(); library.SavePictureToCameraRoll(fileName, e.ImageStream); });}
    31. 31. using System.Windows.Media.Imaging;...void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e){ Deployment.Current.Dispatcher.BeginInvoke(delegate() { BitmapImage b = new BitmapImage(); b.CreateOptions = BitmapCreateOptions.None; b.SetSource(e.ImageStream); PictureImage.Source = b; });}
    32. 32. using System.IO;using System.IO.IsolatedStorage;...using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write)) { WriteableBitmap bitmap = new WriteableBitmap(b); bitmap.SaveJpeg(targetStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100); }}
    33. 33. Demo 4:In-AppCamera 39
    34. 34. 40
    35. 35. internal int FunkyColor(int color){ int a = color >> 24; int r = (color & 0x00ff0000) >> 16; int g = (color & 0x0000ff00) >> 8; int b = (color & 0x000000ff); r += redOffset; g += greenOffset; b += blueOffset; return ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF);}
    36. 36. camera = new Microsoft.Devices.PhotoCamera();// Create the destination for the processed imagewb = new WriteableBitmap(640, 480);this.ProcessedImage.Source = wb;// Start the image pump when the camera is readycamera.Initialized += new EventHandler<CameraOperationCompletedEventArgs> (camera_Initialized);
    37. 37. void camera_Initialized(object sender, CameraOperationCompletedEventArgs e){ pumpARGBFrames = true; ARGBFramesThread = new System.Threading.Thread(PumpARGBFrames); ARGBFramesThread.Start();}
    38. 38. int[] ARGBPx = new int[640 * 480];...captureEvent.WaitOne();pauseFramesEvent.WaitOne(); //Thread sync with camera//Copies the current viewfinder frame into a buffercamera.GetPreviewBufferArgb32(ARGBPx);//Conversion to funky coloursfor (int i = 0; i < ARGBPx.Length; i++){ ARGBPx[i] = FunkyColor(ARGBPx[i]);}
    39. 39. private WriteableBitmap wb;...pauseFramesEvent.Reset();Deployment.Current.Dispatcher.BeginInvoke(delegate(){ //Copy to WriteableBitmap ARGBPx.CopyTo(wb.Pixels, 0); wb.Invalidate(); pauseFramesEvent.Set();});
    40. 40. Demo 6:FunkyCamera 46
    41. 41. Using the Microphone
    42. 42. http://msdn.microsoft.com/en-us/library/gg442302.aspx
    43. 43. Using Sensors
    44. 44. using Microsoft.Devices.Sensors;
    45. 45. if (Gyroscope.IsSupported){ // we have a gyro on the phone}
    46. 46. 54
    47. 47. using Microsoft.Devices.Sensors;...Motion motion;...motion = new Motion();motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);motion.CurrentValueChanged += new EventHandler <SensorReadingEventArgs<MotionReading>> (motion_CurrentValueChanged);
    48. 48. // Try to start the Motion API.try{ motion.Start();}catch (Exception){ MessageBox.Show("unable to start the Motion API.");}
    49. 49. private void CurrentValueChanged(MotionReading e){ if (motion.IsDataValid) { // Show the numeric values for attitude. yawTextBlock.Text = "YAW: " + MathHelper.ToDegrees(e.Attitude.Yaw).ToString("0") + "°"; pitchTextBlock.Text = "PITCH: " + MathHelper.ToDegrees(e.Attitude.Pitch).ToString("0") + "°"; rollTextBlock.Text = "ROLL: " + MathHelper.ToDegrees(e.Attitude.Roll).ToString("0") + "°"; }}
    50. 50. Video Content
    51. 51. <MediaElement Name= "MediaPlayback" Source= "myvideo.wmv" AutoPlay="True"/> http://msdn.microsoft.com/en-us/library/ff462087.aspx
    52. 52. <MediaElement Name= "MediaPlayback"Source="http://mschannel9.vo.msecnd.net/o9/mix/09/wmv/key01.wmv"AutoPlay="True"/>
    53. 53. private void pauseButton_Click(object sender, RoutedEventArgs e){ MediaPlayback.Pause();}
    54. 54. http://smf.codeplex.com/releases/view/63434#DownloadId=222617
    55. 55. 63
    56. 56. http://aka.ms/mbl-phone/starthttp://aka.ms/mbl-phone/toolshttp://aka.ms/mbl-phone/mangohttp://aka.ms/mbl-phone/register
    57. 57. Follow me on Twitter or the Puppy gets it @benriga

    ×