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

Fixing “The image “BadgeLogo” has an ABGR value {value} at position (x, y) that is not valid” error in your Windows 8 app

Recently i was adding a lock screen image and background agent to my Windows 8 app Wordbattle and it worked great. however when i ran the “Windows App Certification Kit” one of the tests failed with the following error:

The image “BadgeLogo” has an ABGR value {value} at position (x, y) that is not valid. The pixel must be white (##FFFFFF) or transparent (00######)

Unsure on what this exactly meant i started searching for this exception and only found some unclear answers on how to solve this problem. It was clear to me that my badge logo images that are used on the lock screen were causing the problem but since I’m a developer and not a designer i didn’t know how to fix this. (Same reason why I’m writing this post since i expect more devs to run into this problem ;) )

After reading the error message and looking at my image at the x and y value of the pixels my understanding was that app logo’s couldn’t have any semi transparent pixels because the error states “the pixel must be white ##ffffff or transparent 00######”. This was however not the correct solution (it does work ofcourse but you can use semi transparent pixels, more on that later). I looked at some system badge icons and i could see that they were also using semi transparent badge icons to draw skewed lines or rounded edges.

I went to one of our XD Guys: Michiel Pruijssers at Avanade and asked him how to fix my badge logo. After some research we found out that some of my semi transparent pixels weren’t pure white but a tiny little bit darker which you can’t see because of the semi transparency. However there is a small workflow on how to fix this for each badge logo that is receiving this error. You’ll need a tool like Photoshop or like me Paint.Net :) to fix this problem. I’ll explain how to fix it with both tools:

Photoshop:

In Photoshop open your badge image and go to Image –> Adjustments –> Levels.

image

In the levels popup you’ll see input levels and output levels of the range of colors used in your logo. 1

change the output levels from 0 to 255 to 254 to 255 and press OK.2

Save the picture. Add the new pictures (remember to fix all your badge icons for each resolution) to your solution and run the Windows App Certification Kit again. it will now pass all the test!

Paint.Net

Fixing your badge in Paint.Net is almost the same as in Photoshop except the menus are in a different location. Open your badge icon in Paint.Net and go to Adjustments –> Levels.

image

In the popup change the value 0 to 254 and press OK.

image

All other colors except for pure white are removed. you can now save your image and add them to your solution again. Run the Windows App Certification Kit and the failing test should pass.

Hopefully this posts helps other devs to fix this problem since the error message is not that clear.

Happy Coding!

Geert van der Cruijsen

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

Launching Skype from your own Windows Store App

One of the strong features of Windows 8 is the integration of apps with the Windows 8 OS and also the ability for applications to integrate with other applications. A scenario that can be useful for many applications is to call someone directly using skype from within your application. By using Protocol extensions this is really easy on Windows 8.

Skype_Logo      

Unfortunately there is no documentation from Skype on this subject yet so that’s why I’m writing this blogpost to explain how you can launch Skype from your application. The code is actually really simple. Skype has registered several protocol extensions (can be found in the AppxManifest.xml file of the skype app) and the only thing you’ll have to know is what parameters to add to this protocol to launch a specific task.

What i did to see which protocol extensions Skype has i opened up the directory of the Skype Windows Store app (program files\WindowsApps) and looked for the AppxManifest.xml file. when you open the file look for Extensions element and in there should be the protocols that the application is bound to.

   1: <Extensions>

   2:         <Extension Category="windows.protocol">

   3:           <Protocol Name="skype"/>

   4:         </Extension>

   5:         <Extension Category="windows.protocol">

   6:           <Protocol Name="tel"/>

   7:         </Extension>

   8:         <Extension Category="windows.protocol">

   9:           <Protocol Name="sms"/>

  10:         </Extension>

  11:         <Extension Category="windows.protocol">

  12:           <Protocol Name="message-skype-com"/>

  13:         </Extension>

  14:         <Extension Category="windows.protocol">

  15:           <Protocol Name="message-messenger"/>

  16:         </Extension>

  17:         <Extension Category="windows.protocol">

  18:           <Protocol Name="audiocall-messenger"/>

  19:         </Extension>

  20:         <Extension Category="windows.protocol">

  21:           <Protocol Name="videocall-messenger"/>

  22:         </Extension>

  23:         <Extension Category="windows.protocol">

  24:           <Protocol Name="audiocall-skype-com"/>

  25:         </Extension>

  26:         <Extension Category="windows.protocol">

  27:           <Protocol Name="videocall-skype-com"/>

  28:         </Extension>

As you can see Skype has many protocols to launch the application, all for specific tasks. you can use tel or sms as generic protocols so people can choose what kind of app they use for calling or texting or use the more specific protocols especially made for skype: skype, message-skype-com, audiocall-skype-com etc.

Launching Skype and starting with a specific task is really easy. On he URL just add the phone number or skype id after the protocol name to launch the app and directly start a voice call or chat message.

In C# you can just create a new URI containing the protocol + username for example: message-skype-com:UserName. This will launch skype and will automatically start a chat session with the user “UserName”

   1: var chatTo = new Uri("message-skype-com:" + UserNameTextBox.Text);

   2: await Windows.System.Launcher.LaunchUriAsync(chatTo);

When you’ve created the URL just call Windows.System.Launcher.LaunchUriAsync and pass in the URL and you’re done. it doesn’t get easier than this.

For your convenience I’ve created a sample project that can be downloaded from my SkyDrive here: http://sdrv.ms/ZRcwSQ

The sample projects launches Skype on different ways, starting Audio calls, video calls etc.

As you could see the code itself is peanuts, just knowing what to call is the trick. i found out which parameters to pass to Skype by trial and error. Luckily passing in the skype username or phone number was one of the first things i tried.

I wish that there would be some kind of list of all applications that can be launched by using app to app communications but unfortunately

Happy coding!

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

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

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

54676_459741017401140_295441675_o

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

you can download it here

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

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

Geert van der Cruijsen

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