31 Days of Windows Phone | Day #24: Embedding Fonts

This post is Day #24 in a series called the 31 Days of Windows Phone.

Yesterday, I wrote about how you can add trial versions to your applications.  It’s an incredibly valuable feature that will ultimately help you sell more apps.  Today, we’re going to cover embedding fonts in our applications.

First, Be Smart

With all applications that are built for mobile devices, you have remember that data is not necessarily “free.”  Your user has a data plan that might only include 5GB of data transfer a month.  Secondly, there’s a limitation to how big an application can be and still be gotten over a data plan: 20MB.  If your application is larger than 20MB, your user will have to use Wi-Fi or sync with their computer.  Neither of those are optimal for selling tons of copies of your app.

Having said that, do not start filling your applications with every possible piece of data, fonts, images, videos, etc. that you “might” need.  Strip it down to its bare minimum, and if you can get that extra content over the air at a later time, think about doing it.

Embedding Fonts in Windows Phone 7

One of the most common questions I get asked about building WP7 apps is how to use a custom font that is not already included. Here’s a list of what IS included by default (Segoe WP) is what is used if you don’t specify a FontFamily:


To add another font to your application, it’s pretty simple, but not terribly obvious.  The first thing you need to do is find a font you want to use.  I recommend DaFont.com or 1001FreeFonts.com, but there are plenty of places that offer free, re-distributable fonts.

That’s an important key word, however.  REDISTRIBUTABLE.  Please make sure that you are only including fonts that are allowed to be redistributed.  In some cases, you might need to pay for these rights.  Make sure you’re covering yourself before you just start adding fonts to your application.


OK, so now that we HAVE a font we can package up and distribute, here’s how we get it embedded in our application.  The first step is to add it to our project.  I generally like to create a “fonts” folder that I keep my fonts in, but it’s not required.  Here’s a screenshot of my Solution Explorer.


The catchy part to using this file appropriately is the Build Action we assign to this file. If you’re not familiar with Build Actions, click on your font in Solution Explorer, and look at the Properties pane.


There are two values we need to change manually, or we’ll never see any success with our font.  The first is the Build Action.  You want to change that to be “Content.”  The second is Copy To Output Directory.  That needs to be “Copy if newer.”  Now my properties look like this:


Now, to actually USE the font, right?  There’s some simple XAML syntax to make this happen on the FontFamily property.  Here’s what it looks like:

<TextBlock Text="12:02 AM" FontFamily="fonts/DigitalDream.ttf#Digital Dream" FontSize="60"/>

As you can see, I need to specify the font file itself, and following a pound sign/hash mark (#), the actual name of the font.  In my example, they’re the same.  If you want to be sure you’re right, open the font file on your computer, and you should see a window that looks like this:


The actual font name is listed right at the top.  You’ll know when you get the syntax right, because the font will immediately change on your design surface in Visual Studio 2010.

Download the Code

If you’d like to see a working example of embedded fonts, download this solution and open it up for yourself.  It’s amazingly simple, but also a great way to give your application a distinct look.


31 Days of Windows Phone | Day #23: Providing Trial Versions of Your App

This post is Day #23 in a series called the 31 Days of Windows Phone.

Yesterday, I wrote about how you could add your game to the Games hub on a Windows Phone.  Today, I’m going to show you how simple it is to set up your application to have Trial sections.  For example, let’s say you create a game that has 50 levels.  Perhaps you want the user to be able to play the first 5 levels for free, but to play the rest, they need to buy the game.  This article will show you how to do that.

Using the LicenseInformation Class

By adding the Microsoft.Phone.Marketplace assembly to our page, we have access to the LicenseInformation class, which is directly related to the “paid” status of our application.

using Microsoft.Phone.Marketplace;

Our next step is to actually use the LicenseInformation class, so let’s create an instance of it:

LicenseInformation li = new LicenseInformation();

Finally, LicenseInformation has a very nice Boolean property called IsTrial(), not surprisingly, that allows us to check if we’re in a Trial state or not.  You can use it in a simple if statement, like this:

if (!li.IsTrial())
	//Do something that only paid users can do.
	//Do something that all users, trial or paid, can do.

Testing Trial Mode

Unfortunately, there’s not a built-in mechanism to just swap between Trial and Paid states.  How I am handling this is pretty simple.  I’m using the same IF statement that you find in your App.xaml.cs file.  It checks to see if you’re debugging, and if you are, sets an IsolatedStorageSetting that I call “trialMode”.

Here’s the entire App() method, including the default code that is in our App.xaml.cs file.  In my example below, I am setting my trialMode variable to TRUE.  Turn this off when you want to test “paid” mode.

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

public App()
	// Global handler for uncaught exceptions. 
	UnhandledException += Application_UnhandledException;

	settings["trialMode"] = false;

	// Show graphics profiling information while debugging.
	if (System.Diagnostics.Debugger.IsAttached)
		settings["trialMode"] = true;
		// Display the current frame rate counters.
		Application.Current.Host.Settings.EnableFrameRateCounter = true;

		// Show the areas of the app that are being redrawn in each frame.
		//Application.Current.Host.Settings.EnableRedrawRegions = true;

		// Enable non-production analysis visualization mode, 
		// which shows areas of a page that are being GPU accelerated with a colored overlay.
		//Application.Current.Host.Settings.EnableCacheVisualization = true;

	// Standard Silverlight initialization

	// Phone-specific initialization

Revisiting my code from earlier, I need to modify my IF statement to handle this new IsolatedStorageSettings value.  I am including my entire MainPage.xaml.cs file this time, so you can see everything in context.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Marketplace;
using System.IO.IsolatedStorage;

namespace Day23_UsingTrial
	public partial class MainPage : PhoneApplicationPage
		LicenseInformation li = new LicenseInformation();
		IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
		// Constructor
		public MainPage()

			if (!li.IsTrial()||(bool)settings["trialMode"] == false)
				//Do something that only paid users can do.
			else if (li.IsTrial() || (bool)settings["trialMode"] == true)
				//Do something that all users, trial or paid, can do.

That’s about all you need to do, though, and this is not necessarily the “best” way to handle this situation, but it’s been working for me.  If someone has a better way, I’d love to start using that instead.

Download the Code

To see all of this in a working example, download this solution file and play with it.  That’s always the best way to learn how stuff works.


31 Days of Windows Phone | Day #22: Apps vs. Games

This post is Day #22 in a series called the 31 Days of Windows Phone.

Yesterday, I posted an epic-length article on the Silverlight Toolkit for Windows Phone.  Today will be a bit shorter, but just as valuable.  We’re going to cover a subtle but important designation in your application’s settings:  the Genre.

If you have created a default Windows Phone application (or a default XNA application), and deployed it to the emulator, you’ve probably noticed that it resides in the primary list of applications. (The list you see when you tap on the arrow on the home screen.)

If you’ve used an actual WP7 device, however, you’ve probably noticed that all of the games show up in the Games hub.  There’s a very simple way to make this happen, though your application will seem to “disappear” in the emulator when you do this.  Keep in mind that you should ONLY do this if your application is ACTUALLY a game.  You might get denied from the App Hub if you aren’t honest about what your application is.

Remember Day #1?

On Day #1 of this series, I walked through each file of a default Silverlight application for Windows Phone.  To make this little switch, all we need to do is open the WMAppManifest.xml document.  Take a look at your Solution Explorer in Visual Studio 2010 to find it.  It’s in the Properties folder.


Inside this file, you’ll find a bunch of metadata about your application.  Specific things like the name/path of your Application icons, application names, default page to load, etc.

As an aside, changing the DefaultTask’s NavigationPage property is a great way to speed up the manual testing of your UI.  Change the name of the page in that node, and your app will load on the new page instead.  Here’s an example:

    <DefaultTask  Name ="_default" NavigationPage="ProductPage.xaml?id=42"/>

OK, back to the task at hand…getting our application to reside in the Games hub instead of being treated like every other application on the phone.  To do this, we need to modify the Genre property of the App node of this document.  Here’s what it looks like by default (I’ve moved things around so that you can see the Genre value without scrolling):

<App xmlns="" Genre="apps.normal" ProductID="{8743bc4b-a909-4512-aab9-8633d93a5b04}" Title="Day22_AppsVsGames" RuntimeType="Silverlight" Version="" Author="Jeff Blankenburg" Description="An amazing demo on how to change your app's location." Publisher="Blankensoft">

You can see that the default value for Genre is “apps.normal.”  Change that value to “apps.games” and you’ll notice that your application vanishes from the emulator.  (It’s not actually gone, you just don’t see the Games hub in the emulator.  Here’s my example, modified with this change:

<App xmlns="" Genre="apps.games" ProductID="{8743bc4b-a909-4512-aab9-8633d93a5b04}" Title="Day22_AppsVsGames" RuntimeType="Silverlight" Version="" Author="Jeff Blankenburg" Description="An amazing demo on how to change your app's location." Publisher="Blankensoft">

If you get an opportunity to deploy your application to an actual device, however, you’ll find your game in the Games hub.  In the United States, that means you can try this as soon as November 8th.  If you’re in New Zealand, however, you can already acquire one.

In order to make this happen, however, make sure to also get registered in the App Hub.  Until you have a developer account there, you won’t be able to push your code to your own phone.

Download the Code

There’s really not much more to this sample code than I wrote about above, but you can download it nonetheless.  Enjoy!


31 Days of Windows Phone | Day #21: Silverlight Toolkit for Windows Phone

This post is Day #21 in a series called the 31 Days of Windows Phone.

After talking about the Map Control yesterday, it occurred to me that you might not be aware that there are TONS of controls available to you through the Silverlight Toolkit.  Today’s article addresses the Silverlight Toolkit for Windows Phone, specifically, but also check out the Silverlight 3 Toolkit as well.

What is a Toolkit?

The original toolkit for Silverlight 3 was a huge pile of extra controls that you could use in your projects.  The controls ranged from charting to accordions, date pickers to autocomplete boxes.  What’s awesome about this toolkit is that it’s completely compatible with our Windows Phone applications that use Silverlight.

The Silverlight Toolkit for Windows Phone 7 is a similar idea, but it only includes additional controls that would be used in a Windows Phone application.  It includes:

  • ContextMenu
  • DatePicker & TimePicker
  • GestureListener
  • ToggleSwitch
  • WrapPanel

I’m going to spend the rest of this article showing examples of each of the controls in this Toolkit, but I also highly encourage you to peruse the Silverlight 3 Toolkit as well.  There’s tons of controls, examples, and code that you can use in your projects.  I’m to cover the charting controls from that toolkit later in this series, but for those of you that are impatient, you can check it out on your own now.

ContextMenu Control

If you’ve had an opportunity to pin something to the Start page, you’ve seen the ContextMenu in action. Here’s what it looks like when I try to pin Internet Explorer to my Start menu in the emulator (tap and hold to show this menu):


In order to make this menu appear, we need the ContextMenu control from the Silverlight Toolkit.  As with all of the examples in this article, we need to add the Silverlight Toolkit assembly to our project.  You can see it here:


Once we’ve added it, we’ll also need to add that namespace to the context of our XAML page.  To add this namespace, add this to the <phone:PhoneApplicationPage> tag at the top of your file:


Now we can get down to business.  Let’s take a common control that we might want to offer our users more options for, the Rectangle.  Perhaps we have a shape, image, icon, etc. that our users need to interact with.  Perhaps there is more than one thing you want to do with this Rectangle (think “right-click” menu).  By adding a ContextMenu to our Rectangle, we can pop a menu any time that our user taps and holds on that object.  This can be ANY XAML element, so you could even apply this to the background of your application, portions of a Panorama, or even Buttons.  Here’s how it’s applied in XAML:

<Rectangle Width="100" Height="100" Fill="Red">
			<toolkit:MenuItem Header="this is menu item 1" Click="MenuItem_Click" />
			<toolkit:MenuItem Header="this is menu item 2" Click="MenuItem_Click" />
			<toolkit:MenuItem Header="this is menu item 3" Click="MenuItem_Click" />

We basically tie in to the ContextMenuService, adding a ContextMenu to our specific control.  You can see that each item can also have a Click event, allowing us to tie these menu options back to our code.  Here’s a screenshot of my ContextMenu:


If you test this in your emulator, you might also notice that everything in the background zooms out a little, as if it’s dropping into the background, bringing the menu to the front and center of the user’s attention.  You might not want this behavior, so the <toolkit:ContextMenu> item has an additional attribute which is IsZoomEnabled.  Setting this to false will stop that zooming animation from happening automatically.

It’s that simple to add the equivalent of a right-click menu to our XAML elements.  This one will likely be the most used of the 6 controls (unless the GestureService  takes off).

DatePicker and TimePicker Controls

As I was preparing the code for this article, these two presented an interesting challenge for me.  They are SO straightforward simple that I just couldn’t figure out what I was doing wrong.  As it turns out, there’s a little magic involved.  I’ll explain that in a bit.  First, let’s talk about getting these controls on our page.  That’s the easy part:

<toolkit:DatePicker Value="7/22/1976" />
<toolkit:TimePicker Value="12:02 AM" />

When you add these controls to your page, they work as advertised.  They allow the user to select a date (starting with the initial date you provide…if you don’t provide one, it uses “today’s” date.)  Here’s screenshots of each:

datepicker   timepicker

OK, now to talk about the perplexing problems these controls presented me.  You’ll notice in the screenshots above, there’s an ApplicationBar.  And it has two icons (with no images).  After beating my head on my desk for a few minutes, I realized that these are the Done and Cancel buttons.  (You can also discover this by clicking on the ellipsis (…) icon.  They’ll slide up to reveal their text labels.

To make these icons actually work, you need to follow these instructions exactly:

  1. Create a folder in the root of your project named “Toolkit.Content”
  2. Add two images to that folder with the specific names:
    1. ApplicationBar.Cancel.png (download it here)
    2. ApplicationBar.Check.png (download it here)
  3. Make sure that the Build Action on those two images is set to “Content.”  If you haven’t done this before, just click on the images, and change it in the Properties tab.


Once you’ve followed those specific instructions, IT JUST WORKS!  I wish this all just happened automatically, but at least we know.  And knowing is half the battle, right?

Here’s a look at the “working” ones:

datepickerfinal   timepickerfinal

GestureListener Control

Up until this point in the 31 Days of Windows Phone, you may have been wondering when you were going to find out how to handle gestures from your user in your application.  Today’s the day!  (DISCLAIMER: this is “one” way to do this.  There are plenty of other approaches to gesture handling, but this is definitely the easiest, and if you’ve been reading along, that’s what this series is optimized for.  The easiest way to accomplish something in Windows Phone.  Not necessarily the best practices that you should ALWAYS use.)

OK, now that that’s cleared up, let’s talk abut the GestureListener.  Much like the ContextMenu, we’re going to let the GestureService know that we’ve created a GestureListener, and then we basically rig up event handlers for the specific gestures we’re looking for.  Remember that we apply this to a specific XAML element, so the gestures will only be recognized on the control that this is applied to.  The gestures that are supported in the GestureListener are:

  • Tap
  • DoubleTap 
  • Hold
  • Flick
  • Pinch
  • Drag and Drop

Each of these are implemented in such a way, however, that it’s almost TOO easy to accomplish.  Pinch and Drag have a few more technical details (basically the delta between when the gesture started and when it completed.)  Here’s what our XAML would look like (on another rectangle):

<Rectangle Width="100" Height="100" Fill="Blue">
				PinchCompleted="PinchEnd" />

As you can see, I can just define the gestures I want to recognize, and then assign event handlers to them, allowing me to translate that gesture to code very simply.  In the sample code for the Silverlight Toolkit for Windows Phone, there’s a great example of how to handle each of these events.

ToggleSwitch Control

You may have seen this control if you’ve tried to change the Date/Time in the Emulator.  Here’s a quick example:


Adding this to the page is simple:

<toolkit:ToggleSwitch Header="Receive updates automatically"/>

In the above screenshot, where it says “24-hour clock”, my example would read “Receive updates automatically.”  The On/Off text is automatically handled for you, thankfully.  If you’d like to do a little more customization to this control, however, it’s pretty easy to do.  There’s a HeaderTemplate and a ContentTemplate that we can leverage to make this control more “our own.”  There’s also Checked and Unchecked events that fire when the switch is manipulated.  (Think of this control much like you would a CheckBox).  Here’s an example of these being used (and bound to a data source):

<toolkit:ToggleSwitch Header="12:02 AM">
            <ContentControl FontSize="{StaticResource PhoneFontSizeLarge}" Foreground="{StaticResource PhoneForegroundBrush}" Content="{Binding}"/>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Alert: " FontSize="{StaticResource PhoneFontSizeSmall}"/>
                    <ContentControl HorizontalAlignment="Left" FontSize="{StaticResource PhoneFontSizeSmall}" Content="{Binding}"/>
                <TextBlock Text="every weekday" FontSize="{StaticResource PhoneFontSizeSmall}" Foreground="{StaticResource PhoneSubtleBrush}"/>

Finally, we have the WrapPanel. While its purpose might seem obvious, it’s a control that is glaringly missing from the standard set of controls available in the original set.

WrapPanel Control

A WrapPanel is basically a StackPanel with some extra awesome sauce added.  I was building a game a few months ago, and I wanted to create a screen that had 30 buttons on it.  Since this was before the WrapPanel was available, I had to dynamically create a Grid, and then assign each new button to a Grid location.  Much more work than I wanted to do, just to get 30 buttons in a nice 5×6 layout.  The WrapPanel solves that problem for us.

In the example below, I have created a WrapPanel that contains 12 buttons. 

	<Button Width="75" Height="75" Content="1" />
	<Button Width="75" Height="75" Content="2" />
	<Button Width="75" Height="75" Content="3" />
	<Button Width="75" Height="75" Content="4" />
	<Button Width="75" Height="75" Content="5" />
	<Button Width="75" Height="75" Content="6" />
	<Button Width="75" Height="75" Content="7" />
	<Button Width="75" Height="75" Content="8" />
	<Button Width="75" Height="75" Content="9" />
	<Button Width="75" Height="75" Content="10" />
	<Button Width="75" Height="75" Content="11" />
	<Button Width="75" Height="75" Content="12" />

In the screenshot below, you’ll see that the WrapPanel dynamically decides how they will fit on each row, and stacks the next row below the first.  No overlap (much like a StackPanel), but also the freedom to not worry about the size of your content screwing up your layout.  Here’s a screenshot:


In my code example, below, you’ll see that I’ve rigged up events on Button #1 and Button #2.  They make the size of all of the buttons grow and shrink.  Playing with this example should demonstrate exactly how the WrapPanel dynamically moves your content around, even at runtime.  Here’s a screenshot of the same code, but with the buttons enlarged significantly:


So that’s it!  We covered all 5 of the new controls available in the Silverlight Toolkit for Windows Phone.  Make sure you download it today, because I think you’ll find yourself needing these sooner than later.

Download the Code

In this sample code, you’ll find a simple example of each of the controls in the Silverlight Toolkit for Windows Phone.  On Day #31, we’ll be covering the Silverlight 3 Toolkit, and how we can leverage the charting controls in our WP7 applications.


31 Days of Windows Phone | Day #20: Map Control

This post is Day #20 in a series called the 31 Days of Windows Phone.

Yesterday’s mammoth post was on Push Notifications, and getting data to the phone, even when your app isn’t running.  Today, we’re back to controls, and more specifically, the Map Control.  As geolocation becomes more and more prevalent in mobile applications, it’s increasingly important to be able to show our user where they are, and what’s relevant near them.

Using the Map Control

Part of your Toolbox in Visual Studio 2010, you just need to drop a new Map Control on your page.  When you do, you’ll also notice that you need to add another XML namespace into your page.


And here’s the default XAML that it used for my example (after I positioned it and sized it appropriately):

<map:Map Height="607" HorizontalAlignment="Left" Name="myMap" VerticalAlignment="Top" Width="456" />

Finally, a quick screen shot of the map in my application:


You’ll notice that in white text, it says “Invalid Credentials.  Sign up for a developer account.”  For the rest of this post, I am going to walk you through all of the different things we can do with this map control, including getting a valid developer API key.

Setting Up Your Developer Account

The first thing you should do, before building your mapping application, is to get a Bing Maps API key.  It’s a simple, free process, and it gets rid of that ugly white text from above.  To get one, head over to Bing Maps Portaland register.  Once you’ve done that, you need to create an API key.  Here’s what the form looks like:


When you fill this out, they will give you an API key that looks something like this:


(No, that’s not my API key.  I’ve changed many characters.  But it looks like what you should be looking for.)



Using the Credentials Provider

Now that you have an API key, we need to plug that in to our application.  If you’ve only got one map in your application, it’s perfectly fine to use it like this:

<map:Map CredentialsProvider="AsWlUnHEvLgHlLHaRqTZLslewv1QIdGppxOqyL-7He2jxyHvLAjutrcntemUih-w9">

If you’re going to be re-using this value over and over, you might want to save this value elsewhere, like your App.xaml file.  To do this, use the example below.  I’ve provided the code you’ll want to include in both your App.xaml file, as well as in your actual Map control.  We’re basically creating a static CredentialsProvider value in our App.xaml, and retrieving it on our page.


	<map:ApplicationIdCredentialsProvider ApplicationId="AsWlUnHEvLgHlLHaRqTZLslewv1QIdGppxOqyL-7He2jxyHvLAjutrcntemUih-w9" x:Key="BingMapsAPIKey"></map:ApplicationIdCredentialsProvider>

Map Control

<map:Map CredentialsProvider="{StaticResource BingMapsAPIKey}">



Changing the Map Control’s features

There are a whole host of options for changing the map’s look & feel.  For example, changing from Road to Aerial mode, or deciding whether to show the zoom level selector.  There is an incredible list of configurable options available to you, and they’re on the Bing Maps Silverlight Control Interactive SDK.  There’s no reason for me to cover ALL of the options outlined there (especially because they did an awesome job already), but because I’d rather focus on how you get your data on a map.  I’m going to focus on two things specifically:  adding a pushpin to a map, and adding custom shapes to a map.

Adding a Pushpin to the map

In C#, adding a pushpin to as simple as creating a new Pushpin object, setting its Location, and adding it to the map.  The same is true of doing it in XAML.  Obviously, XAML provides you some shortcuts, but neither example is very difficult.


<map:Pushpin Location="40.1449, -82.9754" FontSize="30" Background="Orange" Content="1" />


Pushpin pushpin = new Pushpin();
Location location = new Location();
location.Latitude = 40.1449;
location.Longitude = -82.9754;
pushpin.Location = location;
pushpin.Background = new SolidColorBrush(Colors.Orange);
pushpin.Content = "1";
pushpin.FontSize = 30;

The above example, in either case, will add a pushpin to my office, found at 8800 Lyra Drive, Columbus, OH.  Here’s what it looks like in my application:


If you’re wondering how you can convert your address data to latitude/longitude, check out my post from the 31 Days of Silverlight.  It specifically covers Geocoding addresses, and is still exactly what you’re going to want to do in your phone application.

Adding Custom XAML to a map

Another little control we have in the Map assembly is the MapPolygon.  By supplying it with a list of Locations, it will draw a custom polygon shape on your Map, which stays in place even as the user scrolls and pans around the map.  It is tied to specific longitude and latitude values, making it very easy to delineate countries, states, regions, or even parking lots, if that’s what your app is for.  Here’s how to do it:


<map:MapPolygon Fill="Purple" Stroke="White" Opacity=".7" Locations="40.1449,-82.9754 40.1449,-12.9754 10.1449,-82.9754" />


MapPolygon mapPolygon = new MapPolygon();
mapPolygon.Fill = new SolidColorBrush(Colors.Purple);
mapPolygon.Stroke = new SolidColorBrush(Colors.White);
mapPolygon.Opacity = .7;
LocationCollection locations = new LocationCollection();
Location location = new Location();
location.Latitude = 40.1449;
location.Longitude = -82.9754;
Location location1 = new Location();
location1.Latitude = 40.1449;
location1.Longitude = -12.9754;
Location location2 = new Location();
location1.Latitude = 10.1449;
location1.Longitude = -82.9754;
mapPolygon.Locations = locations;


So there you have it.  We’ve now added a Pushpin and a custom polygon overlay to our map.  Make sure to check the Bing Maps Silverlight Control Interactive SDKfor tons more you can do with this awesome control.  (Screenshot of the MapPolygon is below.)


Download the Code

In this sample code, you’ll find examples for adding a pushpin as well as a polygonal shape to your map in both XAML and C#.  You don’t need both, so pick one or the other, depending on your needs.


31 Days of Windows Phone | Day #19: Push Notifications

This post is Day #19 in a series called the 31 Days of Windows Phone.

Yesterday, I wrote about the WebBrowser control, and how to leverage it in your applications.  Today, we’re going to talk about, quite possibly, the most important topic in this series: Push Notifications.

If you’re not familiar with the concept of Push Notifications, it’s pretty simple: instead of forcing your application to check the server for new data every few minutes, your server has the ability to tell your phone when there’s new data.

Why Use Push Notifications?

For one, you’ll save your user’s battery.  Calling back to a server to check for data takes power, and on a phone, power is an absolute scarcity.  You’ll never have enough, and no matter how long your battery lasts, avoiding push notifications will only make that time shorter.

Secondly, you can leverage push notifications to let your user know that something interesting is happening with your application, even if it’s not running.  You can alert the user that they should open your application to interact with whatever it is you needed to tell them.

The Push Notification Process

So that you understand all of the code I’m about to throw at you, I thought it might be a good idea to explain exactly what is happening in this process.

  1. The first time a user runs your application on their phone, the app will call out to Microsoft’s Push Notification service, requesting a custom URI for communications purposes.
  2. When an event happens on your web service, you should pass messages to that URI (with a specific payload), and the Push Notification services will deliver that data to your user’s phone, in the form of a Live Tile update, a Toast notification, or as actual data to your application.

This article is going to focus on the “how” of each of the above bullet points.  If you want to see an example that you can build step-by-step, check out the Windows Phone Developer Training Kit.  It’s got an outstanding Push Notification tutorial that you can use.

Retrieving a Custom URI from the Push Notification Service

Thankfully, they’ve made this part incredibly simple.  We need to use the Microsoft.Phone.Notification assembly, but otherwise, we can get a custom URI from the Push Notification service (PNS) in about 10 lines of code.  First, we’ll create a new HttpNotificationChannel.  This will automatically communicate with the PNS (on a seperate thread), and we’ll create an event to capture what the service returns.

HttpNotificationChannel channel;

void GetPushChannel()
	channel = new HttpNotificationChannel("BLANKENSOFT_" + DateTime.Now.Ticks.ToString());
	channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);

void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
		URIBlock.Text = channel.ChannelUri.ToString();

The custom URI I received from this example was (it’s small so it fits):


Once you have the URI, you’ll want to save that to your web service.  It’s your web service that will be initiating the messages to the phone, and we can do that one of three ways: Tile notification, Toast notification, or a Raw notification.  We’ll cover each of these in the next section.

Different Messages For Different Needs

Earlier I mentioned that there are three different types of messages you can send to a phone.  Here’s a quick outline of what those are:

Raw Notification – Raw notifications are used when your application is actually running on the device.  This allows you to update your interface “live” as the user is using it.

Toast Notification – This message will be received regardless of whether your application is running or not, but popping toast messages while your app is running might be a little annoying.  I’ll demonstrate this example below.  Toast WILL NOT also update your application’s data.  You still need to pass a Raw Notification to make this happen.

Tile Notification – If your application is pinned to the user’s Start screen, you can update the Tile for your application.  You can change the background image, as well as an integer from 0-99.

Sending a Toast Notification

Once we’ve got our Push URI, it’s just a matter of composing an HTTP message, and sending it to that URI.  Here’s an example in code:

HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channel.ChannelUri.ToString());
sendNotificationRequest.Method = "POST";
//Indicate that you'll send toast notifications!
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
if (string.IsNullOrEmpty(txtMessage.Text)) return;
//Create xml envelope
string data = "X-WindowsPhone-Target: toastrnrn" +
		"<?xml version='1.0' encoding='utf-8'?>" + 
		"<wp:Notification xmlns:wp='WPNotification'>" + 
		"<wp:Toast>" + 
		"<wp:Text1>{0}</wp:Text1>" +
		"</wp:Toast>" + 
//Wrap custom data into envelope
string message = string.Format(data, txtMessage.Text);
byte[] notificationMessage = Encoding.Default.GetBytes(message);
// Set Content Length
sendNotificationRequest.ContentLength = notificationMessage.Length;
//Push data to stream
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
	requestStream.Write(notificationMessage, 0, notificationMessage.Length);
//Get reponse for message sending
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

As you can see, the code for this portion can get long and convoluted quickly.  My recommendation is to spend some time going through the Windows Phone Developer Training Kit, and specifically walking through the Push Notification example.

It’s an outstanding example of how push notifications work (from front to back), and shows you just how powerful these updates can be to keep your application in front of your user’s eyes.

Download The Code

For today’s example, downloading the above code won’t do you much good without all of the context that it requires.  Today’s download is actually the final example from the Push Notification demo in the Windows Phone Developer Training Kit.  Enjoy!


31 Days of Windows Phone | Day #18: WebBrowser Control

This post is Day #18 in a series called the 31 Days of Windows Phone.

For the past two days, we have been talking about different display controls: Panorama and Pivot.  Today, we’re going to focus on another important control, the WebBrowser.

What does the WebBrowser control do?

If it’s not obvious, the WebBrowser control lets your user browse a specific web page.  But it’s not a full browser, because it doesn’t come with an address bar, favorites, tabs, etc.  It’s probably best think of it as an <iframe> from the HTML world, but with a much richer interface.  You’ll discover that pinch (and double-tap) to zoom, as well as panning and scrolling are automatically built in, without any work on your part.

One other awesome feature of this control is that it can load both local and web content.  This means that if I’ve got a ton of HTML assets (documentation, maybe?), I don’t have to re-create all of that content again for my application.  Instead, I can embed those HTML pages in my application, and load them locally on the phone rather than relying on a potentially spotty data connection.

Loading local HTML content in the WebBrowser control

Since I brought it up, I should probably show you how to so it too, right?  First, you need some local HTML files added to your project.  I have added two for demonstration purposes, but this could be hundreds if you needed that.


After that, I rigged up two buttons to load these individual files.  Again, there are many different approaches you can take to this, but I want to make sure that you walk away from this article confident you can load local content, and I’ll leave it to you to find the best way to leverage my examples.  In my code below, there are two additional references (“using statements”) you’ll need to make.  They are:

using System.IO;
using Microsoft.Xna.Framework;

You may be thinking, “XNA?  Really?”  I’m here to tell you that on Day #30 of this series, I’m going to show you just how powerful the XNA namespaces can truly be.  For now, just trust me.  In my button event handlers, I have two lines of code.  The first loads the contents of the HTML into a StreamReader, and the second line loads the contents of the HTML file into the WebBrowser control using its .NavigateToString() method.  Here’s what it looks like:

StreamReader reader = new StreamReader(TitleContainer.OpenStream("html/wp7wiki.html"));

If you’d like to read up on the System.Xna.Framework, or the TitleContainer class, click on their respective links in this sentence.  Using this simple example above, however, will allow you to load local HTML content directly into your WebBrowser control.

Scripting is disabled by default

In case you’re planning on loading an HTML page that contains some JavaScript, you should know that scripting is disabled in the WebBrowser control by default.  It’s simple to turn back on (or even toggle) using the IsScriptEnabled property of the control.  Here’s two quick examples:


<phone:WebBrowser x:Name="Browser" IsScriptEnabled="True" />


Browser.IsScriptEnabled = true;

Talking Between Your App and Script

If you want to be able to leverage the scripting that you have on your HTML content, it’s pretty easy to do.  If you want to pass data from your app to the page, you can simply use the .InvokeScript() method, passing the name of the script method, followed by any arguments the method expects:

string returnValue = (string)Browser.InvokeScript("getText", "http://jeffblankenburg.com", "rocks", "awesomely");

To do the opposite, you need one extra step: an event handler for when the a script wants to talk to you.  To do this, I set up the .ScriptNotify event handler, and grab the string it passes to me (in my case, it’s a URL that I will navigate to).  The NotifyEventArgs.Value contains the value the script passes me:

void Browser_ScriptNotify(object sender, NotifyEventArgs e)
	Browser.Navigate(new Uri(e.Value, UriKind.Absolute));

Once you’ve got that set up, it’s one simple line of Javascript to make that event fire:


Because you’re loading network content most of the time, you need to let your user that something is happening.  This seems like a perfect opportunity to talk about the ProgressBar, and how we can use it to show the user that we’re loading something, and that they should be patient.

Using the ProgressBar with the WebBrowser control

There is TONS of information about the ProgressBar at MSDN, so I’m not going to cover all of it.  What I will do, however, is show you how to create a simple “waiting” animation for your user, so that they know you’re loading content.  By using the ProgressBar in the example below, we just need to set IsIndeterminate = true, and show and hide it at the appropriate times.  Here’s the XAML and C# I use to do this:


<ProgressBar Foreground="Orange" x:Name="ProgBar" Visibility="Collapsed" IsIndeterminate="True" Height="4" HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" Width="460" />


void Browser_Navigating(object sender, NavigatingEventArgs e)
	ProgBar.Visibility = Visibility.Visible;

void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
	ProgBar.Visibility = Visibility.Collapsed;

You’ll see that I can use the Navigated and Navigating event handlers to show the ProgressBar to the user at the appropriate times, and hide it otherwise.  Check out the code sample below to see all of this in action!

Download the Code

Today we covered the WebBrowser control in depth, but as with all of my examples, until you can take some working code apart, and see how it works, it’s hard to fully realize what you’re working with.  So do it!  Download this example, and figure out how to add it to your project.