Hi I try implement solution from this site im my WPF app for global exception handling.
http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications.aspx
I use Caliburn Micro as MVVM framework. Service I have in external assembly and it is injected in view model class with MEF.
Here is my implementation for global exception handling in WPF app.
App.xaml
DispatcherUnhandledException="Application_DispatcherUnhandledException"
Startup="Application_Startup"
App class:
public partial class App : Application
{
private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();
public bool DoHandle { get; set; }
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void Application_DispatcherUnhandledException(object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (DoHandle)
{
_msgBox.ShowException(e.Exception);
e.Handled = true;
}
else
{
_msgBox.ShowException(e.Exception);
e.Handled = false;
}
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
_msgBox.ShowException(ex);
}
}
Service method from external assembly:
public void ServiceLogOn()
{
try
{
}
catch (Exception ex)
{
throw ex;
}
}
This service method is call in view model class for example on button click event:
[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen, ILogOnViewModel
{
public void LogOn()
{
_service.ServiceLogOn();
}
}
I run WPF app in Visual Studio and produce exception with message "Bad credentials" in ServiceLogOn method.
I expect that I see the message box with the exception.
But Visual Studio stop debuging app and show exception in service method in service project.
So I try run WPF from exe file and produce same exception in ServiceLogOn method.
I get this error:
Exception has been throw by target of an invocation.
Any exception from view model class is not handled in methods:
Application_DispatcherUnhandledException
or CurrentDomain_UnhandledException.
in App class.
What I do bad?
EDITED with Simon Fox’s answer.
I try implement in MEF bootstraper advice of Simon Fox’s, but I still something do wrong.
I move handle logic for exception to OnUnhandledException method in bootstraper class.
Here is my code from bootstraper class:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
//...
private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();
public bool DoHandle { get; set; }
protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (DoHandle)
{
_msgBox.ShowException(e.Exception);
e.Handled = true;
}
else
{
_msgBox.ShowException(e.Exception);
e.Handled = false;
}
}
//...
}
I bind some method from view model on button and throw new exception. Something like this:
public void LogOn()
{
throw new ArgumentException("Bad argument");
}
But result is sam, I test app out of Visual Studio and get this exception.
Exception has been throw by target of an invocation.
Caliburn.Micro has built in support for hooking unhandled exceptions. The Bootstrapper class (which every Caliburn project requires) sets this up for you and provides the virtual OnUnhandledException method.
In your custom BootStrapper you must override OnUnhandledException to perform any custom actions for unhandled exceptions in your app. Note that you will most likely have to marshal actions such as displaying a message box to the UI thread (Caliburn enables this easily via Execute.OnUIThread).
You may also have an issue in the way your service moves exceptions to the client, but without any details of how the service is implemented/hosted/etc I cannot help. Are you using WCF to do SOAP? Are you using FaultContracts?
Related
We use the CefSharp's ChromiumWebBrowser control (83.4.20) in Windows Forms application.
We hook up the IsBrowserInitializedChanged event to know when the browser control was initialized so we can start loading our web application. Occasionally this event is not fired at all so our application will be stuck and won't load the web app.
In case the app is stuck in initializing the ChromiumWebBrowser control, the WebView_IsBrowserInitializedChanged or WebView_LoadError are not fired:
public MainForm()
{
InitializeComponent();
this.webView.IsBrowserInitializedChanged += WebView_IsBrowserInitializedChanged;
this.webView.LoadError += WebView_LoadError;
}
private void InitializeComponent()
{
this.webView = new CefSharp.WinForms.ChromiumWebBrowser();
// usual WinForms initialization code from the designer
// ...
}
private void WebView_IsBrowserInitializedChanged(object sender, EventArgs e)
{
if (this.webView.IsBrowserInitialized)
{
this.webView.Load(this.ApplicationUri.AbsoluteUri);
}
}
private void WebView_LoadError(object sender, LoadErrorEventArgs e)
{
// handle the error
// ...
}
Are there any other events we can subscribe to to monitor the state of CefSharp and the browser control which would aid as in troubleshooting this situation?
Hi I try log expcetion on App Domain with NLog. It is WPF app with Caliburn Micro.
In MEF bootstraper I have this code:
static readonly ILog Log = LogManager.GetLog(typeof(NLogLogger));
#region Constructors
public MefBootStrapper()
: base()
{
_msgBox = new MessageBoxes();
_doHandle = true;
}
static MefBootStrapper()
{
LogManager.GetLog = type => new NLogLogger(type);
}
#endregion
#region Exception handling on App Domain
protected override void OnUnhandledException(object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (_doHandle)
{
Log.Error(e.Exception.InnerException);
_msgBox.ShowException(e.Exception.InnerException);
e.Handled = true;
}
else
{
Log.Error(e.Exception.InnerException);
_msgBox.ShowException(e.Exception);
e.Handled = false;
}
}
#endregion
When I run app and throw exception from view modle class it show message box that is ok but exception is not logged to file.
I try log exception in view model calls:
something like this: Log.Error(new Exception("4"));
This work, but If i try log exception in OnUnhandleException method it doesnt wokr. Why?
Your problem is that the static field Log gets initialized before your static constructor runs see (Static field initialization). So you will have your Log field with the default Caliburn Nulloger initialized instead of your NLogLogger. You should move the Log field initialization into your static constructor.
private static readonly ILog Log;
static MefBootStrapper()
{
LogManager.GetLog = type => new NLogLogger(type);
Log = LogManager.GetLog(typeof(NLogLogger));
}
I am using PRISM 4 and got my head around almost all features, however as soon as I would like to inject my DomainContext class (RIA) into my view model, the hell breaks loose. :) It would be great if an experienced Unity/Prism developer could give me an advice how to proceed.
Within my bootstrapper, I am registering the required class in Unity Container like this:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<SCMDomainContext>();
}
Within the NavigationModule, I have the following in the ctor to register the NavigationView with a particular region.
public NavigationModule(IUnityContainer container, IRegionManager regionManager)
{
_container = container;
_regionManager = regionManager;
_regionManager.RegisterViewWithRegion(Constants.NavRegion, () => _container.Resolve<NavigationView>());
}
The View takes the View Model as dependency:
public NavigationView(NavigationViewModel viewModel)
{
InitializeComponent();
Loaded += (s, e) =>
{
DataContext = viewModel;
};
}
The ViewModel has the following:
public NavigationViewModel(SCMDomainContext context)
{
_context = context;
ConstructCommon();
}
As soon as I comment this ctor out and put a en empty ctor, it is all fine, for some reason I can't resolve the SCMDomainContext class. Which is the one you add to have the Domain Context created for you provided by Ria Services.
Since I am using Silverlight, I can't see the stack trace to follow the exception, all I get is this message on a page. What am I missing please?
Microsoft JScript runtime error: Unhandled Error in Silverlight Application An exception occurred while initializing module 'NavigationModule'.
- The exception message was: Activation error occured while trying to get instance of type NavigationModule, key ''
Check the InnerException property of the exception for more information. If the exception occurred
while creating an object in a DI container, you can exception.GetRootException() to help locate the
root cause of the problem. at Microsoft.Practices.Prism.Modularity.ModuleInitializer.HandleModuleInitializationError(ModuleInfo moduleInfo, String assemblyName, Exception exception)
at Microsoft.Practices.Prism.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
at Microsoft.Practices.Prism.Modularity.ModuleManager.LoadModulesThatAreReadyForLoad()
at Microsoft.Practices.Prism.Modularity.ModuleManager.IModuleTypeLoader_LoadModuleCompleted(Object sender, LoadModuleCompletedEventArgs e)
at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e)
at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.HandleModuleDownloaded(DownloadCompletedEventArgs e)
at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.IFileDownloader_DownloadCompleted(Object sender, DownloadCompletedEventArgs e)
at Microsoft.Practices.Prism.Modularity.FileDownloader.WebClient_OpenReadCompleted(Object sender, OpenReadCompletedEventArgs e)
at System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e)
at System.Net.WebClient.OpenReadOperationCompleted(Object arg)
Your help on this is highly appreciated,
Kave
I can't see much wrong here. But having said that, I'm using the Initialize method from the interface in the following way to register types and views for regions:
#region properties
[Dependency]
public IUnityContainer Container { get; set; }
[Dependency]
public IRegionManager RegionManager { get; set; }
#endregion
public virtual void Initialize()
{
this.Container.RegisterType<NavigationViewModel>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<NavigationView>(new ContainerControlledLifetimeManager());
this.RegionManager.RegisterViewWithRegion(Constants.NavRegion, () => this.Container.Resolve<NavigationView>());
}
Not sure whether it makes a difference if you don't explicitly register the ViewModel and the View type. Personally I prefer to have control over the way how a type gets resolved by the container.
In fact its best to create a layer for the DomainContext like this. Then its easily resolvable by an IoC:
public class ContactModuleService : IContactModuleService
{
readonly SCMDomainContext _context = new SCMDomainContext();
#region Implementation of IContactModuleService
public EntitySet<Contact> Contacts
{
get { return _context.Contacts; }
}
public EntityQuery<Contact> GetContactsQuery()
{
return _context.GetContactsQuery();
}
public SubmitOperation SubmitChanges(Action<SubmitOperation> callback, object userState)
{
return _context.SubmitChanges(callback, userState);
}
public SubmitOperation SubmitChanges()
{
return _context.SubmitChanges();
}
public LoadOperation<TEntity> Load<TEntity>(EntityQuery<TEntity> query, Action<LoadOperation<TEntity>> callback, object userState) where TEntity : Entity
{
return _context.Load(query, callback, userState);
}
public LoadOperation<TEntity> Load<TEntity>(EntityQuery<TEntity> query) where TEntity : Entity
{
return _context.Load(query);
}
#endregion
}
Just as there is "treat warning as errors" set in our projects to catch early possible problems, I would love to have a runtime exception to catch them early.
I have recently been bit by this problem and I would have been glad to have this.
Can it be done? And if yes, how?
You could hook into the PresentationTraceSources collection with your own listener:
public class BindingErrorListener : TraceListener
{
private Action<string> logAction;
public static void Listen(Action<string> logAction)
{
PresentationTraceSources.DataBindingSource.Listeners
.Add(new BindingErrorListener() { logAction = logAction });
}
public override void Write(string message) { }
public override void WriteLine(string message)
{
logAction(message);
}
}
and then hook it up in code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
BindingErrorListener.Listen(m => MessageBox.Show(m));
InitializeComponent();
DataContext = new string[] { "hello" };
}
}
Here is the XAML with a binding error
<Grid>
<TextBlock Text="{Binding BadBinding}" />
</Grid>
I implemented a solution very similar to the one proposed by Dean Chalk:
Derived a TraceListener that throws instead of logging
Added that listener to PresentationTraceSources.DataBindingSource
Please see the complete solution on GitHub, it includes a demo application and a unit test project.
First add this class to your project:
using System.Diagnostics;
namespace WpfTestApp
{
public class BindingErrorListener : TraceListener
{
public static void Register()
{
PresentationTraceSources.DataBindingSource.Listeners.Add(new BindingErrorListener());
}
public override void Write(string message)
{
}
public override void WriteLine(string message)
{
#if DEBUG
throw new System.Exception(message);
#endif
}
}
}
Then call the Register method in your App.xaml.cs class:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
BindingErrorListener.Register();
// ...
}
}
This way, (by throwing an exception) if you have any binding errors then you will be aware of those errors in the first place, that is, as soon as you start (F5) your application. If you wish, you can log those by injecting your logger object in the BindingErrorListener constructor.
I'm using the following code to display unhandled exceptions in a WPF application:
public MyApplication() {
this.DispatcherUnhandledException += (o, e) => {
var exceptionMessage = new ExceptionWindow();
exceptionMessage.ExceptionMessage.Text = e.Exception.Message;
exceptionMessage.ExceptionCallStack.Text = e.Exception.StackTrace;
exceptionMessage.ExceptionInnerException.Text = e.Exception.InnerException.Message;
exceptionMessage.WindowStartupLocation = WindowStartupLocation.CenterScreen;
exceptionMessage.WindowStyle = WindowStyle.ToolWindow;
exceptionMessage.ShowDialog();
e.Handled = true;
Shell.Close();
};
}
Turns out that I have an exception during the instantiation of the application, so the app constructor is never executed.
A simple way to reproduce it (with a different exception) is by introducing an extra "<" before some tag in your app's configuration file and run it.
A useless error message like that appears before the application constructor get called.
alt text http://srtsolutions.com/cfs-filesystemfile.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/mikewoelmer/ExceptionWPF1_5F00_1C1F39AA.jpg
Does anyone know how to catch such kind of exceptions?
Remark: I'm using Caliburn and my application extends CaliburnApplication.
Okay. I solved the problem by doing the following:
Change the Build Action of the App.xaml file from ApplicationDefinition to Page.
Create a new class like following:
public class AppStartup {
[STAThread]
static public void Main(string[] args) {
try {
App app = new App();
app.InitializeComponent();
app.Run();
}
catch (Exception e) {
MessageBox.Show(e.Message + "\r\r" + e.StackTrace, "Application Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
It replaces the generated App.g.cs Main method by this one, so we have a chance to catch the exceptions.