Code samples + slide deck available of my “Masters in Microsoft” session on new Windows Phone 8 developer features

This post is made for everyone who was at my session at the “Masters in Microsoft” event at the Avanade office yesterday. Hopefully you enjoyed my session! I got asked for the sample code and slide deck a couple of times after the event during the drinks so therefore I’m uploading them here so everyone can grab a copy if they want it.


I’ve uploaded the slide deck as pdf and the complete visual studio with all the working samples is also included in the same directory on my skydrive:

you can download it here

I’ve also uploaded Jermaine’s slide deck on Windows 8 to the same skydrive folder so you can also have a look at them as well.

If you have any questions regarding Windows Phone or Windows 8 development let me know on twitter @geertvdc or just add the hashtag #wpnl and the Dutch Windows Phone community will help you!

Geert van der Cruijsen

Share on Facebook
Kick It on
Shout it
Post on Twitter

8 days of Windows Phone 8 | Day 8: Wallet and In-App purchases

8 days of windows phone 8  

Welcome to the last day in this series of blog posts on the new features for developers of the Windows Phone 8 platform. Today, the 8th day we’ll talk on our last subject of the series, the wallet functionality and how to use in-app purchases.

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech API
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases



    The wallet application is meant to be a place on your phone where all kinds of apps can store things like deals or other things for example points you can save at gas stations, bars etc. Using the Wallet API you can add or read wallet items from and to your Wallet application.

    The first thing we’ll do in our sample application is add a deal to the Wallet. In this example we’ll build a deal for 1 free beer that can be collected in your favorite bar. Before we start adding code we have to add the Wallet Capability to the WMAppManifest.xml file.

    wallet capability

    After that we’ll add a button to create a new free beer deal in the wallet to our MainPage.xaml

       1: <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

       2:     <Button x:Name="FreeBeerButton" Content="get 1 free beer deal!" Click="FreeBeerButton_Click_1"></Button>

       3: </StackPanel>

    At the click event we’ll add the code to create a new deal in the wallet. We start with creating a new Deal object passing a unique ID to it. on this deal you can set a lot of properties from a name to images and a barcode. In this example i’ve added some of the basic properties but barcodes can be really usefull when you want to be able to use the barcode in your favorite bar for example ;) When we’ve set all the properties we’ll call the SaveAsync method and the Deal will be saved. It’s a common practice to also open the wallet application to let the user know that you’ve saved something to the wallet. There is no special launcher for the Wallet application but you can open an URL starting with wallet:// that will trigger the Wallet to open.

       1: private async void FreeBeerButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     var beerDeal = new Deal("1FREEBEER");

       4:     beerDeal.MerchantName = "MyBar";

       5:     beerDeal.DisplayName = "1 free beer!"; 

       6:     beerDeal.Description = "collect 1 free beer at your favorite bar";

       7:     beerDeal.CustomerName = "Geert";


       9:     beerDeal.ExpirationDate = DateTime.Now.AddDays(1);


      11:     beerDeal.IssuerName = "Your Favorite Bar";

      12:     beerDeal.NavigationUri = new Uri("/mainpage.xaml?deal=freebeer", UriKind.Relative);


      14:     await beerDeal.SaveAsync(); 


      16:     Launcher.LaunchUriAsync(new Uri("wallet://", UriKind.RelativeOrAbsolute));


      18: }

    When we run the app and click the free beer button the wallet will open and our deal is visible. if we click our deal we can see it’s details. if you add a barcode the barcode will be visible here as well. There is also an option to go back to the app. If we would click the open app link the app will open using the NavigationURI property set to the Deal object. You can also mark deals here as used or delete them from your wallet.

    wallet1 wallet2 wallet3 wallet4

    Besides deals you can also add Payment Instruments. These objects are things like the points you can gather by shopping at the same store often so you can use these points to get some rewards. Creating a Payment Instrument works almost the same as a deal except then you use the PaymentInstrument object. The PaymentInstrument object also has property to set an amount which you can increase or decrease later.

    If you want to use the Payment Instrument items from the wallet you’ll have to add an extra capability to the WMAppManifest.xml called the ID_CAP_WALLET_PAYMENTINSTRUMENTS

    The third thing you can add to the Wallet are generic wallet items. this can be like a customer card with a barcode or number which you can use in shops to identify yourself as a returning customer. You can create generic wallet items using the WalletTransactionItem.

    In-app purchases

    A really important feature of Windows Phone 8 is the possibility to use in-app purchases. In Windows Phone 7 you could only do free apps, trial modes and paid apps. In-app purchases really add new scenario’s to make money. for example you can create a free game where you can buy new levels for a certain amount of money. Another example is a sports app where you can buy push notifications for a certain season instead of buying the game once and getting notifications forever. so how do we do this?

    In-app purchases have to be created on the development portal. Log into your developer account at and upload a new application or go to the details of an existing app.


    Click on the products tab and then click “Add in-app product” to create a new product that can be bought in our app.


    First we’ll have to fill in the in-app product properties. This consists of a name, and Identifier. this identifier is important because we’ll need to reference this in our app.

    you can also select Durable or Consumable as the product type. the difference between this is that durable products will be bought once and will be available forever after that. consumable products are bought once and then also used only once.


    We can select a price and press save. after that we’ll also have to add a description for our product


    When adding your description you’ll have to add a title, description text and an image. press save again.

    inapp5 inapp6

    Now we’re ready to submit the in-app product. when we press Submit our product will be saved and can be used in our app after certification.


    So now we have an in-app product we can try to buy it from within our app.

    Let’s add a button again to buy our 30 new levels.

       1: <Button x:Name="BuyLevelsButton" Content="buy 30 more levels!" Click="BuyLevelsButton_Click_1" ></Button>

    At the click event we’ll add code to buy our item. First we’ll need to get a list of all available products for our app. We can get this from the CurrentApp object by calling the LoadListingInformationAsync. since we know there is only 1 product we’ll take a shorcut by selecting the first product but you could select your product by checking the ID here. When we have the product we can call the RequestProductPurchaseAsync method to launch the marketplace and let the user choose if he wants to do this extra purchase. When the user chooses to buy the product or not we go back to our code and check if the product is set to Active. If this is true we’ll have to call the ReportProductFulFillment method to tell the store the app knows the purchase is done and after that we can save a property somewhere that unlocks the new feature in your app.

       1: private async void BuyLevelsButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     var products = await CurrentApp.LoadListingInformationAsync();

       4:     var product1 = products.ProductListings.FirstOrDefault();


       6:     var boughtProduct  = await CurrentApp.RequestProductPurchaseAsync(product1.Value.ProductId, true);


       8:     if (CurrentApp.LicenseInformation.ProductLicenses[product1.Value.ProductId].IsActive)    

       9:     {                

      10:         CurrentApp.ReportProductFulfillment(product1.Value.ProductId);

      11:         var saveBoughtProductstate = true;

      12:     }

      13: }

    Note that we don’t add any extra code or anything in a product. it’s just a boolean that is set to true. so in the example of 30 extra levels you can buy all levels should be in the package, you just disable some in your UI unless the boolean is set to true when the purchase is made.

    I really like the possibilities of the in-app purchases and believe this will make more companies like newspapers to build apps for the Windows Phone platform.

    You can download the sample project here

    That’s all folks. the 8 days of Windows Phone 8 blog series has come to an end. Hopefully you enjoyed reading this series of posts and learned something from it.

    If you missed some new features and would like a post on that topic let me know and i’ll see if i can add some extra posts.

    Geert van der Cruijsen

  • Share on Facebook
    Kick It on
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Day 7: Proximity capabilities

     8 days of windows phone 8

    Welcome back to the blog series 8 days of Windows Phone 8. Today, almost the last post we’ll dive into proximity capabilities also known as bluetooth and nfc. One note to this post is that i couldn’t test the code on the emulator since bluetooth and nfc are both only testable on devices and when i wrote this post i didn’t have access to a phone yet so maybe the examples are not 100% working.

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech API
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases



    When you want to use bluetooth or NFC the first thing you’ll need to do is add the Proximity capability in the WMAppManifest.xml file in the capabilities tab.

    proximity capability

    When we’ve done this we’re ready to start building an app to communicate with another device through Bluetooth. Communicating with Bluetooth works through a client server type of connection. One phone needs to be the server and then another phone can connect to this server and the phones can communicate with each other.

    To set up the server and client we’ll add 2 buttons, 1 to start the server and 1 to start the client.

       1: <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

       2:     <Button x:Name="ServerButton" Click="ServerButton_Click_1" Content="server"></Button>

       3:     <Button x:Name="ClientButton" Click="ClientButton_Click_1" Content="client"></Button>

       4: </StackPanel>

    at the click event of the server button we’ll add the following code to set up a PeerFinder object to listen to events. when another peer connects to our phone a ConnectionRequested event will be handled and we’ll show a MessageBox to confirm the user another device is connected.

       1: private void ServerButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     PeerFinder.Start();

       4:     PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;

       5: }


       7: async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)

       8: {

       9:     MessageBox.Show("Connected");

      10:     _ss = await PeerFinder.ConnectAsync(args.PeerInformation);

      11: }

    To connect to the server we’ll need to implement the client part. Under the click event we’ll add the following code to search for server phones and connect to them if we found one. We’ll use the PeerFinder again to search for other peers. when the FindAllPeers method returns we’ll check if there is an active server by checking the count property and when the count is greater than 0 we’ll connect to this peer and check it’s displayname.

       1: protected async void ClientButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     PeerFinder.Start(); 

       4:     var p = await PeerFinder.FindAllPeersAsync(); 

       5:     if (p.Count > 0) 

       6:     { 

       7:         _ss = await PeerFinder.ConnectAsync(p[0]);

       8:         string phoneName = p[0].DisplayName;

       9:     }

    So now we have 2 phones connected we can send a message from one phone to the other. We’ll add another button to the main page and add code to the click event to send a message to another phone.

       1: private async void SendMessageButton_Click_1(object sender, RoutedEventArgs e)

       2:         {

       3:             if (_ss == null)

       4:                 throw new Exception("Socket not initialized");


       6:             DataWriter dw = new DataWriter(ss.OutputStream);

       7:             dw.WriteString("Hello Windows Phone 8");

       8:             await dw.StoreAsync();

       9:         }

    We’ll use the StreamSocket initialized when we created our connection to send the message.  If the socket isnt initialize we’ll throw an exception but continue otherwise. Create a DataWriter from the StreamSocket OutputStream and use the WriteString method to write a string to the DataWriter. Now we can call the StoreAsync method to actually send the message to the other phone.

    The last thing we need to add is receiving the message on the phone. We’ll connect the PeerFinder StreamSocket and call a new private method called WaitForMessage.

    In this asynchronous method we’ll open a DataReader from the StreamSocket’s inputstream. From this datareader we can first read the length of the message and after that we can read the message itself. Now we’re all done in receiving the message through bluetooth.

       1: async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)

       2: {

       3:     MessageBox.Show("Connected");

       4:     _ss = await PeerFinder.ConnectAsync(args.PeerInformation);

       5:     string message = await WaitForMessage();

       6: }


       8: private async Task<string> WaitForMessage()

       9: {

      10:     DataReader dr = null;

      11:     while (true)

      12:     {

      13:         if (dr == null)

      14:             dr = new DataReader(_ss.InputStream);


      16:         await dr.LoadAsync(4);

      17:         uint messageLen = (uint)dr.ReadInt32();

      18:         await dr.LoadAsync(messageLen);

      19:         return dr.ReadString(messageLen);

      20:     }

      21: }


    The other Proximity capability in Windows Phone is NFC. With NFC it’s possible to read NFC tags or to communicate from phone to phone. In this post we’ll dive deeper in how to connect from one phone to another using NFC. To send and receive messages using NFC we’ll add 2 buttons again to our MainPage.xaml

       1: <Button x:Name="NfcSendButton" Click="NfcSendButton_Click_1"  Content="nfc send"></Button>

       2: <Button x:Name="NfcReceiveButton" Click="NfcReceiveButton_Click_1"   Content="nfc receive"></Button>

    At the click event of the Send button we’ll add the following code. We’ll create an instance of a ProximityDevice and the only thing we’ll have to do is call the PublishMessage method on this ProximityDevice. In this example we’re sending a string but it’s also possible to send binary data.

       1: private void NfcSendButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     ProximityDevice pd = ProximityDevice.GetDefault();

       4:     if (pd != null) 

       5:     { 

       6:         pd.PublishMessage("8days", "Hello World!");

       7:     }

       8: }

    After sending the message the last thing we’ll do today is receiving the message. Add the following code to the click event of the receive button. In the click eventhandler we’ll get an instance of the ProximityDevice and subscribe for messages and that’s all. Now when a message is received the NfcReceive method is called and we can just read the message.

       1: private void NfcReceiveButton_Click_1(object sender, RoutedEventArgs e)

       2: {

       3:     ProximityDevice pd = ProximityDevice.GetDefault();


       5:     if (pd != null)

       6:     {

       7:         long Id = pd.SubscribeForMessage("8days", NfcReceive);

       8:     }

       9: }


      11: private void NfcReceive(ProximityDevice sender, ProximityMessage message)

      12: {

      13:     var m = message.DataAsString;

      14: }

    As you can see implementing NFC is really really easy in Windows Phone 8 and i can’t wait for people to use this in their apps. I think all announced Windows Phone 8 devices have NFC capabilities so it can become really big on the platform.


    Tomorrow the last day of the series where we talk on the Wallet features and how to implement in app purchases.

    You can download the sample code here

    Geert van der Cruijsen

  • Share on Facebook
    Kick It on
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Days 6: Speech API

     8 days of windows phone 8

    Welcome again to the blog series called 8 days of Windows Phone 8 celebrating the release of Windows Phone 8 and the Windows Phone 8 SDK. Today, 5 days after the release it’s time for the 6th post in this series on the Speech APIs. Speech on Windows Phone 8 consists of 3 key aspects: Text to Speech, Speech to Text and Voice commands. In this post we’ll demo all 3.

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases


    Text to speech

    The first of the 3 speech APIs we’ll discuss is the Text to Speech API. In Windows Phone 7 you’ll had to use the Bing speech API if you wanted to translate a written sentence into sound. In Windows Phone 8 this API is part of the Windows Phone API although under the hood it will probably still use Bing servers.

    Let’s create a new project and the first thing we need to do is add the Speech Recognition capability in WMAppManifest.xml file in the Capabilities tab in Visual studio 2012.


    After that we’ll add a button to our Mainpage and add the following 2 lines of code to the click event of the button

       1: private void SayHelloButton_Click(object sender, RoutedEventArgs e)

       2: {

       3:     SpeechSynthesizer ss = new SpeechSynthesizer(); 

       4:     ss.SpeakTextAsync("8 days of windows phone 8, day 6");

       5: }

    Run the app and indeed you’ll only need 2 lines of code to get text to speech working. Great! Note that the SpeakTextAsync method of the SpeechSynthesizer is async. First API checked on to the next one you would think.. well no there is more! You can also change the language and the voice of the clip. Let’s add some code to alter the voice and language to a German Male voice:

       1: private void SayGermanButton_Click_(object sender, RoutedEventArgs e)

       2: {

       3:     SpeechSynthesizer ss = new SpeechSynthesizer();

       4:     VoiceInformation vi = InstalledVoices.All.Where(v => v.Language == "de-DE" && v.Gender == VoiceGender.Male).FirstOrDefault();

       5:     ss.SetVoice(vi);

       6:     ss.SpeakTextAsync("8 Tage von Windows Phone 8, Tag 6");

       7: }

    It’s only 2 lines extra to set the language and gender (yes could be 1 i know ;) ) and the rest stays the same. we press the button again (in the sample project i’ve added an extra button to show both scenarios). Now run the project and we’ll have a german talking voice. Now it’s time to go to the next topic, speech to text.

    Speech to text

    the text to speech we discussed in the previous paragraph is pretty cool but converting speech to text is even more amazing and about as easy to implement. Before we start we’ll have to add the microphone capability so we can capture the sounds from the microphone. Just check the box in the capabilities tab of the WMAppManifest.xml file.

  • capabilities microphone

    Now that the capability is added we can start adding code to add the speech recognition. We’ll add a button to ask how you are doing to the mainpage.

       1: <Button x:Name="AskStatusButton" Content="how are you doing?" Click="AskStatusButton_Click"></Button>

       2: <TextBlock x:Name="StatusText"></TextBlock>

       3: <TextBlock x:Name="ConfidenceText"></TextBlock>

    in the code behind we’ll add code to the click event of this button and the results of the speech recognition we’ll be adding to the StatusText textblock. We’ll also add an extra textblock to display the confidence level of the speech recognition.

    In the click event we start with adding an SpeechRecognizerUI object. On this SpeechRecognizerUI object we’ll be settings some properties, The ListenText property is the text that is shown as the title in the speech box as shown on the image below. the next property is the ExampleText. here you can add a sample answer the user could answer. After that we set the ReadoutEnabled property to true so the Phone will speak your text back to you. The last property we’ll add is the ShowConfirmation that shows the spoken line of text as a text on the screen.

       1: private async void AskStatusButton_Click(object sender, RoutedEventArgs e)

       2: {

       3:     SpeechRecognizerUI sr = new SpeechRecognizerUI();

       4:     sr.Settings.ListenText = "How are you doing?";

       5:     sr.Settings.ExampleText = "I'm doing fine"; 

       6:     sr.Settings.ReadoutEnabled = true; 

       7:     sr.Settings.ShowConfirmation = true; 

       8:     SpeechRecognitionUIResult result = await sr.RecognizeWithUIAsync();

       9:     if (result.ResultStatus == SpeechRecognitionUIStatus.Succeeded) 

      10:     {

      11:         StatusText.Text = result.RecognitionResult.Text;

      12:         ConfidenceText.Text = result.RecognitionResult.TextConfidence.ToString();

      13:     }


      15: }

    When we’ve set all these properties we can call the RecognizeWithUIAsync method to trigger the voice recognition. Note that on the first time this is accessed by the user the user has to accept that the voice clips will be send to the Microsoft Servers for processing. when they accept the speech recognition will start.

    speech1 speech2 speech3 speech4

    When the speech recognition finishes you can check the result in code. The result that comes back from the RecognizeWithUIAsync has a text property and also a confidence level to check if the result is usable or not. In the sample project we add these results to the 2 textboxes we’ve added to the mainpage.

    In some use cases you just want the user to choose between some options instead of just free text. this is really easy to implement with the SpeechRecognizerUI class. We’ll be adding another button and 2 more textboxes on the Main page to ask the user which day the current day of the week is.

       1: <Button x:Name="AskDayButton" Content="which day is it?" Click="AskDayButton_Click"></Button>

       2: <TextBlock x:Name="DayText"></TextBlock>

       3: <TextBlock x:Name="DayConfidenceText"></TextBlock>

    After that we’ll add code to the click event of the new button with almost the same code as before with some extra additions. 

       1: private async void AskDayButton_Click(object sender, RoutedEventArgs e)

       2: {

       3:     SpeechRecognizerUI sr = new SpeechRecognizerUI();

       4:     sr.Settings.ListenText = "Which day is it today?";

       5:     sr.Settings.ExampleText = "Friday";

       6:     sr.Settings.ReadoutEnabled = true;

       7:     sr.Settings.ShowConfirmation = true;


       9:     sr.Recognizer.Grammars.AddGrammarFromList("answer", new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" });


      11:     SpeechRecognitionUIResult result = await sr.RecognizeWithUIAsync();

      12:     if (result.ResultStatus == SpeechRecognitionUIStatus.Succeeded)

      13:     {

      14:         DayText.Text = result.RecognitionResult.Text;

      15:         DayConfidenceText.Text = result.RecognitionResult.TextConfidence.ToString();

      16:     }

      17: }

    The only extra line we’ll add is a list of available answers and the speech recognizer will only match the spoken answer to one of these answers. In our example i’ve added the names of the days of the week.

    speech5 speech6 speech7

    When you run the app the app will only accept existing days of the week.

    Voice commands

    The last subject of today is voice commands. With voice commands you can start your app with a specific task or execute a task when you are already in your app. Voice commands always consist of 3 parts. The App name so the operating system knows which app to send the command to. the second part is the the command name and the third part is a Phrase which is a sort of parameter you can add to your command.

    To enable voice commands you’ll have to add an xml file which contains the voice commands. To add this VCD file right click your project in Visual Studio and select Add new item and select the Voice Command Definition from the list.

    vcd file

    By default you’ll get an already filled in VCD file with some example commands and phrases. We’ll be changing this to add a command to start the app by asking what day it is today, tomorrow or yesterday.

    The first thing you’ll have to add to a VCD file is the CommandPrefix. this is the word the operating system will use to find your app.. after that we’ll add a Command. this command needs a ListenFor element where you tell the operating system which text to listen for. you can also add a phrase to this command like i did with the {day}. this phrase with it’s options should also be added to the VCD file.

       1: <?xml version="1.0" encoding="utf-8"?>


       3: <VoiceCommands xmlns="">

       4:   <CommandSet xml:lang="en-US">

       5:     <CommandPrefix>8 days</CommandPrefix>

       6:     <Example>what day is it today?</Example>

       7:     <Command Name="DayToday">

       8:       <Example>What day is it?</Example>

       9:       <ListenFor>What day is it {day}</ListenFor>

      10:       <Feedback>Checking the day</Feedback>

      11:       <Navigate Target="/MainPage.xaml"/>

      12:     </Command>


      14:     <PhraseList Label="day">

      15:       <Item> today </Item>

      16:       <Item> tomorrow </Item>

      17:       <Item> yesterday </Item>

      18:     </PhraseList>


      20:   </CommandSet>

      21: </VoiceCommands>


    When we’ve added the VCD file we can register our VCD to the operating system. You’ll only have to do this once when your app runs for the first time but for now i’ll just add it to the constructor of our mainpage.

       1: public MainPage()

       2: {

       3:     InitializeComponent();


       5:     InitializeVoiceCommands();

       6: }


       8: private async System.Threading.Tasks.Task InitializeVoiceCommands()

       9: {

      10:     await VoiceCommandService.InstallCommandSetsFromFileAsync(new Uri("ms-appx:///VoiceCommandDefinition1.xml"));

      11: }

    That’s all we need to do. to start our app using our voice. You can trigger the voice recognition by holding the windows button for a few seconds. You’ll now see the small “Listening” popup window. if you say “What can i say” or press the question mark you’ll go to a new page with the explanation on what commands are available. The first page will describe the commands that are build in into the system. if you slide to the right you’ll get an overview of all apps that support voice commands. Our app is listed here. When you click the app you’ll get a list of available commands for this app.

    speech8  speech9speech10 speech11

    When we hold the windows button now and say “8 days, What day is it tomorrow?” our app will start and will open the Mainpage.xaml


    The voice command is sent to the MainPage.xaml on the querystring. overriding the OnNaigatedTo event we can check which voice command was used and also which phrase was used.

       1: protected override void OnNavigatedTo(NavigationEventArgs e)

       2: {

       3:     base.OnNavigatedTo(e);


       5:     if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New)

       6:     {

       7:         if (NavigationContext.QueryString.ContainsKey("voiceCommandName"))

       8:         {

       9:             string command = NavigationContext.QueryString["voiceCommandName"];


      11:         }

      12:     }

      13: }

    The voice command and phrase are both added as seperate url parameters so if we run the app again and trigger it by asking what day it is tomorrow we can see the following results when we attach the debugger:

    onnavigated to

    As you can see there is a parameter “day” which you can use in a switch statement for example to call the appropriate method.

    you can download the sample project here:

    That’s all for today on the Speech API’s. Hopefully you’ll be back tomorrow to read my post on the Proximity APIs.

    Geert van der Cruijsen

    Share on Facebook
    Kick It on
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Day 5: .net 4.5 & C# 5.0

     8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 5th day of this series we’ll talk about the new features in the .net framework 4.5 and the C# 5.0 language that can help you build great Windows Phone apps. The main features we’ll handle in this post are the async and await keywords and the DataContractJsonSerializer

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases



    .net framework 4.5 & C# 5.0

    With Windows 8 we’re also upgrading our applictions from silverlight to the .net 4.5 framework and the C# 5.0 language. This does give Windows Phone developers some new features that are not actually new features in the SDK but are really useful for you as a developer of mobile applications. One of these new features are the async and await keywords. This makes building asynchronous applications so much easier and your UI more responsive. The other thing i want to elaborate on today is the use of the DataContractJsonSerializer. This class helps you to serialize or deserialize json strings to or from objects. Really useful when you’re connecting to services on the web.

    Unfortunately not all APIs in the SDK are rewritten to make use of these async and await keywords so you can’t use them to do calls from the web. WebClient and HttpWebRequest do not make use of these features so hopefully sometime we can use HttpClient like we can in Windows 8.

    My ideal situation in creating a demo for this post was combining the async and await keywords together with the json serializer. so if we can’t use it when getting the file from the web lets just use a local file instead. local file access APIs are written using the Task, async and await keywords. so lets get started and build a very very basic To Do list app to check the

    Create a new Windows Phone 8 project and add a ToDo class to store our things we need to so. It’s just a property bag with a Title, Date and some text. To save this file as a json file later we’ll add some attributes so the DataContractJsonSerializer knows how this object can be serialized to a json file. To do this add the [DataContract] attribute to the ToDo class and add the [DataMember] attribute to each property you want to be serialized to json. By default the Serializer will give the properties in the json file the same name as the properties in your class. If you want to have different names you can change this in the DataMember attribute as shown for the Content property which we changed to the word “Text”

       1: [DataContract]

       2: public class ToDo

       3: {   

       4:     [DataMember]

       5:     public string Title { get; set; }


       7:     [DataMember]

       8:     public DateTime Date { get; set; }


      10:     [DataMember(Name="Text")]

      11:     public string Content { get; set; }

      12: }

    So we’ve created a simple container for our objects lets create a business service called ToDoService to save a list of To Do items and get them back again from a file stored in the Local Folder. Local folder is the root of your applications data store which was called the Isolated storage in Windows Phone 7.

    First we’ll add a method to our ToDoService to save a list of To Do items.

  •    1: public async Task<string> SaveToDos()

       2: {

       3:     List<ToDo> todos = new List<ToDo>();

       4:     todos.Add(new ToDo(){Title="todo 1", Date = DateTime.Now, Content="finish this series of blogposts"});

       5:     todos.Add(new ToDo(){Title="todo 2", Date = DateTime.Now, Content="Pick up milk from the store"});

       6:     todos.Add(new ToDo(){Title="todo 3", Date = DateTime.Now, Content="Wash my car"});


       8:     var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;


      10:     DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<ToDo>));

      11:     MemoryStream ms = new MemoryStream();

      12:     dcjs.WriteObject(ms,todos);

      13:     string json = Encoding.UTF8.GetString(ms.ToArray(),0,(int)ms.Length);



      16:     StorageFile todoFile = await localFolder.CreateFileAsync("todos.json",CreationCollisionOption.ReplaceExisting);

      17:     using (var f = await todoFile.OpenStreamForWriteAsync())

      18:     {

      19:         await f.WriteAsync(ms.ToArray(),0,(int)ms.Length);

      20:         f.Close();

      21:     }


      23:     return json;

      24: }

    Please note the async keyword before the return type of this method. by adding this, this method can be called asynchronous and it will always return a Task containing your return type. In the method we first add a few ToDo items to a list. after that we create a new DataContractJsonSerializer and in the constructor we add the type of object it should serialize. We then use the DataContractJsonSerializer to serialize our list of ToDo items to a json string which will be returned at the end of the method.

    When we have this json string we’ll create a new file in the local folder by calling the CreateFileAsync method. please note the await keyword before this method which means that the code below this line should be waiting until this asynchronous call is finished. When we have the local file we’ll just write the json string to this file and close the stream.

    So now the ToDo items are saved in the local file, lets read them back and show them on the screen. We’ll add a new method to our ToDoService called GetToDos() which will read the json file and will deserialize it back to a list of ToDo items.

       1: public async Task<List<ToDo>> GetToDos()

       2: {

       3:     var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

       4:     StorageFile todoFile = await localFolder.GetFileAsync("todos.json");


       6:     DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<ToDo>));

       7:     var stream = await todoFile.OpenStreamForReadAsync();

       8:     var todos = dcjs.ReadObject(stream) as List<ToDo>;


      10:     return todos;


      12: }

    We’ll start again by getting a reference to the local folder and the json file in the local folder. When we have this StorageFile object we can now create a new DataContractJsonSerializer again. Now we open a stream from our StorageFile and pass it to the DataContractJsonSerializer to change it back to a List of ToDo items. We’re all done.

    To finish up the demo application we’ll add a textbox to the mainpage where we can display our json string and we’ll also add an ItemsControl to display the To Do items.

       1: <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

       2:     <ScrollViewer>

       3:         <StackPanel>

       4:             <TextBlock x:Name="JsonText" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       5:             <ItemsControl x:Name="TodoList" ItemTemplate="{StaticResource TodoItemTemplate}" Margin="0,12,0,0"></ItemsControl>

       6:         </StackPanel>

       7:     </ScrollViewer>

       8: </StackPanel>

    In our code behind we’ll hook everything up to write and read the data and show it on the page.

       1: public async void SaveAndGetTodos()

       2: {

       3:     ToDoService ts = new ToDoService();

       4:     string json = await ts.SaveToDos();


       6:     List<ToDo> todos = await ts.GetToDos();


       8:     JsonText.Text = json;

       9:     TodoList.ItemsSource = todos;

      10: }

    If we now run our application we’ll see the json string that is created and also the list of To Do items in the itemscontrol.


    you can download the demo project here:

    Hopefully you enjoyed reading this post or learned some usefull features of the async and await keywords and the DataContractJsonSerializer. More tomorrow on one of the coolest new things in the SDK: the Speech APIs

    Geert van der Cruijsen

    Share on Facebook
    Kick It on
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Day 4: New Screen Resolutions

     8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 4th day of this series we’ll dive into the new screen resolutions of Windows Phone 8 and what you should do to support these as a Windows Phone developer.

  • Day 1: SDK Overview
  • Day 2: Live tiles and Lock screen
  • Day 3: Emulator & Simulation dashboard  
  • Day 4: New screen resolutions
  • Day 5: .net 4.5 & C# 5.0
  • Day 6: Speech
  • Day 7: Proximity capabilities
  • Day 8: Wallet and In-App purchases



    Available Screen resolutions

    3 screen resolutions are supported in Windows Phone 8: WVGA, WXGA and 720p.

      Resolution Ratio
    WVGA 480*800 15:9
    WXGA 768*1280 15:9
    720P 720*1280 16:9

    The most important thing to notice is there are 2 different screen ratio’s. 15:9 and 16:9. If you look at the picture below that is a representation of the 3 resolutions the WVGA (480*800) and the WXGA (768*1280) share the same Ratio so apps build for WVGA can be scaled to WXGA or the other way around. the 720P resolution however uses a 16:9 ratio that is higher so you have to make sure your UI layout is capable of using this longer screen estate.

    wp8 resolutions

    So what should you do to support all these resolutions? The first thing is all the assets Tile image etc should be used in the largest sizes. The OS will resize them to the right size for you. In your app however you should create a flexible UI that will scale certain UI elements like list boxes to change depending if the screen is longer as in the 720p resolution or shorter as in the other 2 resolutions. Also something to keep in mind is that WXGA is 1.6x the resolution of WVGA the canvas is still 480*800. all UI elements will be scaled to 160%. You don’t have to change your UI for WXGA compared to WVGA except for images. You can check for the current device resolution in code.

    To check the current resolution in code you can use the properties in the Application.Current.Host object. In the example project I’ll print these properties on the screen so you can see the actual values in the screenshots below. We’ll also use these values to select appropriate images for the resolution.

    First we’ll add some text fields to the main page XAML together with an image. In the code behind we’ll set these text boxes to the actual screen height/width/scale and resolution name properties.

       1: <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

       2:     <StackPanel Orientation="Horizontal">

       3:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Height</TextBlock>

       4:         <TextBlock x:Name="TextHeight" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       5:     </StackPanel>

       6:     <StackPanel Orientation="Horizontal">

       7:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Width</TextBlock>

       8:         <TextBlock x:Name="TextWidth" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

       9:     </StackPanel>

      10:     <StackPanel Orientation="Horizontal">

      11:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Scale</TextBlock>

      12:         <TextBlock x:Name="TextScale" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

      13:     </StackPanel>

      14:     <StackPanel Orientation="Horizontal">

      15:         <TextBlock Style="{StaticResource PhoneTextNormalStyle}">Resolution</TextBlock>

      16:         <TextBlock x:Name="TextResolution" Style="{StaticResource PhoneTextNormalStyle}"></TextBlock>

      17:     </StackPanel>

      18:     <Image Height="100" x:Name="ScaledImage"></Image>

      19: </StackPanel>

       1: TextHeight.Text = Application.Current.Host.Content.ActualHeight.ToString();

       2: TextWidth.Text = Application.Current.Host.Content.ActualWidth.ToString();

       3: TextScale.Text = Application.Current.Host.Content.ScaleFactor.ToString();


       5: //use the scale to check which resolution you're using

       6: switch (Application.Current.Host.Content.ScaleFactor)

       7: {

       8:     case 100:

       9:         ScaledImage.Source = new BitmapImage(new Uri("Assets/wvga.png", UriKind.Relative));

      10:         TextResolution.Text = "WVGA";

      11:         break;

      12:     case 150:

      13:         ScaledImage.Source = new BitmapImage(new Uri("Assets/720p.png", UriKind.Relative));

      14:         TextResolution.Text = "720P";

      15:         break;

      16:     case 160:

      17:         ScaledImage.Source = new BitmapImage(new Uri("Assets/wxga.png", UriKind.Relative));

      18:         TextResolution.Text = "WXGA";

      19:         break;

      20: }


    The 3 images: wvga, wxga and 720p are images scaled to the correct size. the WVGA image is 432*100 (the same size as the image width and height in the XAML). the 720p and WXGA are both larger the 720p emulator is 1.5x the size of the WVGA image and the WXGA image is 1.6x the size of the WVGA image. this image is chosen dynamically by the scale property as shown in the code above.

    used images: (text font size is the same on all images to give you an idea of the image quality. click the image to see the actual size)




    results in the emulators for all 3 resolutions:

    resolution wvga resolution 720p

    resolution wxga 


  • So now we know how to handle images in your UI. the last part you need to know is that apps on the 720p resolutions have a higher height compared to the WVGA and WXGA resolution (as you can see in the screenshots above). If you fix your design on 800 pixels high you’ll have an empty piece of screen on the bottom that is not used by your app. It’s better to design your app with certain parts with dynamic heights of your page like a listbox, map control or scrollviewer so they will fill up the screen with just a bit longer list, map etc.

    Hopefully this gives you an idea on how to build apps supporting all resolutions.

    You can download the sample project here:

    Thanks for reading my 4th post in this series of 8 about the new features in Windows Phone 8. Tomorrow a post on some new features in the .net framework 4.5 and the C# 5.0 language which can be important for you as a Windows Phone developer.

    Geert van der Cruijsen

    Share on Facebook
    Kick It on
    Shout it
    Post on Twitter