Wednesday, August 14, 2013

Application Exception Handler in WPF application

In WPF application I want to get all the exception in one place for that the below code will help you to capture all the exception in one place. It’s a global exception handling page. In the App.xaml file you need to specify the Startup and DispatcherUnhandledException method you need to give in XAML file. Global application exception handler or maintain application Error log to use below code.

This is the App.XAML file:



<Application x:Class="LiveSourceSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             DispatcherUnhandledException="Application_DispatcherUnhandledException"
    Startup="Application_Startup"
             StartupUri="PreviewUI.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>




In the App.XAML.CS file you need to add the Application start event and other exception event method need to create to capture the exceptions. The below code will help you to get application startup exception and other all the exception will be handled.



using System.IO;
using System.Windows.Forms;


public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // UI Exceptions
            this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

            // Thread exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        }

        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            var exception = e.Exception;
            HandleUnhandledException(exception);
        }

        private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
        {
            HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
            if (unhandledExceptionEventArgs.IsTerminating)
            {
                Comman.ErrorLog("Application is terminating due to an unhandled exception in a secondary thread.");
            }
        }

        private void HandleUnhandledException(Exception exception)
        {
            string message = "Unhandled exception";
            try
            {
                AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
                message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
            }
            catch (Exception exc)
            {
                Comman.ErrorLog("Exception in unhandled exception handler - "+ exc.Message);
            }
            finally
            {
                Comman.ErrorLog(message+ exception.Message);
            }
        }
    }


Error Log Function:

 public class Comman
    {
 public static void ErrorLog(string sMessage)
       {
           StreamWriter objSw = null;
           try
           {
               string sFolderName = Application.StartupPath + @"\Logs\";
               if (!Directory.Exists(sFolderName))
                   Directory.CreateDirectory(sFolderName);
               string sFilePath = sFolderName + "Error.log";

               objSw = new StreamWriter(sFilePath, true);
               objSw.WriteLine(DateTime.Now.ToString() + " " + sMessage + Environment.NewLine);

           }
           catch (Exception ex)
           {
               Comman.ErrorLog("Error -" + ex.Message);
           }
           finally
           {
               if (objSw != null)
               {
                   objSw.Flush();
                   objSw.Dispose();
               }
           }
       }
}


No comments: