In
the following section, you will learn to capture device-specific
exceptions. You will be using the accelerometer device as an example to
properly handle unexpected exceptions by catching AccelerometerFailedException.AccelerometerFailedException
can occur if the accelerometer device on the phone is broken. Also the
exception can occur if the device throws unexpected error caused
internally by Microsoft Window Phone framework. Figure 1 displays the basic UI of the CatchDeviceExceptionDemo project that you will be building.
1. Creating the CatchDeviceExceptionDemo Project
To set up the CatchDeviceExceptionDemo project, follow the steps you've used for previous examples in this book.
Open Microsoft Visual Studio 2010 Express for Windows Phone on your workstation.
Create a new Windows Phone Application by selecting File =>
New Project on the Visual Studio command menu. Select the Windows Phone
Application template, name the application "CaptureAccelerometerData,"
and click OK.
In order to use the accelerometer, add an assembly reference to Microsoft.Devices.Sensors by right-clicking the References folder in Solution Explorer, and choose Microsoft.Devices.Sensors from the Add Reference window, as shown in Figure 2.
2. Building the User Interface
You will be building the user
interface using the XAML in the Visual Studio. For building simple
controls, it is faster to work with the XAML code. Go to Solution
Explorer, open MainPage.xaml, and replace the XAML you find there with the following code.
2.1. Declaring the UI Resources
The namespaces you see in the
following code snippet are typically declared by default when you first
create a Windows Phone project. In particular, namespacesxmlns:phone="clr-namespace:Microsoft.Phone.Controls; assembly=Microsoft.Phone"allow you to add common Windows Phone controls to the application main page.
<phone:PhoneApplicationPage
x:Class="CatchingDeviceExceptionsDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
2.2. Building the Main Page and Adding Components
Create two buttons to start and stop the accelerometer.
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="CatchingDeviceExceptionsDemo"
Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Start Accelerometer" Height="72" HorizontalAlignment="Left"
Margin="84,45,0,0" Name="btnStartAcc" VerticalAlignment="Top"
Width="284" Click="btnStartAcc_Click" />
<Button Content="Stop Accelerometer" Height="72" HorizontalAlignment="Left"
Margin="84,123,0,0" Name="btnStopAcc" VerticalAlignment="Top"
Width="284" Click="btnStopAcc_Click" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Once you have loaded the XAML code, you should see the layout shown in Figure 3. In the next section, you will be coding the application.
3. Coding the Application
In Solution Explorer, open MainPage.xaml.cs and replace the code there with the following code C# code blocks.
3.1. Specifying the Namespaces
Begin by listing the namespaces the application will use. Notice our inclusion of Microsoft.Devices.Sensors that will allow us to start and stop Windows Phone's accelerometer.
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
3.2. Initializing Variables
The variable _acc, Accelerometer object, will be used to start and stop.
Accelerometer _acc;
public MainPage()
{
InitializeComponent();
_acc = new Accelerometer();
}
3.3. Implementing Accelerometer Start and Stop Behavior
Implement a button event for stopping and starting the accelerometer. Notice that you are catching AccelerometerFailedException, which can be raised during the start and stop of the accelerometer. In the exception property, you will find ErrorId and Message that contains specific error code and description that could explain why the error was raised
private void btnStartAcc_Click(object sender, RoutedEventArgs e)
{
try
{
_acc.Start();
_acc.ReadingChanged += (s1, e1) =>
{
// Do something with captured accelerometer data
};
}
catch (AccelerometerFailedException ex)
{
string errorMessage = string.Format(@"
Accelerometer threw an error with ErrorId {0}
during the start operation
with error message {1}
", ex.ErrorId, ex.Message);
MessageBox.Show(errorMessage);
}
}
private void btnStopAcc_Click(object sender, RoutedEventArgs e)
{
try
{
_acc.Stop();
}
catch (AccelerometerFailedException ex)
{
string errorMessage = string.Format(@"
Accelerometer threw an error with ErrorId {0}
during the stop operation
with error message {1}
", ex.ErrorId, ex.Message);
MessageBox.Show(errorMessage);
}
}
4. Testing the Finished Application
To test the finished application, press F5. The result should resemble the screenshot shown in Figure 1.
The only thing you will not be able to test is being able to raise
AccelerometerFailedException, which can be raised only if the
accelerometer device fails. But the demo will give you a good idea of
how you should be handling the device-related exception if it ever
occurs.