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

WPF – Binding Data in an XML file to a ComboBox

Some things in WPF are very different from Windows Forms programming. Lately, I’ve been working on my first real UI in which I’ve used WPF over Windows Forms. Using XAML takes a little bit of getting used to, but I’m finding that I have a lot more control over the UI, along with the obvious advantage of seperating the UI presentation from the actual application logic.

Just the other day I needed to create a ComboBox control on a section of my UI, the items in which would need to be loaded from an XML file at runtime. The XML file was to be included as a resource.

The XML file looked something like this:






...

I wanted the ‘name’ attribute from each Language node to be bound to my ComboBox. In order to do this, first we need to define the XML file as a resource in our XAML:





...
...

Then, we just need to add the ItemsSource, SelectedValuePath, and DisplayMemberPath to the ComboBox XAML, specifying the resource we declared earlier, and the attribute that we want to bind:




Note the ‘SelectedItem’ can be set as well from the XAML, It’s set to ‘Arabic’ in the above example.

SharpSVN: A Gentle Introduction

SharpSVN is a really useful library which encapsulates the functionality of the Subversion client so we can leverage it programmatically from .NET applications. I can think of many uses for this. In the past, in some of the automation frameworks I’ve worked with, updating the source code from SVN has been a manual task ran weekly. Using SharpSVN, we could write a simple console application to accomplish this. It could also be useful to automate repetitive SVN tasks in a development environment.

In this post, I’m going to outline the basics of using SharpSVN, and in the process create a simple C# console application to check-out some source code.

For starters, we’ll need to download the SharpSVN package from here. Next, create a C# console application in Visual Studio. You’ll need to target .NET 2.0.

Unzip the SharpSVN package, and add ‘SharpSVN.dll’ as a reference to your console application. Next, add the following code. We’ll pass the location we want to check-out from as an argument to the application:


string Repository = string.Empty;

if (args.Length != 1)
{
Console.WriteLine("Usage: SharpSVN ");
}
else
{
Repository = args[0];
}

I’m assuming here that you’re already authenticated with your SVN server. Now the code to actually perform the check-out, which is really simple:


using (SvnClient client = new SvnClient())
{
try
{
SvnUriTarget target = new SvnUriTarget(Repository);

if (client.CheckOut(target, @"C:\Working"))
{
Console.WriteLine("Successfully checked out '" + Repository + @"' to 'C:\Working'");
}

}
catch(Exception e)
{
Console.WriteLine("Error occurred during check out: " + e.ToString());
}

That’s it. The above code will check-out the source code from the SVN repository you passed as an argument to ‘C:\Working’.

The only downside I’ve seen with SharpSVN, is that it only seems to work when I target .NET 2.0. Maybe I could download the source and try to compile it under .NET 4.0, but I haven’t tried that.

I see huge usage for this library in future projects, and it’s certainly better that a previous solution I had implemented using the command line interface to the TortoiseSVN client.

Happy Coding…

C# – Logging to the Windows Event Viewer

In the past for any applications I’ve written in C#, I’ve always logged any information I needed to in a .txt file in the Windows %temp% directory. This was really quite a messy approach when I consider it now.

Logging from your applications can be useful for a couple of reasons:

  • Auditing: Depending on your level of logging, you can get a step by step view of what’s happening with your application. I find this useful for testing as I write code.
  • Diagnostics: This is the more obvious use of logging from your application – capturing a stack trace or other useful information in the event of any issues.

Using the Windows Event Viewer to capture auditing or diagnostic logging is a much better approach, as you can specify when you log what type of event this is, i.e. ‘Information’ (for auditing), or ‘Warning’ and ‘Error’ (for diagnostic logging). This makes it a lot easier to find errors, and makes any logging you do highly readable.

I’ve created this class which wraps the logging to the Event Viewer functionality:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;

namespace EventLoggingExample
{
public class LoggingHelper
{
private string Application;
private string EventLogName;

///

/// Constructor
///

/// The application doing the logging /// The log to write to in the Event Viewer public LoggingHelper(string app, string log)
{
Application = app;
EventLogName = log;

// Create the event log if it doesn't exist
if (!EventLog.SourceExists(Application))
{
EventLog.CreateEventSource(Application, EventLogName);
}

}

///

/// Write to the event log
///

/// The message to write public void WriteToEventLog(string message, string type)
{
switch (type.ToUpper())
{
case "INFO":
EventLog.WriteEntry(Application, message, EventLogEntryType.Information);
break;
case "ERROR":
EventLog.WriteEntry(Application, message, EventLogEntryType.Error);
break;
case "WARN":
EventLog.WriteEntry(Application, message, EventLogEntryType.Warning);
break;
default:
EventLog.WriteEntry(Application, message, EventLogEntryType.Information);
break;
}
}
}
}

To use it, just create an instance and log at will:


LoggingHelper log = new LoggingHelper("MyApplication", "MyAppLog");
log.WriteToEventLog("Some application information", "info");
log.WriteToEventLog("This is your first warning!", "warn");
log.WriteToEventLog("An error has occurred...", "error");

This is definetely something I’ll be adding to my utilities library.

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!

ASP.NET MVC – Creating a DropDownList

I’ve been looking at the ASP.NET MVC framework for the past two weeks, and it has occurred to me that some of the simple things we may want to do when creating a web application may seem confusing to someone new to ASP.NET MVC – for example the task of creating a DropDownList control on a form. ASP.NET MVC provides a number of ‘HTML Helpers’ which we can easily use to construct the form items. ‘DropDownList’ is one of these HTML helpers we can use.

Let’s create a simple example form using some of these HTML helpers. To begin a form, we can use a helper, we just need to add this code to our View:


<% using (Html.BeginForm()){ %>

// Form data will go here

<% } %>

This creates the basic form code for us – no need to explicitly write any HTML code. Before adding the DropDownList control, we need to decide where we want to get the data which will bind to the list. We can either hard code the items, or use LINQ to SQL to grab them from a database at runtime.

Method 1 – Hardcoding the form items

With this approach, we just add the items to a list, and pass this list to ViewData, so we can access it from the View:


List items = new List();
items.Add(new SelectListItem
{
Text = "Apple",
Value = "1"
});
items.Add(new SelectListItem
{
Text = "Banana",
Value = "2",
Selected = true
});
items.Add(new SelectListItem
{
Text = "Orange",
Value = "3"
});

ViewData["DDLItems"] = items;
return ViewData;

Then, to actually display the DropDownList, we’d just need to add a single line to our View code, utilizing the DropDownList HTML helper:


<%= Html.DropDownList("DDLItems") %>

Method 2 – Using LINQ to SQL to get the data at runtime

We could also retrieve the list data from a database table at runtime using LINQ to SQL. In order for this approach to work, you will need to have generated LINQ to SQL classes for your database using the wizard in Visual Studio. Then we can easily write the code to retrieve the data:


// Get the list of supported languages (for example) from the DB
var db = new TransDBDataContext();
IEnumerable languages = db.trans_SupportedLanguages
.Select(c => new SelectListItem
{
Value = Convert.ToString(c.ID),
Text = c.Name.ToString()
});

ViewData["SupportedLanguages"] = languages;
return View();

Again, to display the DropDownList, we’d just need to add a single line of code to the View:


<%= Html.DropDownList("SupportedLanguages") %>

From the above, you can see how easy it is to render form items using the HTML helpers provided by ASP.NET MVC.

For a full list of the helpers, check out the MSDN documentation here.