Welcome to Jeff Fansler's Blog

I've spent many years in the computer industry. I've worked in labs installing software, building computers, setting up networks, and teaching people how to use a mouse. I've worked as a developer building business applications and products. I've worked as a manager building teams and processes. In the end I've ventured on building a company which allows me to do a little of everything. This blog is where I talk about what I've learned during my journey

 

I recently attended a session at CodeMash 2011 called Mobile Smackdown. During this session Jeff Blankenburg (WP7), Chris Judd (Android), and Dan Steinberg(iPhone) set out to create a twitter application in 15 minutes or less. I thought it was a great session. I found it very interesting to see how the same application was implemented in each platform. In the session Dan was the only one to finish the application within the time limit.

Once I got home, I was curious to see how hard it would be to create this application in 15 minutes. I also thought others may find this interesting, so I created a screen cast of my attempt. I wrote the application once without worrying about time to make sure I had everything down. I then went through it once as fast as I could, but I did not run a timer. The attempt in the screen cast is my 3rd attempt.

Kudos go out to Jeff, Chris, and Dan for an entertaining and informative session. 

The video content presented here requires JavaScript to be enabled and the latest version of the Adobe Flash Player. If you are using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Adobe Flash Player by downloading here.


Someone asked me the other day, “Why are you developing for Windows Phone 7?” We had an interesting discussion, but for me it boiled down to three main reasons. Here they are:

The User Experience

The core user experience on the phone is very clean. The information you need is where it should be, everything just works. Using the phone is a seamless transition between applications. I don’t even like using the word applications, because it’s more like functionality. It feels like one app (a phone) with a gazillion features added. Users like simple and Windows Phone 7 is simple.

The Marketplace

The concept of a marketplace isn’t new. Microsoft, however, has solved many of the problems I have had with other marketplaces. It’s closed in an open way. What I mean by this is that only applications that pass Microsoft’s criteria will be accepted, but the criteria that you need to meet are clear. This allows for an ecosystem where users can trust the applications they install and developers can feel confident that there application will be accepted before they start developing it.

Ease of Development

The last reason we have decided to develop for WP7 is the ease of development. Microsoft has long been a leader when it comes to development tools and technology. By using existing frameworks with Silverlight and XNA Microsoft has made our investment in these technologies even more valuable. Instead of there being a steep learning curve on a new platform, we have been immediately productive.

Community

I know I said 3 reasons, so consider this one a bonus. The community surrounding Microsoft technologies including Windows Phone 7 is phenomenal. This community is created by developers who are always willing to spend extra time to help out their peers. This community is strongly encouraged by Microsoft and is one of the main reasons we continue to develop using many Microsoft technologies including Windows Phone 7. If you don’t already, I encourage you to find your local user group and attend meetings. Find out what other developers are doing through twitter, blogs, and other forums.


Along with the release bits for Windows Phone 7 came a new control called Pivot.  Pivot allows you to define Pivot Items that the user can scroll through with a swipe of their finger to the left or right. The pivot control looks like this:

Pivot

In this case, the pivot has two pivot items, requests (index 0) and tags (index 1). There are several posts in the intrawebs that explain how to use the pivot control.  It’s pretty easy.  One gotcha to think about when using the pivot is what happens if your application is interrupted (phone call, windows button, etc).  When the user navigates back to your app with the back button, the pivot will display the first pivot item. I don’t like that.  I want the user to go back exactly where they were. They should see the same pivot item that they were looking at when they navigated away from your app. Here’s how.

This isn’t a hard problem to solve.  All we want to do is save the state of the selected index off the pivot control.  Fortunately the smart guys at MS thought of this for us. We can use the PhoneApplicationService.Current.State dictionary to store the selected index when the phone navigates away from our app. Here’s the code:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{            
    var state = PhoneApplicationService.Current.State;

    if (state.ContainsKey("SelectedPivotIndex"))
    {
        state.Remove("SelectedPivotIndex");
    }

    state.Add("SelectedPivotIndex", pivot.SelectedIndex);
}

Now all we have to do is read in that state when we navigate to the page:

protected override void  OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{            
    var state = PhoneApplicationService.Current.State;

    if (state.ContainsKey("SelectedPivotIndex"))
    {
        pivot.SelectedIndex = (int)state["SelectedPivotIndex"];
        state.Remove("SelectedPivotIndex");
    }

    base.OnNavigatedTo(e);
}

I know, easy, right?


As promised, here’s my post on launchers and choosers.  There is a lot of information out there on this topic. I’m adding to it for my own benefit. The two sources that I pulled most of my information from were the 3 part post from Yochay located here: Part 1, Part 2, Part 3, and the WP7 Training Kit Launchers and Choosers Lab.

What are Launchers and Choosers

A pretty common scenario for a phone application is to utilize the functionality that exists on the phone.  I’m talking about features like accessing contact data, sending emails and texts, dialing a phone number, and searching the web.  All of these features are part of the phone and it’s nice to be able to access these features within your own applications.  As a 3rd party application developer you do not have access to these features directly. You have to use Microsots API’s to access them.  These API’s are called launchers and choosers. The difference between a launcher and a chooser is simply that choosers return data. The launchers and choosers are covered under the Windows.Phone.Tasks Namespace. You can see the list from the API docs.

Using Launchers

Launchers are pretty simple.  You create a new instance of the launcher you want to use, set any properties, and call the Show() method. Here’s an example:

var task = new WebBrowserTask() {URL = "http://www.ThisIsFanzoo.com"};
task.Show();

That’s really all there is to launchers.

Using Choosers

Choosers are similar but a little more difficult.  You have to create a new instance of the chooser and set any properties just like the launcher.  Unlike the launcher, you have to give your chooser a way to return data.  This is done using the choosers Completed event. I found this to be interesting.  If you remember my last post, I said that no matter what, if your application is not on the screen then it is terminated.  Well, when you show a chooser, your app isn’t on the screen.  If your app is terminated, how is the event going to fire when the chooser is done?  This is a gotcha that I encountered.  When I started writing my first sample, I created the chooser and wired up to the completed event all in my button click event handler.  It took me a while to figure out why the completed event wouldn’t fire when control returned to my application.  After playing for a while, I realized that when my application was terminated, so was the event handler. To get around this, I created my choosers in the class scope and initialized them in the page constructor.  This way, when my app is activated the constructor runs, wires up to the completed event and then WP7 magically fires that event. Here’s what the code looks like:

private PhoneNumberChooserTask _choosePhoneNumberTask;

public Choosers()
{
    InitializeComponent();
    _choosePhoneNumberTask = new PhoneNumberChooserTask();
    _choosePhoneNumberTask.Completed += new EventHandler<PhoneNumberResult>(ChoosePhoneNumberTaskCompleted);
}

Let’s also take a look at the completed event handler. In this example I am taking the chosen phone number and sending a text message with it:

private void ChoosePhoneNumberTaskCompleted(object sender, PhoneNumberResult e)
{
    new SmsComposeTask() {Body = "I Like Windows Phone 7", To = e.PhoneNumber}.Show();            
}

I hope you found this post helpful.  If you’d like to see the source code, you can get it here.


How’s that for a title.  At least it’s descriptive. As it says, this post was going to be on Launchers and Choosers in Windows Phone 7.  After struggling a bit I realized that before I could understand exactly how the Choosers were working, I needed to understand the application execution model.  So here we are, the WP7 application execution model.

Every post I’ve read about the WP7 execution model starts out talking about the lack of multi-tasking and this post will be no different.  WP7 does not support multi-tasking.   This point has caused some controversy. Old versions of the Windows phone supported multi-tasking.  So does Android and iPhone (with iOS4). The rest of this paragraph is my opinion on the multi-tasking issue. Unless MS can get multi-tasking down perfect, I’m glad it is not included. So why doesn’t MS just copy Android’s model?  Because it sucks.  If my Mom has an Android phone and I have to explain to her how to kill an application because it’s draining her battery, then the model is broken.  I believe Steve Jobs said something like, “If you have to manually kill an application, you are doing it wrong.” As soon as I see some flavor of a task manager on a phone I cringe. I don’t want WP7 to be a geek only phone.  I want it in as many hands as possible, and I want it to just work. So why not follow Apples model.  They have done a better job.  It’s simple.  As a user I don’t have to worry about closing an app.  That said, since I’ve upgraded my iPhone 3gs to iOS4, it’s been much more buggy then it used to be.  In my naive mind, I blame this on the multi-tasking. I have seen the phone become more responsive by going through my app history and clearing it out.  If I have to do that, it’s the same as a task manager, it just looks nicer. I may be the only one, but until MS can get mutli-tasking perfected, I don’t want to see it on the phone. That’s my opinion, take it for what it’s worth.  Let’s get into the details of what this means.

Without multi-tasking this means that any time your app is not on the screen, it is terminated. There are lots of reasons for your application to leave the screen.  A few examples include the user hitting the back button beyond the start of your application, hitting the windows, using a chooser to select a phone number from a list of contacts, etc.  All of these examples will terminate your application.  There are four important methods that fire as your application loads and is terminated.  Each of these methods are defined in the App.xaml.cs class of your application. Let’s look at each one and understand what they do.

Application_Launching - The launching method fires when you application loads a new instance.  This is the method that would fire the first time you run your app.  Also, if you hit the Windows button, go to the application list and launch your application this method will fire.  This method indicates that you are launching a brand new instance of your application.

Application_Activated - Activated and launching are mutually exclusive. Both will not execute, only one.  Activated is run whenyour application is loaded, but it’s not a new instance.  This was confusing to me, because instance isn’t really the correct word. The applications are always a new “instance” because there is no multi-tasking. The difference is how your application is launched.  If activated is called, it means that your app was running, then was terminated to do something else, and then was launched again.  An example of this would be using the Windows key, launching a different application, then using the back button until your application is on the screen again.  A better example is when you use a chooser to select a phone number.  When the chooser returns with a result, application activated will be called.

Application_Deactivated – The opposite of  Activated, Deactivated is called when you might come back to the application. If a phone call comes in or if you launch a chooser to select an email address deactivated would be called.

Application_Closing - Closing happens when you aren’t going to come back to your application.  Mainly this occurs when you use the back button to go past the start of your application.

I can’t stress enough that any time your application is not on the screen, it is terminated.  You can use these events to handle the storage and loading of data when this happens. There are several ways to store data but two very common ones.  One is in IsolatedStorage.  You should use IsolatedStorage any time you need to store data more permanently.  The other common option is in the PhoneApplicationService.Current.State dictionary.  Use the dictionary when it’s nice if the data was stored, but not critical.  A common use here is to save the values from a form that the user entered so that when they come back, they don’t have to start over with a blank screen.  Keep in mind that your data is not guaranteed to remain in the State dictionary.

If you want to learn more about the execution model there is a great three part post from  Yochay.  Here are the links: Part 1, Part 2, Part 3.

My next blog post will be on Launchers and Choosers.  Before I get to that, here’s a quick tip if you are getting started with them.  When you launch your chooser and then see a blank screen after you pick something, hit F5 in Visual Studio.  This is a feature.  Notice that the VS debugger detaches when you launch the chooser.  The blank screen is your opening to re-attach the debugger so you can continue debugging your app.  It took me a while to figure this out so hopefully this helps.


This is going to be a short post.  If you search the interwebs for information on navigation in WP7 you will find plenty of information.  I’m adding to that information mainly for my own good.  Hopefully you will get some use out of it as well.

The first point to make here is that navigating in WP7 uses the System.Windows.Navigation API.  This is not a new API.  I believe it was introduced with Silverlight 3. If you are already comfortable using this API then you are all set. If you are like me and haven’t worked with a lot of Silverlight then it’s new.

Navigation is simply the act of going from one xaml page to another.  I’m a web developer and this is very much the same as moving from one html page to another. In fact if you are comfortable with how navigation works in the web world, you will be comfortable here. In order to navigate from one xaml page to another, all you need to do is call the Navigate method off of the NavigationService class with the URI of the page you want to go to.  Here’s the code:

private void BtnNextPageClick(object sender, EventArgs e)
{
    NavigationService.Navigate(new Uri("/Page3.xaml", UriKind.Relative));            
}

That’s the meat of navigation. As I said, this is going to be a short post. 

Ok, well, I guess there are a few other items to cover. Let’s cover the rest in a Q&A style:

How do you go back to the previous page?

Good question, I’m glad you asked.  All Windows Phone 7 devices will have a hardware back button.  If the user clicks it, they go to the previous page.  If there isn’t a previous page, your app closes and it goes to whatever was running before your app launched. Some of you may be tempted to add a button to your screen to give your users another way to go back.  I honestly can see no good reason to do this.  I remember when some web pages would add back buttons to them and it’s just pointless.  It serves to confuse the user.  Let them use the back button on the device.  Any time they ever want to go back, they know where to go.

How do you pass data from one page to another?

Oh, another great question.  As I mentioned earlier, if you are comfortable with navigation on the web, you’ll be comfortable here.  To pass data you use a query string.  A simple name/value pair string.  It starts with a “?” and each value is separated by an “&”. Here’s an example:

private void BtnNextPageClick(object sender, EventArgs e)
{
    NavigationService.Navigate(new Uri("/Page2.xaml?Message=Main Page Says Hi!", UriKind.Relative));
}

In this call to Navigate I am passing in a property called “Message” that has a value of “Main Page Says Hi”.

Hmm, that’s cool, but how do you consume that data?

Boy, you guys are on a roll with the great questions. Let me start by showing you a potential gotcha. You may be tempted to use Loaded event off of the page to read in the value from the query string and then consume it.  Don’t do this.  The Loaded event isn’t guaranteed to run every time your page shows on the screen.  It only runs when your page is loaded, and it could already be loaded.  Instead, override the OnNavigatedTo method.  Reading the actual value is pretty simple.  The QueryString dictionary is  part of the NavigationContext class. To read it you should use the TryGetValue method off of the QueryString dictionary.  The code looks like this:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var message = string.Empty;

    if (NavigationContext.QueryString.TryGetValue("Message", out message))
    {
        MessageBox.Show(message);
    }
}

So what about passing complex data types? What if I want to pass a person?

Well, I’m open to other ideas here, but I will give my opinion.  Don’t do it.  Each page or view should only know about the data that it needs to render. When navigating to a new page, it’s because you want to see different data.  That means the new page should only care about the data it needs which will be different then the page you are navigating from.  Normally I pass ID’s around.  As an example,let’s say I want to have a page that displays summary information about a player on the Detroit Red Wings.  I then want to be able to navigate to a page that shows me the history of teams the player has played for.  I would create a hyperlink or button on the summary page to navigate to the summary page.  I would pass along with that the ID of the player.  On the summary page I would lookup the history information only for that player and display it.  This question could turn into a much larger topic on Model-View-ViewModel and such so I will leave it at that. If you are interested in me covering that topic at some point, leave me a comment.

Thanks for all the great questions and have a great day!


The application bar is a menu system used in WP7. MS has built this into the API’s so that applications can maintain a consistent look and feel. This image shows what the application bar looks like when expanded.

WP7AppBar

 

There are a few components in play here.  The icons in the circles are called Icon Buttons. In this example there are three; last, next, and favorite. WP7 limits you to only having a maximum of 4 icon buttons.  If you try to add more an exception will be thrown when your application starts.  Normally the text for these icons will not appear.  It will only show when the menu is expanded as shown in the screen shot. As you would expect you can hook up to the click event on these icon buttons to take action when the user clicks.

The ellipsis in the upper right corner of the application bar is used to expand and collapse the application bar.  As I mentioned, when expanded the text for each icon will display.  In addition to that, WP7 will display any menu items you have defined. In the screen shot the text “load my favorite picture” is a menu item.  The menu item also exposes the click event so you can take action when the user clicks. There is no maximum to the number of menu items you can add.  WP7 will display the first few items and then you can scroll up and down to see the rest. In my experience WP7 showed about 5 items.

Adding an application bar to your application is simple.  All you have to do is add XAML that looks something like this:

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Opacity=".5">
        <shell:ApplicationBarIconButton x:Name="btnLast" IconUri="/Images/appbar.back.rest.png" Text="Last" Click="BtnLastClick"></shell:ApplicationBarIconButton>
        <shell:ApplicationBarIconButton x:Name="btnNext" IconUri="/Images/appbar.next.rest.png" Text="Next" Click="BtnNextClick"></shell:ApplicationBarIconButton>
        <shell:ApplicationBarIconButton x:Name="btnMarkFavorite" IconUri="/Images/appbar.favs.rest.png" Text="Favorite" Click="BtnMarkFavoriteClick"></shell:ApplicationBarIconButton>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem x:Name="mnuLoadFavorite" Text="Load My Favorite Picture" Click="MnuLoadFavoriteClick"></shell:ApplicationBarMenuItem>            
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Notice I’m setting the IsVisible and IsMenuEnabled properties to true on the ApplicationBar.  I am also setting the Opacity to .5. It’s important to note that If you set the opacity to a value less than 1 then the application screen size will be the entire screen.  If you set the Opacity to 1 then the application screen size will be reduced by the size of the application bar.

If you are interested in reviewing this code, you can download the sample application here.


When I started digging into the WP7 push notification system I thought it would be pretty quick to learn.  On the surface it’s not terribly complicated.  My phone app tells a service that it wants to receive notifications and the service sends them.  In the end, it pretty much is that simple. Getting there, however, was more difficult then it needed to be.  This is mainly due to the beta nature of WP7.  Working on beta platforms shows how poorly the web handles finding the most relevant information. There are lots of articles out there that explain the messaging system.  I’m sure I could look harder, but the few samples and demos that I reviewed didn’t work out of the gate.  I had to review several and piece together information from different sources to get a working demo.  The good news in doing this, is I now have a pretty good understanding of how the notification system works. This article is my attempt at explaining what I’ve learned.  When reading this, keep in mind that this is based on the first beta drop of the WP7 dev tools. I will try hard to keep the post updated as the API’s become more final.

What Is The WP7 Push Notification System And Why Do I Need It?

Push notifications aren’t new to the smart phone industry.  The concept is simple.  Here’s a scenario:

I installed an application on my phone.  I am interested in the content of this application even when the application is not running.  If something worthy of getting my attention happens I would like the application to alert me of it.  Again, even when it’s not running.

How about a more concrete scenario:

I am signed up for Twitter.  I want to be alerted whenever a new tweet arrives that references my name.  I have a twitter app on my phone that I can manually check at any time.  That’s great, but I want my phone to notify me when I’m not running my app.  Push notifications can do that.

Kindly MS realized that this is an important scenario to solve and have included a solution with the WP7 API’s.

Push Notification Architecture

There are three important players in the WP7 notification scenario; the phone, the application service (owned by the app developer), and the Microsoft push notification service. In order to get up and running with sending notifications the following must occur:

  1. Run the application for the first time and subscribe to notifications from the the applications notification service.
  2. On each run of the application register to receive the notifications.
  3. Send notifications from the application service to the Microsoft push notification service.
  4. Receive notifications (when the application is running) from the Microsoft push notification service.

That’s not to complicated and makes sense.  Let’s break down each step and look at the code necessary to make it happen.

Subscribing with The Notification Service

In this part of the flow there are two components involved.  The phone application and the application notification service. Let’s start by looking at the phone.

In order to subscribe to the notifications you need two pieces of information; a unique identifier for the phone and a URI. The unique identifier is easy enough.  When your app loads, generate a GUID and store it in isolated storage.  If you’ve already stored it (running the app for the second time) then just load it from isolated storage.

if (IsolatedStorageSettings.ApplicationSettings.Contains("DeviceId"))
{
    _deviceId = (Guid)IsolatedStorageSettings.ApplicationSettings["DeviceId"];
}
else
{
    _deviceId = Guid.NewGuid();
    IsolatedStorageSettings.ApplicationSettings["DeviceId"] = _deviceId;
}

Ok, so we have our unique identifier, what about the URI? This URI is what the WP7 push notification service will use to send a notification to the device. To generate that we need to look at the notification API and specifically at Channels.  Channels are objects that allow you to possibly subscribe to multiple notification content.  For example, if I wanted to subscribe to scores for all NHL games, and also to all MLS games. I could use two separate channels to cover that content and the device could decide which to subscribe to.  To keep this example simple, we are only going to use one channel. Each channel you create needs a unique name.  Once a channel is created, you can retrieve it instead of creating it again.  Here is the code that does this:

private void SetupNotificationChannel()
{
    _channel = HttpNotificationChannel.Find(ChannelName);

    if (_channel == null)
    {
        _channel = new HttpNotificationChannel(ChannelName);
        _channel.ChannelUriUpdated += ChannelUriUpdated;
        _channel.ErrorOccurred += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ErrorOccurred(e));
        _channel.Open();
    }
    else
    {
        RegisterForNotifications();
    }
}

Now that we have a channel setup we can get our URI and subscribe with our application service.  The Channel class has an attribute called ChannelUri. In order to subscribe we can call into our application service like this:

private void RegisterWithNotificationService()
{
    var svc = new NotificationService.NotificationServiceClient();

    svc.SubscribeCompleted += (s, e) =>
    {
        if (e.Error != null)
        {
            Debug.WriteLine("Error registering with notification service");
        }
    };

    svc.SubscribeAsync(_deviceId, _channel.ChannelUri.ToString());
}

 

Now is a good time to talk about the second component involved; the application notification service.  In my sample, my service exposes a method called Subscribe. The interface looks like this:

[OperationContract]
void Subscribe(Guid clientID, string uri);

In order to get a simple notification running, not much has to happen here.  I will mention though that depending on your scenario you could need to do some more complex work here.  This is all up to you as the application developer.  Mainly I’m talking about receiving preferences from the application user.  Again, we will keep this simple since we are just trying to learn the notification system. All I’m going to do in the Subscribe method is store the clientID and URI. For simplicity I’m going to store this in a static dictionary. This would be a horrible idea for a real system since you would loose all your subscribers as soon as the application restarts, but it will work for our example. Here’s the implementation of our interface I showed above:

private static Dictionary<Guid, Uri> _clientUris = new Dictionary<Guid, Uri>();

public void Subscribe(Guid clientID, string uri)
{
    if (_clientUris.ContainsKey(clientID))
    {
        _clientUris[clientID] = new Uri(uri);
    }

    else
    {
        _clientUris.Add(clientID, new Uri(uri));
    }
}

That’s it.  We are now registered. To summarize, the phone created a unique identifier and a channel.  It then sent that unique identifier and the channel URI to the application service in order to subscribe to notifications. The application service stored the unique ID and the URI for future use. Once we are subscribed, we need to manage what happens when a notification is sent.

Registering to Handle Notification Events

Registering is simply the act of wiring up to some events off your channel in order to handle notifications that come in when your application is running and also telling the channel how to handle notifications when your application is not running.This is a good time to talk about the different types of notifications that the WP7 notification system supports. There are three notification types:

  1. Toast Notifications – When the application is not running, these will slide in on the screen for a few seconds and then slide out. If the user taps the notification your application will launch. When a toast notification comes in and the application is running, the application decides what to do with it.
  2. Raw Notifications – When the application is not running, these notifications aren’t used. Only when the application is running can you receive these notifications and do something with the data.  As the name suggests, the data here is raw.  It can be whatever you want it to be as long as it is under the size limit.
  3. Tile Notifications – When the application is not running and if the application is pinned to the start page, these notifications will be handled by the phone.  There are three items you can alter with a tile notification; the tile image, the tile number (think un-read email count), and the title.  There is no way to receive tile notifications when you application is running.

Based on the three notification types, let’s look at how you register. You would want to take these actions every time your application is executed. If you were paying attention earlier you noticed that in the SetupNotificationChannel method I wired up to an event off the Channel class called ChannelUriUpdated. This event fires any time the Uri is updated. I haven’t found much more information then that, but based on experience, it is fired when the channel is first created. In the event handler I need to setup a few things on the channel. There are two key tasks the sample code is doing.  First it tells the channel to “bind” to tile notifications and also tells it which URI’s are valid for loading external tile images. It then tells the channel that it would like to bind to toast notification. Binding basically tells WP7 device to handle these notifications when they are sent and the application is not running. Here’s the code:

private void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
    _channel = HttpNotificationChannel.Find(ChannelName);

    if (!_channel.IsShellTileBound)
    {
        var uris = new Collection<Uri> { new Uri("http://www.thisisfanzoo.com") };
        _channel.BindToShellTile(uris);
    }

    if (!_channel.IsShellToastBound)
    {
        _channel.BindToShellToast();
    }
        
    RegisterForNotifications();
}

Now that we’ve told the phone what to do when we aren’t running, we now need to wire up to the appropriate events when we are running. One item to note here, is that none of these events come in on the UI thread.  That means you need to use BeginInvoke magic to get back to the UI thread (assuming you want to update your UI). There are three events that are important here; HttpNotificationReceived, ShellToastNotificationReceived, and ErrorOccurred. Here’s the code to wire up:

private void RegisterForNotifications()
{
    RegisterWithNotificationService();
    _channel.ShellToastNotificationReceived += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() =>  ToastReceived(e));
    _channel.HttpNotificationReceived += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => HttpNotificationReceived(e));
    _channel.ErrorOccurred += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => ErrorOccurred(e));
}

Ok, let’s review. So far we have told our application notification service that we exist, we have told the phone to handle notifications when the application isn’t running, and we have event handlers to handle notifications when the application is running.  Now we need to send some notifications and see how to handle them. We will start with sending notifications.

Sending Push Notifications from the Application Notification Service.

For learning and testing purposes I created a super simple WPF app to trigger each of the three types of notifications.  This application calls into the application notification service to do the actual delivery of the notifications. Let’s take a quick look at what the WPF application is doing.  First, here’s the code to send Toast:

private void BtnSendToastClick(object sender, RoutedEventArgs e)
{
    var svc = new NotificationService.NotificationServiceClient();
    svc.SendToast(txtToastTitle.Text, txtToastMessage.Text);
}

Here’s the code to send a Raw message:

private void BtnSendMessageClick(object sender, RoutedEventArgs e)
{
    var svc = new NotificationService.NotificationServiceClient();
    svc.SendRawNotification(txtMessage.Text);    
}

Here’s the code to send a Tile message:

private void BtnSendTileUpdateClick(object sender, RoutedEventArgs e)
{
    var svc = new NotificationService.NotificationServiceClient();
    var logoPath = string.Empty;

    switch (cmbImage.SelectedIndex)
    {
        case 0:
            logoPath = "/Images/logo2.png";
            break;
        case 1:
            logoPath = "/Images/logo3.png";
            break;
        case 2:
            logoPath = "http://www.thisisfanzoo.com/blog/samples/logo2.png";
            break;
    }

    int count;

    if(Int32.TryParse(txtTileCount.Text, out count))
    {
        svc.SendTileUpdate(txtTileTitle.Text, count, logoPath);    
    }
}

As you can see, this code is simple. There’s not much worth explaining here so let’s move on and look at the service.  The service has three methods, one for each notification type.  Here is the interface:

[OperationContract]
void SendToast(string title, string message);

[OperationContract]
void SendTileUpdate(string title, int count, string imageUrl);

[OperationContract]
void SendRawNotification(string message);

Well, that’s pretty straight forward. Let’s jump right into the implementations. We’ll start with toast:

public void SendToast(string title, string message)
{
    var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"WPNotification\">" +
           "<wp:Toast>" +
              "<wp:Text1>{0}</wp:Text1>" +
              "<wp:Text2>{1}</wp:Text2>" +
           "</wp:Toast>" +
        "</wp:Notification>";

    toastMessage = string.Format(toastMessage, title, message);

    var messageBytes = System.Text.Encoding.UTF8.GetBytes(toastMessage);

    foreach (var uri in _clientUris.Values)
    {
        SendMessage(uri, messageBytes, NotificationType.Toast);
    }
}

There’s a little more meat there so let’s talk about it.  First notice the toast XML.  This was a source of some pain when learning this because the XML has changed a bit.  Most examples I found on the intraweb are wrong. Fortunately MSDN is correct and so is this code (for now). So we generate some XML with our toast data, encode it into a byte array and then send it to each URI that has been subscribed.  I knew that URI would come in handy.  Sending the actual message is the same for all three notification types so I’ll talk about that last. The other two notifications types are very similar to this but let’s look at the code anyway. Here’s Tile notifications:

public void SendTileUpdate(string title, int count, string imageUrl)
{
    var tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"WPNotification\">" +
           "<wp:Tile>" +
              "<wp:BackgroundImage>{0}</wp:BackgroundImage>" +
              "<wp:Count>{1}</wp:Count>" +
              "<wp:Title>{2}</wp:Title>" +
           "</wp:Tile> " +
        "</wp:Notification>";

    tileMessage = string.Format(tileMessage, imageUrl, count, title);

    var messageBytes = System.Text.Encoding.UTF8.GetBytes(tileMessage);

    foreach (var uri in _clientUris.Values)
    {
        SendMessage(uri, messageBytes, NotificationType.Tile);
    }
}

 

There are three pieces of data that are sent in a Tile message. The count will be displayed over your tile and can be used to show the number of un-read messages that have been received.  The title will be used as the tiles title on the start screen. The background image is the path to the image you want to use for your tile.  This image can be a path to a local resource or to a remote resource.  If you are using a remote resource there are some restrictions on how fast the image needs to load, and you also need to specify which URI’s will be valid to load images from.  If you remember we did this earlier in the ChannelUriUpdated method.

Here are Raw notifications:

public void SendRawNotification(string message)
{            
    var messageBytes = Encoding.UTF8.GetBytes(message);

    foreach (var uri in _clientUris.Values)
    {
        SendMessage(uri, messageBytes, NotificationType.Raw);
    }            
}

Now that that makes sense, let’s look at how we actually send the notification to the notification service. To do this we are simply going to make an HTTP POST to the subscribers URI. We can also look at the response to that POST in order to get some useful information. Here’s the code:

private static void SendMessage(Uri uri, byte[] message, NotificationType notificationType)
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Http.Post;
    request.ContentType = "text/xml";
    request.ContentLength = message.Length;
    
    request.Headers.Add("X-MessageID", Guid.NewGuid().ToString());

    switch (notificationType)
    {
        case NotificationType.Toast:
            request.Headers["X-WindowsPhone-Target"] = "toast";
            request.Headers.Add("X-NotificationClass", ((int)BatchingInterval.ToastImmediately).ToString());
            break;
        case NotificationType.Tile:
            request.Headers["X-WindowsPhone-Target"] = "token";
            request.Headers.Add("X-NotificationClass", ((int)BatchingInterval.TileImmediately).ToString());
            break;
        default:
            request.Headers.Add("X-NotificationClass", ((int)BatchingInterval.RawImmediately).ToString());
            break;
    }

    using (var requestStream = request.GetRequestStream())
    {
        requestStream.Write(message, 0, message.Length);
    }
    try
    {
        var response = (HttpWebResponse)request.GetResponse();

        var notificationStatus = response.Headers["X-NotificationStatus"];
        var subscriptionStatus = response.Headers["X-SubscriptionStatus"];
        var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

        Debug.WriteLine(string.Format("Device Connection Status: {0}", deviceConnectionStatus));
        Debug.WriteLine(string.Format("Notification Status: {0}", notificationStatus));
        Debug.WriteLine(string.Format("Subscription Status: {0}", subscriptionStatus));
    }
    catch (WebException ex)
    {
        Debug.WriteLine(string.Format("ERROR: {0}", ex.Message));
    }
}

In the real world you’ll want to do something more significant with the response information then write it out to the debug console, but this is a sample. I’m pretty comfortable with web development so making a POST like this makes sense to me and I think the code is fairly self describing.  There are two headers that we are adding to our POST. X-WindowsPhone-Target defines the notification type.  If this header is not defined then it is a Raw notification. The X-NotificationClass defines when the service should send the notification.  I’ve used an enum here to simplify, here it is:

public enum BatchingInterval
{
    TileImmediately = 1,
    ToastImmediately = 2,
    RawImmediately = 3,
    TileWait450 = 11,
    ToastWait450 = 12,
    RawWait450 = 13,
    TileWait900 = 21,        
    ToastWait900 = 22,        
    RawWait900 = 23
}

Those wait values are in seconds (i.e.: ToastWait450 will send toast with a 450 second delay).  I’m not quite sure why there is a separate value for each notification type, but there is.

There are a couple significant headers in the response as well. X-NotificationStatus will tell you the status of the notification that was received by the MS Push Notification system.  Normally we are looking for a value of “Received". The X-SubscriptionStatus header will tell you what the status is of the subscription (sorry for the lame explanation). The expected value is “Active”. The X-DeviceConnectionStatus will tell you the connection status of the device (again, sorry for the lame explanation). We are looking for a value of “Connected”. You can find a good explanation of the possible values at the bottom of this page.

Ok, our notification is sent. The only part left is to look at how to handle the channel events on the phone if the application is running.

Handling Notifications When The Application Is Running

There are several scenarios on why you may want to handle notifications when the application is running.  I’ll leave specific ideas to your imagination.  There are two events that will fire from the channel class when a notification arrive.  They are the HttpNotificationReceived event and the ShellToastNotificationReceived event. As you can probably guess ShellToastNotificationRecevied is fired when a toast notification is sent to the device.  The HttpNotificationReceived is fired when a raw notification is sent. Let’s start by looking at the ShellToastNotificationReceived event:

private void ToastReceived(NotificationEventArgs e)
{
    lblMessage.Text = "Toast Message Received";
    txtMessage.Text = string.Format("Title:{0}\nMessage:{1}", e.Collection["wp:Text1"], e.Collection["wp:Text2"]);
    Debug.WriteLine("Toast Recevied:" + e.Collection["wp:Text1"] + ", " + e.Collection["wp:Text2"]);
}

I’m not doing anything fancy with the results here.  I’m just displaying the the toast data in a textbox and updating a label to indicate that a toast message was received.  Notice that both text values (text1 and text2) are in the NotificationEventArgs.Collection collection (that’s awkward naming).

Now let’s look at the HttpNotificationReceived event:

private void HttpNotificationReceived(HttpNotificationEventArgs e)
{
    var reader = new StreamReader(e.Notification.Body);
    var message = reader.ReadToEnd();
    Debug.WriteLine(string.Format("Raw notification received: {0}", message));
    lblMessage.Text = "Raw Message Received";
    txtMessage.Text = message;
    reader.Close();
}

In this case I am using a StreamReader to get the data out. This is a raw message.  The Body property could be anything (i.e.: Binary, xml, string, etc).  In this case I’m simply sending over a string and so we can use a StreamReader to get the string out.

Phew… this is a long post, but I think that covers most of what you will need to know when getting started with the WP7 Push notification system.  The sample application that I wrote is available here. If you want to jump right in and try it out, load the solution, and run the applications in the following order:

  1. Start Notifications.Service
  2. Start Notifications.Phone
  3. Start Notifications.Sender

Reminder, this is beta software. I’ve read about a bug where the phone emulator will have an issue getting notifications setup properly when it first loads.  I haven’t experienced this so maybe this has been fixed.  If you have trouble at first, let the emulator run for a few minutes and then try again.

I read a lot of articles in order to come up with this sample application and post so here are some links I used as reference:


Before I begin this post I want to be clear, although I have made some tweaks, using the Wiimote as accelerometer input was done by Bill Reiss. Thank you Bill for giving me something fun to play with.

Let's start at the beginning. What is an accelerometer? You can read about it in more detail here: http://en.wikipedia.org/wiki/Accelerometer, but effectively it's a little doohickey that allows a device (in our case the Windows Phone) to detect the magnitude and direction of acceleration.

Windows Phone 7 (WP7) will have an accelerometer in it. The framework namespace that covers the accelerometer is Microsoft.Devices.Sensors. The class we care about here is the Accelerometer class. This class has 2 important methods Start and Stop. As you can likely guess, start tells the system you want to start reading values from the accelerometer and stop means you are done. The Accelerometer also has an important event called ReadingChanged. This event fires once you have started the accelerometer and one of the accelerometer values has changed. The event uses the AccelerometerReadingEventArgs class to return back the values that have changed. There are 3 important values, X, Y, and Z. Each represents the force of acceleration on that axis.

When I first started playing with the accelerometer I didn't quite understand what the values for X, Y, and Z meant. When a device is sitting face up on a desk, X and Y will both be zero (or close to it). Z will be -1. if you took a nail and hammered your device to the table, that nail would represent the Z axis. It's value is -1 because gravity is pulling it down in that direction. If you turn the device over (face down) Z would now be equal to 1. The same pattern follows for X and Y. If you put the device on it's right side X will be 1. Put it on it's left side and X will be -1. If you stand the device up Y will be -1. If you turn the device upside down, Y will be 1. Keep in mind that these values can be greater than zero for when greater than normal forces are put on them. Shaking for example.

As you can probably figure out, based on these values you can tell when a user tilts to the left, right, top, bottom, up or down.

The Accelerometer and the WP7 Emulator

Unfortunately there's no easy way to test accelerometer code using the WP7 emulator. It currently doesn't pick up an accelerometer even if you have one on your PC. There are a few solutions for testing floating around. The one I like the most is using a Wiimote's accelerometer. If your computer has an accelerometer in it and you can access it from .NET I'm sure you could use code very similar to the Wiimote version. As I mentioned at the beginning of this post, I didn't think of this. This was Bill Reis's idea. I just used it as a way to understand how to use the Accelerometer.

Code

Using the accelerometer is pretty easy. For my example, I'm going to use a menu button to start and stop the accelerometer. The start stop code looks like this:

private void AppBarStartStopClick(object sender, EventArgs e)
{
    // If the accelerometer is null, initialize and start
    if (_accelerometer == null)
    {
        // Instantiate the accelerometer sensor object
        _accelerometer = new WiimoteAccelerometer();

        // Add an event handler for the ReadingChanged event.
        _accelerometer.ReadingChanged += AccelerometerReadingChanged;
        _accelerometer.Start();                                
    }
    else
    {
        // if the accelerometer is not null, call Stop
        _accelerometer.ReadingChanged -= AccelerometerReadingChanged;
        _accelerometer.Stop();
        _accelerometer = null;
        txtCoordinates.Text = "X=?, Y=?, Z=?";                    
    }
}

This code simply wires up to the ReadingChanged event and starts the accelerometer if it hasn't been started yet. All the magic happens in that event. When the event fires I want to move around an image on a canvas based on the accelerometer values. The first gotcha that I found is that this event does not return on the UI thread. That means you have to jump back to the UI thread with some BeginInvoke magic. That code looks like this:

private void AccelerometerReadingChanged(object sender, AccelerometerEventArgs e)
{
    //acceleromter returns on a different thread so let's go back to the UI thread
    Deployment.Current.Dispatcher.BeginInvoke(() => MyReadingChanged(e));
}

All that's left is setting the actual Top and Left values of the image. In this code I am multiplying the accelerometer values by 5. I do this because I want the image to move a little faster so it's easier to see it working.

private void MyReadingChanged(AccelerometerEventArgs e)
{
    var left = Canvas.GetLeft(imageLogo) + e.X * 5;
    var top = Canvas.GetTop(imageLogo) - e.Y * 5;

    //constrain the image to the canvas
    if (left < 0)
    {
        left = 0;
    }
    else if (left > canvasMain.Width - imageLogo.Width)
    {
        left = canvasMain.Width - imageLogo.Width;
    }                

    if (top < 0)
    {
        top = 0;
    }
    else if (top > canvasMain.Height - imageLogo.Height)
    {
        top = canvasMain.Height - imageLogo.Height;
    }

    Canvas.SetLeft(imageLogo, left);
    Canvas.SetTop(imageLogo, top);

    txtCoordinates.Text = string.Format("X={0}, Y={1}, Z={2}",
            e.X.ToString("0.00"), 
            e.Y.ToString("0.00"),
            e.Z.ToString("0.00"));            
}

That's it for the code. Not very complex. If I had a device I'd just deploy that to the device and stare for hours as the logo moved around the screen. Getting it running with the Wiimote is a little different, but not much more work.

Getting it Running with the Wiimote

The Wiimote can't talk directly to the WP7 emulator. To get around that, we are going to use the Wiimote Accelerometer server. This is a fairly simple piece of code that exposes the accelerometer values as a service. Instead of using the normal WP7 Accelerometer class we'll use the WiimoteAccelerometer class. This class will use the WiimoteAccelerometerProxy class to request values from the service every 100ms.

To get this running, we have to first connect the Wiimote via Bluetooth. You can read about how to do that here. Once connected run the WiimoteAccelerometerServer.exe. If everything is working correctly you should see the X, Y, and Z values scroll down your screen. One note here, run this in a console as an admin.

Once that's running you should be all set. Fire up the emulator and run your app. Click the start icon and watch the icon float around the screen as you move the Wiimote.

That's it. You can download the source code for this sample here.


Earlier today Jeff Blankeburg made a blog post about hostility towards windows phone 7.  Instead of commenting on his blog I decided to share my thoughts with everyone.

Kin

No Question MS dropped the ball here.  I think most were surprised when it was announced and then surprised when it was yanked.  The lifetime of Kin was so short that I doubt it will make a large impact over time.  People talk about it now because it's somewhat recent news.  Give it a few months and most will forget it.

 

Market Size

I've seen some comments suggesting that the game is over because Apple and Google own the market.  I've seen those same comments when Android came out saying that Apple owned the market.  There's no question that Apple's timing to market was excellent.  There was a void and they filled it first. Their leadership position has taken a hit from Google and with their less than stellar execution of the iPhone 4 launch.  There is no question in my mind that there is room in the market for MS.  Both by taking share away from Apple and Google and because it's an expanding market.  I see WM7 taking share away from both, but time will tell.

 

Development

I am a .NET developer so I am biased on this one.  In my opinion the developer story here is the clincher for MS.  I have toyed with development on the iPhone and was very disappointed.  I have no interest in managing memory anymore. It's time to move on and Apple's holding on to an anchor with their outdated development tools and languages.  The low friction development environment that MS offers will make it so much easier to build apps that we will see a lot of developers on the platform.

 

Conclusion

In the end I feel MS will do well because they fit between the iPhone and Android.  iPhone has a walled garden that enforces a level of application quality but has a price to pay with the development tools and languages.  Android has a better development model but is so open that consumers loose confidence in the quality of applications.  WM7's model enforces a level of application quality with a low entry price for developers.  If, and this is a big if, MS can market WM7 as well as they have the XBOX then they will have a place in this game.