Throw Unhandled Exception

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="135" Width="300">
  <StackPanel>
    <Button x:Name="btnThrowUnhandledException" Click="btnThrowUnhandledException_Click" Content="Throw Unhandled Exception" Margin="10,5,10,5"/>
  </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.Windows;
using System.ComponentModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }


        private void btnThrowUnhandledException_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

    }
}

   
    
     


Throw Unhandled Exception From Thread

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="135" Width="300">
  <StackPanel>
    <Button x:Name="btnThrowUnhandledExceptionFromThread" Click="btnThrowUnhandledExceptionFromThread_Click" Content="Throw Unhandled Exception From a New Thread" Margin="10,5,10,10"/>
  </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.Windows;
using System.ComponentModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }


        private void btnThrowUnhandledExceptionFromThread_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += delegate { throw new NotImplementedException(); };              

            backgroundWorker.RunWorkerAsync();
        }
    }
}

   
    
     


Customize UpdateSourceExceptionFilter

image_pdfimage_print


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:WpfApplication1"
  x:Class="WpfApplication1.Window1">
    <Window.Resources>
        <c:MyDataSource x:Key="ods"/>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)&#91;0&#93;.ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox Name="textBox3" Width="50" FontSize="15"
             Validation.ErrorTemplate="{StaticResource validationTemplate}"
             Style="{StaticResource textBoxInError}">
            <TextBox.Text>
                <Binding Path="Age3" Source="{StaticResource ods}" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <ExceptionValidationRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

        <CheckBox Name="cb" Checked="UseCustomHandler" Unchecked="DisableCustomHandler">Enable Custom Handler (see ToolTip)</CheckBox>
    </StackPanel>
</Window>

//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        void UseCustomHandler(object sender, RoutedEventArgs e)
        {
            BindingExpression myBindingExpression = textBox3.GetBindingExpression(TextBox.TextProperty);
            Binding myBinding = myBindingExpression.ParentBinding;
            myBinding.UpdateSourceExceptionFilter = new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
            myBindingExpression.UpdateSource();
        }

        void DisableCustomHandler(object sender, RoutedEventArgs e)
        {
            Binding myBinding = BindingOperations.GetBinding(textBox3, TextBox.TextProperty);
            myBinding.UpdateSourceExceptionFilter -= new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
            BindingOperations.GetBindingExpression(textBox3, TextBox.TextProperty).UpdateSource();
        }

        object ReturnExceptionHandler(object bindingExpression, Exception exception)
        {
            return "This is from the UpdateSourceExceptionFilterCallBack.";
        }
    }
    public class AgeRangeRule : ValidationRule
    {
        private int _min;
        private int _max;

        public AgeRangeRule()
        {
        }

        public int Min
        {
            get { return _min; }
            set { _min = value; }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value; }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            int age = 0;

            try
            {
                if (((string)value).Length > 0)
                    age = Int32.Parse((String)value);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }

            if ((age < Min) || (age > Max))
            {
                return new ValidationResult(false,
                  "Please enter an age in the range: " + Min + " - " + Max + ".");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

    public class MyDataSource
    {
        private int _age;
        private int _age2;
        private int _age3;

        public MyDataSource()
        {
            Age = 0;
            Age2 = 0;
        }

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        public int Age2
        {
            get { return _age2; }
            set { _age2 = value; }
        }

        public int Age3
        {
            get { return _age3; }
            set { _age3 = value; }
        }
    }
}

   
    
     


Manage unhandled exceptions that are thrown on secondary worker threads.

image_pdfimage_print


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="WpfApplication1.MainWindow"
  Height="200" Width="400">

  <Button Click="aClick">Thread</Button>

</Window>
//File:Window.xaml.cs

using System; 
using System.Threading; 
using System.Windows; 
using System.Windows.Threading;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Title = string.Format("Running on Main UI Thread {0}", Thread.CurrentThread.ManagedThreadId);
        }

        void aClick(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(aMethod);
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }
        void aMethod(){
            try{
                string msg = string.Format("secondary on worker thread {0}.", Dispatcher.CurrentDispatcher.Thread.ManagedThreadId);
                throw new Exception(msg);
            }catch (Exception ex){
                int secondaryWorkerThreadId = Thread.CurrentThread.ManagedThreadId;
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback)delegate(object arg)
                    {
                        string msg = string.Format("from secondary worker thread {0}.", secondaryWorkerThreadId);
                        throw new Exception(msg, ex);
                    }
                    , null);
            }
        }

    }
}

   
    
     


Throw Exception from button click action

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AppEventsSample" Height="300" Width="300">
    <Grid>
    <Button Height="23" x:Name="shutdownButton" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75">Shutdown</Button>
    <Label Height="25" HorizontalAlignment="Left" Margin="10" x:Name="label1" VerticalAlignment="Top" Width="100">Application Events:</Label>
    <ListBox Margin="20" x:Name="eventsListBox" ItemsSource="{Binding}" />
    <Button Height="23" Margin="10" Name="exceptionButton" VerticalAlignment="Bottom">Exception</Button>
  </Grid>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace WpfApplication1 {
  public partial class Window1 : System.Windows.Window {

    public Window1() {
      InitializeComponent();
    //  this.DataContext = ((App)Application.Current).EventLog;
    }

    protected override void OnInitialized(EventArgs e) {
      base.OnInitialized(e);
      exceptionButton.Click += new RoutedEventHandler(exceptionButton_Click);
      shutdownButton.Click += new RoutedEventHandler(shutdownButton_Click);
    }

    void exceptionButton_Click(object sender, RoutedEventArgs e) {
      throw new Exception("Opps! Unhandled exception!");
    }

    void shutdownButton_Click(object sender, RoutedEventArgs e) {
      Application.Current.Shutdown(111);
    }

  }
}

   
    
     


Catch XamlParseException

image_pdfimage_print


   
  


<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="FlowDocReader Load/Save Sample" Width="640" Height="480">
  <StackPanel>
    <FlowDocumentReader Name="FlowDocRdr" Grid.Row="1"/>
  </StackPanel>
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Windows.Markup;

namespace WpfApplication1
{

    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();

            FlowDocument content = null;
            
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "FlowDocument Files (*.xaml)|*.xaml|All Files (*.*)|*.*";

            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileStream xamlFile = openFile.OpenFile() as FileStream;
                if (xamlFile == null) return;
                else
                {   
                    try 
                    { 
                        content = XamlReader.Load(xamlFile) as FlowDocument; 
                        if (content == null) 
                            throw(new XamlParseException("The specified file could not be loaded as a FlowDocument."));
                    }
                    catch (XamlParseException e)
                    {
                        String error = "There was a problem parsing the specified file:

";
                        error += openFile.FileName;
                        error += "

Exception details:

";
                        error += e.Message;
                        System.Windows.MessageBox.Show(error);
                        return;
                    }
                    catch (Exception e) 
                    {
                        String error = "There was a problem loading the specified file:

";
                        error += openFile.FileName;
                        error += "

Exception details:

";
                        error += e.Message;
                        System.Windows.MessageBox.Show(error);
                        return;
                    }

                    FlowDocRdr.Document = content;
                }
            }
        }
    }
}

   
    
     


Manage unhandled exceptions that are thrown on secondary user interface (UI) threads.

image_pdfimage_print
   
  


<Application
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="WpfApplication1.App"
  StartupUri="MainWindow.xaml" 
  DispatcherUnhandledException="App_DispatcherUnhandledException" />

//File:Window.xaml.cs
using System; 
using System.Text; 
using System.Windows;
using System.Windows.Threading; 

namespace WpfApplication1
{
    public partial class App : Application
    {
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}
", e.Exception.InnerException.Message);
            sb.AppendFormat("{0}
", e.Exception.Message);
            sb.AppendFormat("Exception handled on main UI thread {0}.", e.Dispatcher.Thread.ManagedThreadId);
            MessageBox.Show(sb.ToString());

            e.Handled = true;
        }
    }
}