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 | Day 2: Live tiles & Lock screen

    8 days of windows phone 8

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

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

      day2

      Live tiles

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

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

      Sizes used for these templates are:

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

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

      Flip template

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

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

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

       

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

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

      You can set the following properties on the flip tile:

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

      The result will look something like this:

      Small: (note small tile doesn’t flip)

      small

      Medium:

      medium medium example back

      Wide:

      wide example  wide example back

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

      Iconic template

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

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

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

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

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

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

      iconsmall

      Medium:

      iconmedium

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

      iconwide

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

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

      Cycle template

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

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

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

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

      Small:

      cyclesmall

      Medium:

      cyclemedium

      Large:

      cyclewide

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

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

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

      Lock screen

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

      lock screen app icon, count and Text

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

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

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

       

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

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

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

      settings lock screen lock screen app added lock screen enabled

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

      Lock screen Image

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

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

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

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

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

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

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

      lock screen before lock permission

      After pressing yes:

      lock screen new

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

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

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

      Geert van der Cruijsen

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

    8 days of Windows Phone 8

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

    8 days of windows phone 8

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

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

     

    day1

    SDK overview

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

    Application Platform & .net framework

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

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

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

    Tiles and notifications

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

    wp8

    Multi-resolution

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

    Maps

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

    Speech

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

    Wallet & In-app Purchases

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

    Proximity

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

    Data Sense

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

     wp8-2

    Simulation dashboard

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

    Globalization

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

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

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

     

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

    Geert van der Cruijsen

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