DCSIMG
August 2011 - Posts - Arik Poznanski's Blog

Arik Poznanski's Blog

It CAN be done with .NET

News

MVP

MCC

CodeProject MVP

MCPD

MCTS

Subscribe to my blog by email

Arik Poznanski LinkedIn Profile

Email: arik.com at gmail dot com
or, use this form

Locations of visitors to this page


Sela Group

Sela Canada

DZone MVB

Links

Official Blogs

WPF / SL Blogs

Developers Blogs

August 2011 - Posts

Order in Chaos: Handling unhandled exceptions in a WPF application

Introduction

So you want to handle somehow all the unhandled exceptions in your application.
Usually you want to accomplish one of the following:

  • Log the exception for later diagnostics
  • Present the user an unhandled exception UI, nicer than the default

You heard there’s an event you should register, or maybe you find one by mistake, but is it the correct one?

Did you know there are four (!) different events for handling unhandled exceptions in the .NET framework?

So what is the difference between them and when should we use each one?
This post will hopefully answer these questions.

Note: this is NOT a replacement for try-catch blocks!

 

Summary

I’ll begin with the summary to avoid boring busy developers.

In a typical WPF application you should use Application.Current.DispatcherUnhandledException for exceptions generated on the UI thread and AppDomain.CurrentDomain.UnhandledException for all the other exceptions.

Now, for the details..

 

System.Windows.Forms.Application.ThreadException

This event is used for catching unhandled exceptions only on UI threads created by WinForms. Other exceptions, generated on non-UI threads won’t arrive to this event. Use AppDomain.Current.UnhandledException to catch them.

The default behavior of a WinForms application with an unhandled exception is to present the following error dialog:

image

If you register to this event, the application will not show the error dialog and will automatically extend the application life (i.e. the application won’t be killed).

If you do want to end your application, maybe after logging the exception or asking the user with a personalized dialog, you must do it yourself using Application.Exit().

You can find the MSDN documentation on this event here.

 

System.Windows.Application.Current.DispatcherUnhandledException

This event is used for catching unhandled exceptions only from the main UI thread created by WPF.

The default behavior of a WPF application with an unhandled exception is to present the following error dialog and end the application:

image

If you register to this event, you will get the chance to log the exception, but the application will still end, unless you set e.Handled = true, on the event’s EventArgs parameter.

You can find the MSDN documentation on this event here.

 

Dispatcher.UnhandledException

This event is used for catching unhandled exceptions on the thread attached to the specific Dispatcher (WPF only). Note, that in WPF two threads can have two different Dispatcher object attached. This event is only useful if you have several UI threads in your WPF application, which is quite rare. If you’re not sure, you probably need to handle only the previous event: Application.Current.DispatcherUnhandledException.

As in the previous event, if you register, you will get the change to log the exception. To prevent the exception internal handling from being called set e.Handled = true.

You can find the MSDN documentation on this event here.

 

AppDomain.CurrentDomain.UnhandledException

This event is used for catching unhandled exceptions generated from all threads running under the context of a specific application domain.

You can find the MSDN documentation on this event here.

 

Bonus: AppDomain.CurrentDomain.FirstChanceException

This event which exists only from .NET 4, is raised on ANY exception, if the handled one. In fact, the event is raised before the search for the catch blocks. You can’t handle the exception using this event. You can use it if you need to log exceptions that are caught.

You can find the MSDN documentation on this event here.

 

That's it for now,
Arik Poznanski.

Silverlight Tutorial Published [HEB]

After publishing a Windows Phone tutorial, the next logical step is a Silverlight tutorial.

So here it is, a 40 chapters tutorial in Hebrew completely adapted to Silverlight web development and using relevant source code and screenshots.

The tutorial is hosted on the great Hebrew developers community site: WebMaster.org.il

 

The tutorial is based on Silverlight 4 and it teaches Silverlight web development from the first step, using Visual Web Developer 2010 Express, provided freely by Microsoft.

Following is the index for all chapters:

  1. Introduction & Working Environment
  2. First Application
  3. XAML Language
  4. Setting Properties in XAML
  5. XAML and Code-behind C#
  6. Layout: Introduction
  7. Layout: Using StackPanel
  8. Layout: Using Grid
  9. Layout: Using Canvas
  10. Layout: Additional Properties
  11. Basic Controls: Introduction
  12. Basic Controls: Button Controls
  13. Basic Controls: Text Controls
  14. Basic Controls: ListBox
  15. Basic Controls: ComboBox
  16. More Controls
  17. Date Controls
  18. Understanding ContentControl
  19. Using Dependency Properties
  20. Using Routed Events
  21. Adding Child Windows
  22. Using Resources
  23. Data Binding: Introduction
  24. Data Binding: Controlling Information Flow
  25. Data Binding: Controlling Update Time
  26. Data Binding: Defining Sources
  27. Data Binding: Using IValueConverter
  28. Data Binding: Using INotifyPropertyChanged
  29. Data Binding: Binding to Collections
  30. Using Data Templates
  31. Using Shapes
  32. Using Brushes
  33. Displaying Images and Videos
  34. Using Transformations
  35. Using Styles
  36. Access HTML from Silverlight
  37. Access Silverlight from HTML
  38. Adding Splash Screen
  39. Creating Out-Of-Browser Application
  40. Using Isolated Storage

Stay tuned for the WPF tutorial.

That's it for now,
Arik Poznanski.

kick it on DotNetKicks.com Shout it

New C# Forum for the Israeli Developers Community

Following are some blog news:

New Israeli C# Forum

I'm proud to present a new MSDN forum in Hebrew for the C# developers community in Israel, managed by yours truly.

The forum is available on the following link: http://social.msdn.microsoft.com/Forums/he-il/VisualCsharpil

To all those nice developers who keep asking me C# related questions by mail, I strongly urge you to post your C# related questions on this forum.

NOT because I don't enjoy it!

On contrary, I love to help you and would even more enjoy it if even more people could enjoy the answers. Plus, there's more people on this forum that can help, so you will probably get an answer sooner :)

 

In other news..

New Windows 8 Blog

With Build conference approaching fast, Microsoft recently opened a new blog for Windows 8 behind the scenes details. Hopefully this is a sign that Microsoft is going to raise the curtain from the mysterious Windows 8. Follow the new blog here or on their Twitter @BuildWindows8.

 

That's it for now,
Arik Poznanski.

kick it on DotNetKicks.com Shout it

Using Windows Phone As Windows 7 Accelerometer Sensor

I just had a cool idea! (actually I had it like 6 month ago, but bear with me).

My idea involves mixing some of the features in Windows 7 with some of the features in Windows Phone 7, to create a glorious mix!

image

 

Windows 7

One of the new features in Windows 7 is the Sensor API which provides a standard interface for accessing sensors of various types, like accelerometer, etc..

I wrote in the past about how you can consume this API from a C# application using Windows API Code Pack.

 

Windows Phone 7

Windows Phone 7 comes with a few sensors out of the box, among them: accelerometer!

 

Idea

What if we use Windows Phone 7 accelerometer sensor as a standard device on Windows 7?

 

Roadmap

So how can we accomplish that? let's break the idea to steps:

Step 1: Create a software driver

I’ll start with creating a dummy software driver. This driver will implement what's necessary to be a standard Windows 7 Accelerometer sensor, but at this stage will simply return constant data.

In order to write a sensor driver for Windows 7 I’ll need to use User Mode Driver Framework (UMDF), a COM-like, C++ framework for writing user-mode drivers in Windows 7.

Step 2: Transfer Windows Phone 7 sensor data into the PC

The next step is to find a way to transfer the accelerometer data from a Windows Phone device into the PC. One possible way of doing this implementing a local WCF service on the desktop that the Phone will keep calling with accelerometer data. This will require an application to run on the phone to keep the data flowing.

Step 3: Consume the WCF service from the phone

Using the service from the previous step we can now consume it in a simple Windows Phone application that all it does is getting the accelerometer sensor data using the phone API and call the WCF service with the latest data.

Step 4: Make the software driver consume the Windows Phone 7 data

Now that I have a software driver that returns dummy accelerometer data and a way to get real accelerometer data from the Windows Phone, all I need to do is connecting the dots and make my accelerometer driver return the real data. To do this I'll need some kind of inter process communication to transfer the data from the WCF service to the driver.

 

Long Story Short…

I present to you the Windows Phone Accelerometer Driver for Windows 7!

The full source code for this project can be found on the CodePlex project site.

 

Some Implementation Details

The actual driver was fairly easy to implement since I used the CodeProject article "Writing a Sensor Driver for the Wiimote on Windows 7" by Rajasekharan Vengalil as a base for my Windows Phone 7 driver. You can find the driver source code in the project named WP7AccelerometerDriver.

As mentioned earlier I've implemented a simple local WCF service for transferring the accelerometer data from the phone to the driver. You can find the service source code in the project named WP7AccelerometerService. The service uses named pipes to communicate with the driver.

The phone application is a very simple one that consumes the WCF service and call it whenever a new accelerometer value is available. You can find its source code in the project named WP7AccelerometerClient.

Finally, if you want to check the functionality of the accelerometer driver you can use either the SensorDiagnostics project or the more fun PlaneDemo project, which I borrowed for Sergey Zwezdin blog.

 

How to Install?

1. Download and extract project binaries or source from the CodePlex project site.

2. Open CMD as administrator

3. Go to the folder \Driver\Install\

4. According to the bitness of your OS Run install_wp7_driver_32bit.bat or install_wp7_driver_64bit.bat to install the driver.

image 

5. When the following notification appears, select "Install this driver software anyway":

image
This should take around 1-2 minutes to complete.

6. Enable installed Sensor in the Control Panel

image 

7. Run the WCF service from as administrator. If you run it from Visual Studio, make sure you ran Visual Studio as administrator.

image

 

8. Run the Windows Phone client on a real device while connected to the PC and enter your PC (LAN) IP

image

 

9. That's it! you can now sit back and enjoy the ride using the PlaneDemo application or SensorDiagnostics, or any other software that uses the accelerometer sensor.

image

image

 

How to Uninstall?

If you want to uninstall the driver simply go to the Device Manager, select the "WP7 Accelerometer Sensor" device from the Sensors category, select uninstall from the context menu and make sure you mark the checkbox to delete the driver.

image

 

Final Note

I've seen the project works both on a real device and using the phone emulator, however it's not a one-click install. I expect users to have problems with the installation. If you encounter some problems, please post on the CodePlex project site forum page and I'll do my best to help.

Also, if you want to improve the source code (maybe adding GPS support?) or the installation procedure, I'll be happy to include your improvements and even include you as one of the project members on CodePlex.

This project was pure fun since it combines many useful technologies to create real value. Among the technologies you can find: C++, COM, UMDF, C#, WCF, WP7, etc..

That's it for now,
Arik Poznanski.

WPF: Dictionary Value Converter

What’s the story?

You want to convert an enum value to a bitmap image.

That’s easy, here’s a solution

Usually you would simply create a new value converter which has some custom code (e.g. a switch –case statement) to convert from the enum value to the relevant image.

Is there a better solution?

How many times have you written this kind of converter, the kind that takes a value and maps it to another value?

Well, no more!

I present to you: DictionaryValueConverter. A Converter that lets you define a collection of key-value pairs and do the mapping for you.

So, how can I use this converter?

The following code provides a common usage of this converter. Here I map three enum values to three different bitmap images. Each value in the Values property is another image which is mapped by its x:Key.

<converters:DictionaryValueConverter x:Key="propertyTypeToImage">
    <converters:DictionaryValueConverter.Values>
        <BitmapImage x:Key="{x:Static local:PropertyType.Name}"
                     UriSource="Name.png" />
        <BitmapImage x:Key="{x:Static local:PropertyType.Age}"
                     UriSource="Age.png" />
        <BitmapImage x:Key="{x:Static local:PropertyType.Phone}"
                     UriSource="Phone.png" />
    </converters:DictionaryValueConverter.Values>
</converters:DictionaryValueConverter>

This is SO COOL, can I use it also to convert Booleans to Visibility?

Well, yes and no.

Theoretically, it will work. There is nothing in the code which prevents it.

Practically, you need a way to specify the “true” and “false” Boolean values as the keys.

Unfortunately, XAML 2006 doesn’t allow x:Key to have complex values (using property element syntax). This was fixed in XAML 2009, but WPF doesn’t support it yet.

To work around it you can define constants for the “true” and “false” values and use x:Static markup extension to provide the keys.

For example:

public static class BooleanValues
{
    public const bool True = true;
    public const bool False = false;
}

 

<converters:DictionaryValueConverter x:Key="booleanToVisibilityConverter">
    <converters:DictionaryValueConverter.Values>
        <Visibility x:Key="{x:Static local:BooleanValues.True}">Visible</Visibility>
        <Visibility x:Key="{x:Static local:BooleanValues.False}">Collapsed</Visibility>
    </converters:DictionaryValueConverter.Values>
</converters:DictionaryValueConverter>

 

So, how is it implemented?

Like this:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;

namespace Common.Converters
{
    public class DictionaryValueConverter : IValueConverter
    {
        /// <summary>
        /// Store the key type.
        /// Setting this property is needed if your key is an enum and  
        /// </summary>
        public Type KeyType { get; set; }

        /// <summary>
        /// Store the key-value pairs for the conversion
        /// </summary>
        public Dictionary<object, object> Values { get; set; }

        public DictionaryValueConverter()
        {
            Values = new Dictionary<object, object>();
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // if key type is not set, get it from the first dictionary value, usually it's the same for all the keys
            if (KeyType == null)
            {
                KeyType = Values.Keys.First().GetType();
            }

            // if key type is an enum
            if (KeyType.IsEnum)
            {
                // convert integral value to enum value
                value = Enum.ToObject(KeyType, value);
            }

            // if dictionary contains the requested key
            if (Values.ContainsKey(value))
            {
                // return the relevant value
                return Values[value];
            }

            // otherwise, don't return a value, this will fall back to the binding FallbackValue
            return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // no support for converting back
            return DependencyProperty.UnsetValue;
        }
    }
}

You can download a demo application here.

That’s it for now,
Arik Poznanski.

Windows Phone Tutorial Published [HEB]

I've recently published a 41 chapters tutorial in Hebrew about developing application using Windows Phone. The tutorial is hosted on the great Hebrew developers community site: WebMaster.org.il

Windows Phone Tutorial Published [HEB]

The tutorial is based on Windows Phone Mango and it teaches Windows Phone development from the first step, using Visual Studio 2010 Express, provided freely by Microsoft.

Windows Phone Tutorial Published [HEB]

Following is the index for all chapters:

  1. Introduction & Working Environment
  2. First Application
  3. XAML Language
  4. Setting Properties in XAML
  5. XAML and Code-behind C#
  6. Layout: Introduction
  7. Layout: Using StackPanel
  8. Layout: Using Grid
  9. Layout: Using Canvas
  10. Layout: Additional Properties
  11. Basic Controls: Introduction
  12. Basic Controls: Button Controls
  13. Basic Controls: Text Controls
  14. Basic Controls: ListBox
  15. More Controls
  16. Web Controls
  17. Understanding ContentControl
  18. Using Dependency Properties
  19. Using Routed Events
  20. Adding Pages to the Application
  21. Using Resources
  22. Data Binding: Introduction
  23. Data Binding: Controlling Information Flow
  24. Data Binding: Controlling Update Time
  25. Data Binding: Defining Source
  26. Data Binding: Using IValueConverter
  27. Data Binding: Using INotifyPropertyChange
  28. Data Binding: Binding to Collections
  29. Using Data Templates
  30. Using Shapes
  31. Using Brushes
  32. Displaying Images and Videos
  33. Using Transformations
  34. Using Styles
  35. Using Pivot and Panorama
  36. Handle Phone Orientation
  37. Working with Application Bar
  38. Application Lifecycle
  39. Using Launchers
  40. Using Choosers
  41. Using Accelerometer Sensor

Coming next: A Silverlight guide and a WPF guide (with technology specific details and screenshots).

That's it for now,
Arik Poznanski.

kick it on DotNetKicks.com Shout it