Handling Exceptions on Windows Phone 7

In this post I’ll outline how to deal with exceptions in a Windows Phone 7 application. Ideally when an exception happens, we want to display some meaningful information to the user that can be provided to the developer to aid in the debugging of the issue. The worst thing that can happen is for the application to crash and just exit. This can lead to frustration on the users part (as I’ve experienced with the official Twitter application on iOS 4.0), or worse dissuade a user from purchasing any other applications bearing your name.

In this example, when an exception occurs, we’ll ensure that we navigate to an error page, and display the stack trace. Aside, this is obviously not the best thing to display to an end user. The best approach may be to display a generic error message with an option to report the error, which then emails the exception information to your support address. I leave that as an exercise to the reader, in this example, we’ll just display the stack trace information directly to the user:

1. Add a new Windows Phone Portrait Page to your Windows Phone 7 project in Visual Studio. For the purpose of this example, I’ve named the page ‘Error.xaml’.

2. In ‘Error.xaml’, locate the ‘LayoutRoot’ Grid element, and replace its content with the following:















3. The page you created above will act as the container for any exceptions that we need to display. Next, open up ‘Error.xaml.cs’, and add the following code:


using System.Windows.Navigation;
...
...

public static Exception Exception;

// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ErrorText.Text = Exception.ToString();
}

This sets up an Exception Object that is hooked up to ErrorText.Text upon navigating to the page.

4. Finally, we need to hook up an event handler that ensures that we navigate to this page whenever an unhandled exception occurs. This is done from ‘App.xaml.cs’. Open up ‘App.xaml.cs’, and replace the content of the ‘Application_UnhandledException’ function with the following code:


if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break in the debugger
System.Diagnostics.Debugger.Break();
}

// Running on a device / emulator without debugging
e.Handled = true;
Error.Exception = e.ExceptionObject;
(RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =
new Uri("/Error.xaml", UriKind.Relative);

If you have completed the above steps correctly, then whenever an unhandled exception occurs in your application, the application will navigate to this page, and display the exception stack trace.

To verify these steps, add a button to your ‘MainPage.xaml’ and have it link to a page that doesn’t exist, e.g.


NavigationService.Navigate(new Uri("/NotHere.xaml", UriKind.Relative));

Launch the application in the emulator, and click the button you just created, (You’ll need to launch without debugging). The result should be navigation to ‘Error.xaml’ with the exception details:

Windows Phone Error Example

Windows Phone 7 – Check if first run

Many of the applications I’ve been looking at developing during my Windows Phone 7 endeavours have a common requirement – the ability to check if this is the first run of the application. For example, if you are designing an application that will access a service like Twitter or Facebook, you’ll need to gather the users login details in order for your application to function.

For example, on the first run of the application, we’ll want to display a login dialog, gather the users information and store it. We can use the isolated storage facility on Windows Phone 7 devices to store this information. If you’re unfamiliar with isolated storage, check out my previous post here.

Step 1 – Store a value to track if this is the first run

I added this code to the ‘Application_Launching’ function. This function is called each time your application is launched.


// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
// Set if this is the first run of the application or not
if (!settings.Contains("firstRun"))
{
settings.Add("firstRun", (bool)true);
}
else
{
settings["firstRun"] = (bool)false;
}
}

Step 2 – Intercept navigation to your main page, redirect if necessery

Next, we need to create an event handler to intercept any navigation the your main page, and redirect to your ‘first run’ page (login or whatever) if necessery.

First we check if we’re navigating to our main page, if we’re not the function just returns and navigation proceeds as normal. If we are, we’ll ensure that if it’s the first run of the application, the user will be redirected to a login page etc.


///

/// Event handler to intercept MainPage navigation
///

/// the frame /// navigation args void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
// Only care about MainPage
if (e.Uri.ToString().Contains("/MainPage.xaml") != true)
{
return;
}

// Check if this is the first run of the application
if ((bool)settings["firstRun"])
{
e.Cancel = true;
RootFrame.Dispatcher.BeginInvoke(delegate
{
RootFrame.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
settings["firstRun"] = (bool)false;
});
}
else
{
RootFrame.Dispatcher.BeginInvoke(delegate
{
RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
}
}

Step 3 – Ensure the event handler is called when navigation occurs

Finally, we need ensure that the event handler we created in step 2 above is actually called when any navigation occurs. To accomplish this, all we need to do is add the following code in the constructor of the ‘App.xaml.cs’ file:

// Add this code to the constructor in App.xaml.cs

// Route the user to the login screen if it's the first run of the application
RootFrame.Navigating += new NavigatingCancelEventHandler(RootFrame_Navigating);

That’s pretty much it, I’ve successfully used the above mechanism in two different applications, hope this saves you some time!

Windows Phone 7 – Storing & Retrieving Information

I’m planning on doing a series of posts called ‘2 Minute Tutorials’. I always get frustrated when searching for information on the Internet. Sometimes, I just want a simple explanation, and a code example that I can utilize immediately. This is what I hope to provide in this series of posts, which will be mostly related to Windows Phone 7, C#, and C++.

In this particular installment, I’m going to take you through the process of storing and retrieving information on the Windows Phone 7 platform – a certain requirment should you intend developing a WP7 application. You can store information on the phones local file system quite easily. This may be required for saving such things as user information like usernames and passwords to services such as Twitter, or application specific preferences such as a preferred language or orientation.

This functionality is provided by the IsolatedStorageSettings class contained in the System.IO.IsolatedStorage namespace. It’s ‘isolated’, because it can only be accessed by your application, not by any others. If you need to share information between applications, you’ll need to store it on the web somewhere – this offers local, isolated storage only.

IsolatedStorageSettings allows you to store name/value pairs in a dictionary. This data will always be there, even after powering off the phone. It will remain in the file system until you either remove it, or you uninstall the application to which it belongs.

Here’s an example of storing an item called ‘username’:

using System.IO.IsolatedStorage;
...
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("username", "jimmy");

Simple. It’s just as easy to retrieve the data again:

string username = (string) settings['username'];

Some important things to remember:

  • Your application will throw an exception if you try to retrieve a value that is not present so you should always handle this case.
  • You can save anything, even Objects.
  • You have to explicitly cast your data when you retrieve it.

That’s it. It’s that simple to store and retrieve information on the local file system of a device running Windows Phone 7.

See here for the MSDN documention on IsolatedStorageSettings.

Windows Phone 7 Development – First Impressions

Since my Christmas leave from work has begun, I’ve had some time to really look at Windows Phone 7 development over the last 2 days, and have gotten really excited about it all. I’ve been meaning to do this for ages (since WP7 was released actually), but have always either been too busy or suffered procrastination (thanks Zen Habits!).

Some positives:

  • Development Environment – I think Microsoft has done an excellent job on Visual Studio 2010, and the WP7 development tools plug in seamlessly. If you don’t already have Visual Studio 2010, Microsoft is offering a special Express Editon for Windows Phone.
  • Developer Resources – There are a huge amount of resources available on Microsoft’s App Hub (often called ‘MarketPlace’ – the equivalent of Apple’s ‘App Store’), ranging from tutorials, walkthroughs of some key concepts and full application code examples.
  • The Windows Phone Emulator – This is installed as part of the developer tools, and it really is state of the art. I haven’t purchased an actual device running WP7, but have been using the emulator to test my inital application effort. There are some obvious things that won’t work on the emulator, for example anything to do with the accellerometers (the emulator assumes it is lying on a flat surface), but it’s perfect for testing your inital Windows Phone 7 applications.
  • Familiarity – If you’ve ever developed using C# on the Windows platform, you already have a huge start in WP7 development.
  • Developer Subscription – The cost of a yearly developers subscription, a mere 99 Euro, can easily be covered with very little downloads of your applications (should you even be bothered about it).

The only ‘negative’ I’ve found so far is that I’ve had to purchase a (long overdue) brand new Dell running Windows 7 in order to create my development environment. My previous machine, running Windows XP, is not supported by the Windows Phone 7 development tools, which seems strange to me, since XP is not scheduled to be EOL’d until 2014. It seems to be another move by Microsoft to push people to move to Windows 7 or (shudder) Windows Vista.

Windows Phone 7 development is one of the three areas I want to become proficient with in the first half of 2011. I had initially focused on the iOS platform, but when I thought about it, it didn’t make much sense, since I’m already familiar with C# and didn’t feel I’d gain any real advantage by learning Objective C. Also, rumours began to circulate this week regarding Microsoft getting into bed with Nokia, so WP7 will surely gain more momentum in the first half of 2011.

My first application, (well under way!), will be a simple Twitter client. The reason I chose this is that it will encompass many of the key concepts I’ll need to learn, such as designing user interfaces for WP7, storing information locally on a WP7 device, and accessing external information via API’s. I plan to complete this over Christmas – screenshots to follow once it is.

Aside: If you’re interested in getting into developing on the Windows Phone 7 platform, check out Jeff Blankenburg’s 31 Days of Windows Phone, it’s the best introductory article series I’ve found so far.