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 dev.windowsphone.com 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 DotNetKicks.com
    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 DotNetKicks.com
    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="http://schemas.microsoft.com/voicecommands/1.0">

       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: http://sdrv.ms/QSJ2yx

    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 DotNetKicks.com
    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: http://sdrv.ms/QSJ2yx

    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 DotNetKicks.com
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Day 3: Emulator & Simulation Dashboard

    8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 3rd day of this series we’ll dive into the new Emulator and the Simulation Dashboard in Visual Studio 2012.

  • 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



    Windows Phone Emulator

    The Windows Phone 8 emulator has changed a lot from the Windows Phone 7 emulator. The new emulator is actually a Hyper-V virtual machine so it feels like an actual phone. When starting the Windows Phone 7 emulator you only had a your app, internet explorer and the settings app available for testing. When starting the Windows Phone 8 emulator you’ll see all the apps you would expect when you buy a Windows Phone. From the dialer to the people hub everything is there in the emulator.

    The reason the new emulator is running in Hyper-V is also the reason why you can only develop for Windows Phone on Windows 8 Pro or higher. You’ll also need a processor that supports Second Level Address Translation (SLAT). This should be available on machines running an I3/I5/I7 processor from intel (my old dual core intel laptop wouldn’t run the emulator because of missing SLAT).

    If you don’t have SLAT you can still develop apps in Visual studio and compile them you’ll only not be able to run the emulator.

    When you open a new Windows Phone project in Visual studio you’ll see several options when choosing an emulator. You can choose to test on a connected device like you could in Windows Phone 7 and there are a bunch of emulators.

    From the 4 emulators you can choose the WVGA, WXGA and 720P these are emulators which run in different resolutions. on the lowest resolution WVGA there’s an extra emulator that runs on 512MB internal memory. The others run on 1024MB. This 512MB emulator is the Windows Phone 8 equivalent of the 256MB Windows Phone 7 emulator which has some restrictions and will not run every app available in the store. Currently the only phone that is announced with 512MB is the HTC 8S. All other phones by HTC, Nokia and Samsung have 1024MB.


    When we press F5 and build and deploy our app the emulator boots up and will automatically launch your app. Booting the emulator will take a bit longer than it did on Windows Phone 7 but it’s understandable since it’s a complete working phone now instead of only your app running in a empty shell.

    wp8 emulator theme settings accent colors wp8

    When the emulator is started you can do everything you can do on a Windows Phone 8 device. you can select the theme color and language like you could on Windows Phone 7 and you can also check all build in apps like the market place, the people hub or the office hub. Great for inspiration when designing and developing your apps since These build-in apps implement the Microsoft Design Language and Windows Phone grid really well.

    There is also an option to open aditional tools like you could on Windows Phone 7 by pressing the arrow key on the bottom of the menu bar next to the emulator. By default it will open the first tab where you can test the accelerometer. This works exactly the same as was the case for Windows Phone 7. you can move the phone around by clicking and dragging the emulator image to see the result in the emulator. You can also change the orientation or play a shake movement.


    the 2nd tab is the location tab. Again nothing changed here from Windows Phone 7. you can select a location on the map to see it change in the emulator immediately or record several locations and play it back with set intervals between the locations to emulate a moving phone.


    The third tab is the screenshot tab. You can take screenshots here of apps running on the emulator. For Windows Phone 7 developers again nothing else new here. On a side note, if you are testing on your device you can also take screenshots by holding the power button together with the start button.


    The last tab in the additional tools menu is the Network tab. On this tab you can see the which virtual network adapter the emulator is using.


    Simulation Dashboard

    The emulator gives you lots of features to test your application. You can test most test scenarios like test with multiple accent colors, dark/light theme. Test multiple languages and cultures etc. Some use cases however were really hard to test on Windows Phone 7. You had to have a device to test cases like what would happen when your phone goes on the lock screen or what happens on a slow data connection. Some of those cases like a slow data connection are still really hard to test in a consistent way even if you have a device. Luckily Microsoft had the same idea so they came up with a solution for these use cases called the Simulation Dashboard in Visual Studio 2012.

    You can find the Simulation dashboard in the tools menu of Visual Studio.


    When you open the Simulation Dashboard you’ll see a new screen on the right where you can set some features of the emulator (don’t know why they didn’t add the simulation dashboard as a to the additional tools of the emulator, would be logical in my opinion)


    The first option is to change your network connection speed to 2G/3G/4G, Wi-Fi or no network. you can also switch the signal strength from good to poor. This gives you a lot of options to see what happens with your app when a user uses your app on a slow connection so you can see if you should improve your app to support slow connection scenarios.

    The next option is to lock the screen of your emulator. really usefull when testing the new lock screen features as described in yesterdays post. This feature can also be useful when building and testing apps that should be able to run under the lockscreen.

    The last scenario is to trigger a reminder. this was also a pain to test before but now it’s just 1 press of a button and a reminder will pop up on your emulator. fun fact: if you press the snooze button another reminder WILL pop up again after the set time ;)

    That’s all i can tell you about the new features available in the Windows Phone 8 emulator and Simulation Dashboard. I think these features really add more value and make it easier for developers to build and test their applications for Windows Phone 8.

    If you have any feedback on this post or this blog serie let me know on twitter or a comment below this post. Tomorrow we’ll discuss what you should do to support all screen resolutions that are available in Windows Phone 8.

    Geert van der Cruijsen

  • Share on Facebook
    Kick It on DotNetKicks.com
    Shout it
    Post on Twitter

    8 days of Windows Phone 8 | Day 2: Live tiles & Lock screen

    8 days of windows phone 8

    Welcome back to my series of blog posts called 8 days of Windows Phone 8. Today, the 2nd day of this series we’ll dive into the new possibilities of Windows Phone 8 live tiles and the lock screen.

    • 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 


      Live tiles

      If you are familiar with developing for Windows Phone 7 you already know about live tiles. They are one if the unique features of Windows Phone that everyone loves. In Windows Phone 8 Microsoft added more possibilities to create live tiles and also made them more flexible for the end users to really personalize their phone.

      One of the main changes is that live tiles now can be set by any user to 3 different sizes. Small, medium and wide. There are also 3 different templates to create live tiles that show information on different ways: the Flip template, the Cycle template and the Iconic template.

      Sizes used for these templates are:

      Flip Cycle Iconic
      Small 159 * 159px 159 * 159px 110 * 110px
      Medium 336 * 336px 336 * 336px 202 * 202px
      Wide 691 * 336px 691 * 336px -

      You might expect that there would be even more resolutions for the images because of the new resolutions that are supported in Windows Phone 8 but this is not the case. The OS will scale the images for you so you only have to supply them once.

      Flip template

      In Windows Phone 7 it was possible to create tiles and set certain properties on them like a title, count, a back ground image and a text located on the back of the tile. In Windows Phone 8 this is still possible but Microsoft created 2 more tile templates to create live tiles. The template that was used in Windows Phone 7 is now called the Flip Template because it has data on it’s back and will flip at random intervals showing this data. The other templates are called the Iconic template and the Cycle template.

      So lets start looking at some code. At the end of the post you can download all the example code in 1 project to set the different kinds of tiles. Let’s create a Flip tile first:

      We start with a new empty project and add a button to set our flip template. Lets add a click event and place our tile creation code there to make it as easy as possible. In the click event we’ll start adding the code for adding the live tile


       1: private void FlipButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
       5:     FlipTileData fliptile = new FlipTileData();
       6:     fliptile.Title = "WP8";
       7:     fliptile.Count = 9;
       8:     fliptile.BackTitle = "day 2";
       10:     fliptile.BackContent = "back medium";
       11:     fliptile.WideBackContent = "back of the wide tile";
       13:     fliptile.SmallBackgroundImage = new Uri("Assets/159.png",UriKind.Relative);
       14:     fliptile.BackgroundImage = new Uri("Assets/336.png", UriKind.Relative);
       15:     fliptile.WideBackgroundImage = new Uri("Assets/wide.png", UriKind.Relative);
       17:     tile.Update(fliptile);
       18: }

      First of you can get the current active tile by querying the ShellTile class. After that we’ll be creating a new FlipTileData object where we can set all the properties of the new tile. We’ll set the title, count and other properties. Some properties are only for the tile in small mode, some are only used in medium or wide mode and some are used in all modes like the count. We’re adding 3 different images for the 3 sizes of the tile. When we finished setting the properties on the tile we can call the update method on our tile object and pass the FlipTileData to it to set the new tile.

      You can set the following properties on the flip tile:

      Title The title is shown on the bottom left of the front of the tile. it will be shown on the medium and wide tiles.
      Count The count is the number in the black circle on the top right of every tile. The count is shown at all tile sizes.
      BackgroundImage The background image is the image shown on the background of the front of the tile at medium size
      BackBackgroundImage To set the background of the back of the tile use the BackBackgroundImage
      BackContent BackContent is the text shown on the back of a tile at medium size
      BackTitle Title shown on bottom left of the back of a tile on medium and wide size
      SmallBackgroundImage The background of the tile at small size.
      WideBackgroundImage The background of the tile ad wide size
      WideBackBackgroundImage The background of the back of the tile at wide size
      WideBackContent Text shown on the top left of the back of a tile at wide size

      The result will look something like this:

      Small: (note small tile doesn’t flip)



      medium medium example back


      wide example  wide example back

      If you were used to creating live tiles in WP7 there aren’t that much changes as you can see. All that is different are the small and wide sizes of the tile.

      Iconic template

      The iconic template is a new template that is available in Windows Phone 8 and i think this is a really good addition to the Windows Phone SDK. Lots of apps use tiles with a white icon and a transparent background so it looks like the native Windows Phone apps. However lots of people have trouble sizing the icon and the count in the black circle doesn’t look as good as the build in apps like mail or the message hub. To make this easier for everyone Microsoft created the Iconic tile template and it works almost similar to the FlipTile except for we’re using a IconicTileData object instead of the FlipTileData. I think the Iconic tiles will be used a lot on Windows Phone 8.

       1: private void IconicButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
       5:     IconicTileData icontile = new IconicTileData();
       6:     icontile.Title = "WP8";
       7:     icontile.Count = 12;
       9:     icontile.IconImage = new Uri("Assets/202.png", UriKind.Relative);
       10:     icontile.SmallIconImage = new Uri("Assets/110.png", UriKind.Relative);
       12:     icontile.WideContent1 = "8 days of windows phone 8";
       13:     icontile.WideContent2 = "day 2";
       14:     icontile.WideContent3 = "Live tiles and lock screen";
       16:     ShellTile.Create(new Uri("/MainPage.xaml",UriKind.Relative), icontile, true);
       17: }

      As you can see creating the tile is done the same way as the as the first tile we created except for using the IconicTileData.

      The properties in the IconicTileData are a bit different. one key aspect are the images you can add to the Iconic tiles. They are set to different sizes compared to the other tile templates because they only use part of the tile. In the current beta build i’ve used to create this blogpost the images don’t seem to work that well but my guess this will be finished in the final SDK build.

      Another thing that is different is the last line of generating the live tile. The default live tile is made by a FlipTileData object and you can’t update an existing tile to another template so we’re creating a new tile for the Iconic tile.

      Small: (seems to be a bug in the 8.0 build of the sdk where the count falls of the edge of the tile. Don’t know if this only happens in the emulator or also on actual devices since i haven’t tested it on a device yet because i don’t have a device.)




      Wide: (also the rendering of this seems to be a bit off since there should be a margin below the icon that doesn’t seem to be here right now in this build of the SDK)


      The wide template also has 3 lines of text you can add to the wide tile. because of this this template is really versatile and probably one of the reasons this template will be used a lot. A complete list of the IconTileData properties is:

      Title Title shown on bottom left of the tile in medium and wide size
      Count Count shown on the right of the icon image at all sizes
      BackgroundColor Set the background of the tile. if not set it will use the phone accent color
      IconImage Image used in the medium tile size
      SmallIconImage Image used in the small and wide (bottom right) tile size
      WideContent1 Line 1 in the largest font on the wide tile size
      WideContent2 Line 2 of text on the wide tile size
      WideContent2 Line 3 of text on the wide tile size

      Cycle template

      The Iconic tile adds a lot of new possibilities for the live tiles that developers tried to achieve on Windows Phone 7. One example of Windows Phone 7 tiles that lots of people liked was the photo tile where there is a set of images that get rotated in turns on the tile. On Windows Phone 7 there was no way to recreate this as a developer but now with Windows Phone 8 there is a possibility using the Cycle Template.

      Creating a cycle live tile is done the same way as creating the other 2 templates so lets get started and implement the code under the 3rd button in our example app to create a Cycle tile.

       1: private void CycleButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     CycleTileData cycleicon = new CycleTileData();
       4:     cycleicon.Title = "WP8";
       5:     cycleicon.Count = 5;
       7:     cycleicon.SmallBackgroundImage = new Uri("Assets/159.png", UriKind.Relative);
       9:     List<Uri> images = new List<Uri>();
       10:     images.Add(new Uri("Assets/cycle1.png", UriKind.Relative));
       11:     images.Add(new Uri("Assets/cycle2.png", UriKind.Relative));
       12:     images.Add(new Uri("Assets/cycle3.png", UriKind.Relative));
       13:     cycleicon.CycleImages = images;
       15:     ShellTile.Create(new Uri("/MainPage.xaml?id=cycle", UriKind.Relative), cycleicon, true);
       16: }

      The Cycle tile uses the CycleTileData object to set it’s properties and this tile has fewer properties compared to the other templates. The title and count are available as on every other template and the other property that is unique for this template is the CycleImages property. It’s an IEnumerable of Uri’s to images (1 size) that will be used on the medium and wide sizes. it will center the image if it is larger as the tile itself is showing only a part of the image. if the tile is set to small it will only show a static image set in the SmallBackgroundImage property.







      The IEnumerable of images used in the medium and wide tiles can contain up to 9 images and will be rotated using a smooth slide animation. The complete list of properties available in the CycleTileData is:

      Title Tile shown on medium and wide tile sizes in the bottom left corner
      Count Counter shown on all tile sizes at the top right corner
      SmallBackgroundImage Static image shown at the background of the tile at small tile size
      CycleImages List of up to 9 images which will be rotated on the tile at medium and wide tile size.

      Looking at all the live tile features Microsoft added for Windows Phone 8 i believe it really adds some nice new options to create live tiles. I can’t wait for people to use them in their apps.

      Lock screen

      New in Windows Phone 8 is the possibility to add your own apps to the lock screen of Windows Phone 8. As a developer you can’t force an app to be shown on the lockscreen but you can enable your app for it so users can add your app to their lock screen. You can also change the lock screen image in your app by code.

      lock screen app icon, count and Text

      The image on the lock screen is an image you have to include in your project that uses a transparent background and a white icon.

      To set the lock screen image ad an image of 30 * 30 pixels to your solution and open up the WMAppManifest.xml and change the DeviceLockImageURI element to the URL of your lock screen image. Also set the IsRelative attribute to true and IsResource attribute to false. The count and text will be taken of the live tile count property of the current main tile in your app.

       1: <DeviceLockImageURI IsRelative="true" IsResource="false">Assets\LockImage.png</DeviceLockImageURI>


      To enable the lock screen image and text you also have to add the following lines of XML to the WMAppManifest.xml below the Tokens element

       1: <Extensions>
       2:       <Extension ExtensionName="LockScreen_Notification_IconCount" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       3:       <Extension ExtensionName="LockScreen_Notification_TextField" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       4: </Extensions>

      The settings for displaying data on the lock screen is now complete so we can change our settings on our phone to add our app to the lock screen. To do this. open up settings and go to the lock screen settings. On this screen you can select 1 app that can show the text (default is the calendar app) and 5 apps that are allowed to show an icon + counter. Select your app and you’re ready to go.

      settings lock screen lock screen app added lock screen enabled

      As you can see it uses the counter of our main tile (the flip tile example) and the the text is also the same as we’ve set to the BackContent property of the FlipTileData.

      Lock screen Image

      The last thing I’ll show you is how to set the lock screen background image from within your app. Like using the lock screen icon you’ll also need to add an extension to the WMAppManifest.xml to enable setting the lock screen image

       1: <Extensions>
       2:       <Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
       3: </Extensions>

      When you’ve added the extension to the manifest it’s time to start writing the code to change the lock screen image. First you’ll need to check if your app already provided the current lock screen image and if that isn’t the case you need to ask the user’s permission to change the lock screen image. if the user accepts you can change the lock screen image.

      I’ve added an image of 768*1280 pixels (largest supported resolution right now) set the image to embedded resource and added the following code to the click event of the 4th button to set the lock screen image when we press the button.

       1: private void LockBackgroundButton_Click(object sender, RoutedEventArgs e)
       2: {
       3:     SetLockScreenImage();
       4: }
       6: private async void SetLockScreenImage()
       7: {
       8:     //check if current app provided the lock screen image
       9:     if (!Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication)
       10:     {
       11:         //current image not set by current app ask permission
       12:         var permission = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
       14:         if (permission == Windows.Phone.System.UserProfile.LockScreenRequestResult.Denied)
       15:         {
       16:             //no permission granted so return without setting the lock screen image
       17:             return;
       18:         }
       19:     }
       21:     Windows.Phone.System.UserProfile.LockScreen.SetImageUri(new Uri("ms-appx:///Assets/lockscreen.png", UriKind.Absolute));
       22: }

      As you can see the SetLockScreenImage is using the async keyword because asking the user for permission can only be done by using an async call. therefore we’re using the await keyword there when asking for permission and the app will wait untill the response comes back from the user.

      When we run the app now and press the button we’ll see the old lock screen image being replaced by the newly added image

      lock screen before lock permission

      After pressing yes:

      lock screen new

      This is all for day 2 of my series of blog posts called “8 days of Windows Phone 8”. Tomorrow we’ll have a look at the emulator and the simulation dashboard which give you a lot of options to test your apps.

      Download the sample project here: http://sdrv.ms/QSJ2yx

      Liked the post or have any feedback? leave a comment below!

      Geert van der Cruijsen

    Share on Facebook
    Kick It on DotNetKicks.com
    Shout it
    Post on Twitter

    8 days of Windows Phone 8

    Yesterday Windows Phone 8 was announced at the live broadcasted event in San Francisco and today the SDK was made available to the public on BUILD. To celebrate this I wrote this series of blog posts to inform you on the new features in the Windows Phone 8 SDK. Inspired by the 31 days of Mango by Jeff Blankenburg when Windows Phone 7.5 Mango was released I thought it was a good idea to create a blog series called “8 days of Windows Phone 8” where I could inform you on using the new features of the just released Windows Phone 8 SDK.

    8 days of windows phone 8

    This first day I would like to start off with a quick summary of all the features that are added in the new SDK. After that I’ll post a new post for the coming 7 days where we’ll dive deeper in each of these features with code samples and demo’s.

  • 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



    SDK overview

    So what’s new in the SDK? Well the most important change that was already announced before this SDK is the merge with the Windows 8 kernel. Because of this the foundation where Windows Phone 7 was built on was replaced by WinRT. In Windows Phone 8 you’ll have access to a subset of the full Windows 8 WinRT and it’s currently called WinPRT. (Don’t know if that will be the official name). The WinPRT contains a subset of the Windows 8 WinRT APIs and also contains a set of new APIs that are only used for phone specific features.

    Application Platform & .net framework

    It’s now possible to build native applications in C++ and you can also use Direct3D to create 3d graphics on Windows Phone. Javascript and HTML however are not included in the SDK and I don’t know if Microsoft has any plans to add this in the future either.

    If you just want to port your Windows Phone 7.5 app to Windows Phone 8 it’s not that much work. A few namespaces have changed so you might have to replace the namespace of these controls. The controls that were moved by Microsoft are the Pivot and the Panorama controls because Microsoft wanted to improve their performance. The LongListSelector is also moved from the Silverlight Toolkit to the SDK itself. Existing Windows Phone 7.5 apps will also run on Windows Phone 8 devices so your existing apps will all keep working on the new devices that will be released.

    The new .net framework 4.5 and C# 5.0 language also add new features that are really useful when building apps. Some examples are the new async and await keywords and serialization features for JSON files. More on these new features at day 5.

    Tiles and notifications

    The new home screen of Windows Phone 8 with the 3 sizes of tiles also needs changes to the API to support this of course. It is now possible to set more texts and images on your tiles which will be used in the different size scenarios. A great addition is that you can also add notifications of your tiles to the lockscreen. In Windows Phone 7.5 it was only possible to see updates on your lockscreen for missed calls, text messages or emails but now you can set up to 5 different apps to have notifications on the lockscreen. It’s also possible to add a text notification to the lockscreen like in Windows Phone 7.5 the Agenda did. The user can select 1 application that is allowed to show it’s notifications there in text. The data of the count on the lockscreen and the text notification on the lockscreen are pulled from the data of the main Tile so you only have to set this to use these new features. More information and examples will be posted in tomorrow’s post that is completely dedicated to these features.



    Microsoft also announced earlier that there will be multiple resolutions available on the phones. The 3 available resolutions are: 480X800 (WVGA), 768X1280 (WXGA) and 720×1280 (720P). Both WVGA and WXGA are in a 15:9 ratio where 720P is 16:9 Ratio. Every app will always work on each phone. You can make your UI a bit flexible so that for example listboxes will fill the extra screen space that is available on the 16:9 ratio. If you don’t change anything to your existing design the app will still work but will show a bit of empty space below the app. On day 3 we’ll dive deeper in how to build a flexible UI with these new screen resolutions.


    Microsoft replaced the old Bing maps by Nokia maps. New features of these maps are that you can use the system launchers to download a piece of map through the MapDownloaderTask and you can also use the MapsDirectionTask to get directions to a location on the map. You can also launch the Maps application by a MapTask Launcher.


    Speech and voice commands are one of the coolest things in the SDK in my opinion. With the new features in the SDK you can start your app by saying commands like “Start MyApp, go to ThisPage”. You can also add a list of available commands which people will hear when they hold the Windows button and say “What can i say?”.

    Wallet & In-app Purchases

    The wallet gives Windows Phone users a place where they can collect coupons, credit card and payment info and accounts, Memberships and loyalty cards. By adding a few capabilities in your manifest (So the user knows you’re going to use the wallet) you can extend the wallet with your apps. You can add/ read update or delete wallet items. (you can only change items linked to your app, so it’s not possible to steal someones credit card info for example). This feature will need to prove itself in the future if it is going to be used a lot or not. One other feature I know for sure will be used a lot are in app purchases. This feature finally gives you the possibility to charge your users for features in an app so the business models on making money are being extended by a lot. examples of this are: buying extra levels for a game. buy a month subscription to a newspaper app etc.


    NFC is one of the features in Windows Phone that are highly anticipated by all the users. It’s possibilities are endless and i’m really curious of what developers are going to use it for. All currently announced phones have NFC capabilities so only time will tell. More on this on day 7.

    Data Sense

    Data sense is a new feature in Windows Phone 8 that allows users to keep track of their data plan. The api also allows developers to support their users by adapting data usage in their apps by checking if the user is on a data plan or not. It can also check if the user exceeded his data plan or is near  exceeding it and because of that it can disable (or ask the user to disable) certain parts of the app that use a lot of data.


    Simulation dashboard

    Some scenarios are always hard to test without a real device or even when you have a device simulating scenarios like low bandwidth or poor phone signal are nearly impossible to test even though chances are high actual users will run into these scenarios and they might break your app. Microsoft came with a really cool solution to this for Windows Phone 8 and it’s called the Simulation dashboard that is available in Visual Studio 2012. From the Simulation dashboard you can change the bandwidth or signal quality, throw interruptions like getting a call or a notification popup while your app is playing and you can even make the emulator jump to the lock screen to test if everything keeps working when you apps need to keep running under the lockscreen. At day 4 we’ll dive deeper in the possibilities of the new emulator and the simulation dashboard.


    Globalization and localization support was already quite good in Windows Phone 7.5 but now with Windows Phone 8 available in 180+ countries and 50+ languages Microsoft added support for apps to read from right to left which is common in certain languages. I don’t know if a lot of people are going to use these new globalization features but it is nice to mention it’s available.

    That was my quick overview of the SDK. From tomorrow on we’ll dive deeper in the SDK with code samples and more details. What will be discussed in the next blog posts of this series:

  • 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


    Hopefully you’ll be back tomorrow for the next post in this series!

    Geert van der Cruijsen

  • Share on Facebook
    Kick It on DotNetKicks.com
    Shout it
    Post on Twitter