Sunday, June 20, 2010

Debugging a Silverlight app in Cassini

This post was born out of a long and frustrating process of trying to debug two Silverlight apps.

While you can apply these tips more generally as you choose, I can only promise they are relevant in the following situation:

Your Silverlight application polls one or more WCF services that are not in the Silverlight web project
You are developing on a shared server or otherwise would like to run the services and the Silverlight app in the Development Server (Cassini)
You press F5 to debug your Silverlight application and you are bombarded with uncaught and seemingly untraceable WCF exceptions
You have a feeling of anger, coupled with self loathing, that you cannot debug your own app
With this grim stage set, let’s follow along with how I made things better.

Unhandled Exceptions

Yuck, an unhandled exception is shocking; first that your code has any bugs, second that they dare to interrupt your debugging session. Of course, you want to fix the source of these exceptions, but first you’ve got to find them. Heading over to your app.xaml.cs file and let’s wire up the global unhandled exception handler.

In the constructor:

this.UnhandledException += this.Application_UnhandledException;
The handler code:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
   if (!System.Diagnostics.Debugger.IsAttached)
   {
    //define what your app should do when in PROD
   }
   else
   {
    //force break in vs debugger on error
    System.Diagnostics.Debugger.Break();
       //but can continue if like
       e.Handled = true;
   }
}
As you can see here, this code checks to see if there is a debugger attached to the process, and if there is, it forces a stop. The behavior you’ll see when debugging is that if you have an unhandled exception, all of the sudden you’ll jump to the else clause of this method and be able to inspect the exception object e for details.

Read more: Clarity Consulting

Posted via email from .NET Info