I made some Nokia Glance backgrounds for you

Nokia released a beta application to add simple backgrounds to your glance screen made by Nokia Beta labs.

The app is available for almost all Nokia Lumias (except for 5XX and 6XX range) and can be downloaded for free. (you do need to have the GDR2 update installed of course to have the Glance feature).

Download Glance Backgrounds here from the store:

c8e829d1-9ce9-4d87-9081-ce9548daa8e1

There are a lot of people creating backgrounds and I wanted to add some my self so i thought to just share them here so other people can use them as well if they like.

The backgrounds i created are all quite simple showing logos of some stuff I like. Click the image to get the full resolution image so you can save that to your phone.

wp8 win8 nokiavisual studio vs ms colorms blackwhite avanade avanade color

If you like the backgrounds or if you also created some glance backgrounds let me know in the comments below

Enjoy!

Geert van der Cruijsen

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

App to App communication on WP8 session @ Techdays 2013 slidedeck + sample code

Last week I did a session about App to App communication on Windows Phone 8 and people who attended asked me to make the source of the samples and the slide deck available. I was quite busy this week but here it finally is.

 

You can download the 3 sample projects from my skydrive here. The 3 sample projects contain different apps showing different app to app scenarios:

ColleaguesDemo: App used to show how to launch office apps from within your app by opening Word / Excel or PowerPoint files. This app is also bound to a custom file type .colleague. if you install the app and try to browse to http://demo.vdcruijsen.net/geert.colleague this app should start because it is associated with .colleague files.

MovieList + GMDB: MovieList is an app to store my movies. I wanted to be able to launch the GMDB (Geert’s movie database) app to watch the movie details or watch a trailer. so when you browse to a movie in the movielist you can launch GMDB from there. The GMDB app is associated with the GMDB: protocol so you can launch the app from either the MovieList app or by an URL in an SMS/mail or NFC tag like this: gmdb:movie?id=8

techdaysbanner2

Hopefully you enjoyed my session at TechDays and see you there again hopefully next year or at some other Windows Phone event.

I’m really curious to see apps showing up in the marketplace using App to App scenario’s because it would really add something to the Windows Phone Ecosystem.

Happy Coding

Geert van der Cruijsen

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

Fun with ValueConverters: building a Mustachify.me converter for Windows Phone & Windows 8

Valueconverters are a really usefull feature when you are building an app using the MVVM pattern so you can bind properties from your viewmodel of a specific type to a element in the view which can only bound to another type of object. Using avalueconverter you can convert the value of one kind of object to a different kind so you can still bind them.

What I often see when looking at code from people who are new to MVVM is that they have a lot of properties in their viewmodels that can easily be reduced by using valueconverters. The best example which is used the most is probably the Boolean to Visibility converter. When building an app, chances are high that you want to show or hide certain UI elements depending on some boolean in your viewmodel. To bad the Visibility property of these elements only wants a bind to the Visibility enum and not your boolean. By using a value converter you can switch this boolean value to a Visibility without creating a new Visibility typed property in your viewmodel that I see a lot of people doing.

Don’t worry you don’t have to create all these converters yourself. A lot of them are already created by others and shared on several locations. Microsoft made a coding4fun toolkit that contains the most important converters like the one i described above. You can check out these converters here: http://coding4fun.codeplex.com/wikipage?title=Converters

So how hard is it to create your own converter? It’s really easy and I’ll show it by creating a new converter step by step in the rest of this post. I was watching someone demoing a fun app a few weeks back that used the site http://Mustachify.me to add mustaches to pictures and i thought this could be a pretty cool converter to create and add to your application so you can change all your images in your apps to images with Mustaches.

To start let’s create a new Windows Phone 8 project (These valueconverters aren’t only for Windows Phone, you can also use them for Windows 8, WPF, Silverlight, etc) and we’ll choose the “Windows Phone Databound app” project template so we will get some out of the box simple MVVM implementation.

To make this as simple as possible let’s just open the MainViewModel.cs and remove the out of the box  LocalizedSampleProperty, the Items collection and the IsDataLoaded and LoadData methods. Now we only have a SampleProperty left and we’ll rename this to property to PhotoUrl and give it a default value of some random picture

   1: private string _photoUrl = "http://upload.wikimedia.org/wikipedia/commons/2/21/Steve_Ballmer_at_CES_2010_cropped.jpg";

   2: /// <summary>

   3: /// Sample ViewModel property; this property is used in the view to display its value using a Binding

   4: /// </summary>

   5: /// <returns></returns>

   6: public string PhotoUrl

   7: {

   8:     get

   9:     {

  10:         return _photoUrl;

  11:     }

  12:     set

  13:     {

  14:         if (value != _photoUrl)

  15:         {

  16:             _photoUrl = value;

  17:             NotifyPropertyChanged("PhotoUrl");

  18:         }

  19:     }

  20: }

Our simple viewmodel is ready so now lets create the UI for this example. Just remove everything inside the LayoutRoot Grid and place a new Pivot there with 2 pivot items. inside the pivot items we’ll place 2 images. 1 original and 1 with the added mustaches.

   1: <phone:Pivot Title="mustachifymeconverter" Grid.Row="1">

   2:     <phone:PivotItem Header="default">

   3:         <Grid>

   4:             <Image Source="{Binding PhotoUrl}"/>

   5:         </Grid>

   6:     </phone:PivotItem>

   7:     <phone:PivotItem Header="mustache">

   8:         <Grid>

   9:             <Image Source="{Binding PhotoUrl}"/>

  10:         </Grid>

  11:     </phone:PivotItem>

  12: </phone:Pivot>

Since we haven’t implemented the valueconverter yet the app will now show just 2 images both bound to the same PhotoUrl property created in the viewmodel. To make our example build we’ll have to remove the MainLongListSelector_SelectionChanged and the OnNavigatedTo methods from the MainPage.xaml.cs and the code inside the Application_Activated method in the App.xaml.cs since these are not needed anymore.

Let’s run the app and see if everything is working. The app should look something like this, showing a picture of Steve without any mustache :)

mustachedemo1   

It’s time to add the MustachifyMeConverter to our project. Just create a new class called MustachifyMeConverter and make it implement :IValueConverter

   1: public class MustachifyMeConverter : IValueConverter

   2: {

   3:     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   4:     {

   5:         throw new NotImplementedException();

   6:     }

   7:  

   8:     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   9:     {

  10:         throw new NotImplementedException();

  11:     }

  12: }

When you implement the IValueConverter you’ll have to implement 2 methods. Convert and ConvertBack. Since http://Mustachify.me only supports adding mustaches we’ll leave the ConvertBack as it is and only implement Convert.

Implementing the Mustachify.me converter Convert method is really simple. you actually only need 1 line of code: check if the string passed as a value is empty, if not just add “http://mustachify.me/?src=” in front of the old url and return it.

   1: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   2: {

   3:     return value != null ? "http://mustachify.me/?src=" + value.ToString() : string.Empty;

   4: }

Yes ValueConverters are really easy to create so let’s also use it in our app. Adding it to the XAML is also pretty easy. Since building the UI should be done in Blend (in my opinion) lets add the value converter in Blend! Fire up the Mainpage in Blend and select the image on the 2nd pivot page. In the properties window select the Source and choose “Create Data Binding”. In the popup you’ll see an option to select a ValueConverter on the left bottom of the window.

mustachedemo2

Press “Add value connector” and in the new window select the MustachifyMeConverter we created. Press Ok and we’re all done.

mustachedemo3

Fire up the app again and now the 2nd pivot item should have mustaches added to the picture without adding any code in our viewmodel to support this.

mustachedemo1mustachedemo4

Hopefully this small tutorial gave you some ideas on how and when to use ValueConverters when building Windows Phone apps or any other XAML based apps using the MVVM pattern.

You can download the sample project here: http://sdrv.ms/VYhVVk

Happy coding!

Geert van der Cruijsen

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

Windows Phone 8 Emulator Skin Switcher 1.0 released on codeplex

Last year when working on some Windows Phone 7 projects i thought it was a good idea to change the skin of the Phone emulator of all the developers in our team for screenshots and demos. I created a project on codeplex and gathered all the skins i could find on the internet into a simple app where people could switch from the default skin to a Lumia 800, HTC device or Samsung phone for example.

When Windows Phone 8 was announced i received a lot of questions from people to update the skin switcher app to support Windows Phone 8 and finally today i had time to finish this project and upload version 1.0 on codeplex.

In the Windows Phone 8 Emulator Skin Switcher you can choose between 17 different skins from all currently available Windows Phone 8 devices. The app works the same way as it did for Windows Phone 7. Just start the skin switcher, select a skin and restart your emulator. You can select up to 3 different skins at the same time. 1 for each emulator resolution.

emulator skin switcher wxga

Available skins at 1.0 release:

  • WVGA
  • WP8 Default
  • HTC 8S Blue
  • HTC 8S Orange
  • Nokia Lumia 820 Black
  • Nokia Lumia 820 Cyan
  • Nokia Lumia 820 Red
  • Nokia Lumia 820 White
  • Nokia Lumia 820 Yellow
  • WXGA
  • WP8 Default
  • Nokia Lumia 920 Black
  • Nokia Lumia 920 Grey
  • Nokia Lumia 920 Red
  • Nokia Lumia 920 White
  • Nokia Lumia 920 Yellow
  • 720p
  • WP8 Default
  • HTC 8X Black
  • HTC 8X Blue
  • HTC 8X Neon
  • HTC 8X Red
  • Samsung Ativ S

You can download the Windows Phone 8 Emulator Skin switcher at codeplex here:

http://wp8emulatorskins.codeplex.com/

If you’re still working with Windows Phone 7 you can use the old Windows Phone 7 Emulator Skin Swicher which is also available on codeplex

HTC_8S_Blue_Skin_Up_480x800 HTC_8X_Neon_Skin_Down_720x1280 Nokia_Lumia_820_Cyan_Skin_Up_480x800 Nokia_Lumia_820_Red_Skin_Up_480x800 Nokia_Lumia_920_Grey_Skin_Up_768x1280 Samsung_ATIV_S_Skin_Down_720x1280

If you have any feedback or if you’ve created a skin yourself and would like to have it added to the application let me know by adding a comment here or contact me on twitter

Happy Coding and testing using your skinned Windows Phone 8 emulator!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
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

    day8

    Wallet

    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";

       8:     

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

      10:         

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

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

      13:  

      14:     await beerDeal.SaveAsync(); 

      15:  

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

      17:  

      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.

    inapp1

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

    inapp2

    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.

    inapp3

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

    inapp4

    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.

    inapp7

    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();

       5:     

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

       7:     

       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

    day7

    Bluetooth

    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: }

       6:  

       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");

       5:  

       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: }

       7:  

       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);

      15:  

      16:         await dr.LoadAsync(4);

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

      18:         await dr.LoadAsync(messageLen);

      19:         return dr.ReadString(messageLen);

      20:     }

      21: }

    NFC

    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();

       4:  

       5:     if (pd != null)

       6:     {

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

       8:     }

       9: }

      10:  

      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.

    proximity

    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

    day6

    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.

    capabilities 

    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:     }

      14:  

      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;

       8:  

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

      10:  

      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"?>

       2:  

       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>

      13:  

      14:     <PhraseList Label="day">

      15:       <Item> today </Item>

      16:       <Item> tomorrow </Item>

      17:       <Item> yesterday </Item>

      18:     </PhraseList>

      19:  

      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();

       4:  

       5:     InitializeVoiceCommands();

       6: }

       7:  

       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

    speech12

    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);

       4:  

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

       6:     {

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

       8:         {

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

      10:  

      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

     

     day5

    .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; }

       6:  

       7:     [DataMember]

       8:     public DateTime Date { get; set; }

       9:  

      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"});

       7:  

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

       9:  

      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);

      14:  

      15:  

      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:     }

      22:  

      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");

       5:  

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

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

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

       9:  

      10:     return todos;

      11:  

      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();

       5:  

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

       7:  

       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.

    day5demo

    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 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

     

    day4

    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();

       4:  

       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)

    wvga

    720p

    wxga

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

    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 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

     

    day3

    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.

    image

    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.

    accelerometer 

    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.

    location 

    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.

    screenshot

    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.

    network 

    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.

    simulationdashboardlink

    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)

    simulationdashboard

    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