so I was trying to add "AppDomain.CurrentDomain.UnhandledException" handler to my application and it worked OK if I log the error to a text file. but when I try to use a MessageBox it never pops. is it another bug in .Net? any ideas?
here is my code sample:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
and here is my handler method:
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Whoops! Please contact the developers with "
+ "the following information:\r\n\r\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
EDIT: I've tried all of the possible options but I still can't see the MessageBox. Now the problem is when I run it from Visual C# (debug mode) it perfectly shows the box. but when I run the application directly from the debug/release folders it doesn't shows the MessageBox and the Application keeps running like there is no error is happening...
this example works for me in debug mode and release mode with vs2010 or not:
using System;
using System.Windows.Forms;
namespace WinFormsStackOverflowSpielWiese
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main() {
System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
try {
var exception = e.Exception != null ? e.Exception.Message + e.Exception.StackTrace : string.Empty;
MessageBox.Show("Whoops! Please contact the developers with the following information:\r\n\r\n" + exception,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally {
Application.Exit();
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
try {
var exception = e.ExceptionObject is Exception ? ((Exception)e.ExceptionObject).Message + ((Exception)e.ExceptionObject).StackTrace : string.Empty;
MessageBox.Show("Whoops! Please contact the developers with the following information:\r\n\r\n" + exception,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally {
Application.Exit();
}
}
}
}
code for the form
EDIT now with a timer, with the same result....
using System.Windows.Forms;
namespace WinFormsStackOverflowSpielWiese
{
public partial class Form1 : Form
{
private System.Threading.Timer myTimer;
public Form1() {
this.InitializeComponent();
this.myTimer = new System.Threading.Timer(state =>
{
var i = 0;
var s = 100 / i;
}
, null, 5000, 5000);
}
}
}
The case might be because Unhandled Exceptions cause the application to terminate silently and UnhandledExceptionEventHandler handles non-UI thread exceptions.
See Application.SetUnhandledExceptionMode Method, AppDomain.UnhandledException Event and Application.ThreadException Event
EDIT:
Try setting Application.SetUnhandledExceptionMode as per first link:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //add this line
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Related
I'm developing a dnn module. And i used codebehind C#. But DNN shows error when I add a the module. Other pages work just fine but the page I add the module to says DotNetNuke error. The error does not have any code and it only displays my logo. Even the admin strip disappears.
What did i do wrong?
using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI;
using System.Configuration;
//imports
namespace DotNetNuke.Modules.Catagory
{
public partial class View : CatagoryModuleBase, IActionable
{
public bool inEdit = false;
private bool IsValid = true;
#region Event Handlers
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
private void Page_Load(object sender, System.EventArgs e)
{
try
{
if (IsPostBack)
{
if (Catagory_Table.SelectedRow != null)
{ //There is a selected item, hence edit mode Catagory_Table.SelectedIndex >= 0
this.inEdit = true;
to_edit_mode();
}
else
{
to_add_mode();
}
}
else
{
to_add_mode();
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void Button1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
SqlDataSource1.Insert();
}
//the rest if the methods to handle the buttton events....
}
You will want to try to check the Admin/Event Viewer to see what the error is specifically, then you can be better informed on what it will take to fix.
I am trying to understand why the DispatcherTimer contained within SingletonWithTimer is not firing in the following WPF application. I've been researching this for a couple of days and cannot seem to get to the bottom it. This application is the reduced essential parts of an existing application that I'm trying to fix. The Startup object of this project is WPFApplication5TimerTest.Program.
The output in the console lists as follows, the problem is evident because the word "TimerTick" is not shown in the output:
Timer is initialized
'WpfApplication5TimerTest.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework.Aero\v4.0_4.0.0.0__31bf3856ad364e35\PresentationFramework.Aero.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Sample thread
Sample thread
Sample thread
Sample thread
Sample thread
Sample thread
The thread '<No Name>' (0x10b0) has exited with code 0 (0x0).
Sample thread exiting!
This is Program.cs:
using System;
namespace WpfApplication5TimerTest
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
AppObject = new App();
AppObject.Run();
}
public static App AppObject
{
get;
private set;
}
}
}
This is App.xaml.cs:
using System;
using System.Threading;
using System.Windows;
namespace WpfApplication5TimerTest
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
var sampleThread = new Thread(new ThreadStart(SampleThreadEntryPoint));
sampleThread.Start();
new MainWindow().Show();
}
private void SampleThreadEntryPoint()
{
SingletonWithTimer.Initialize();
while (!_shutdownEvent.WaitOne(1000))
Console.WriteLine("Sample thread");
Console.WriteLine("Sample thread exiting!");
}
protected override void OnExit(ExitEventArgs e)
{
_shutdownEvent.Set();
}
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
}
}
This is MainWindow.xaml.cs:
using System;
using System.Windows;
namespace WpfApplication5TimerTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Closed(object sender, EventArgs e)
{
Program.AppObject.Shutdown();
}
}
}
This is SingletonWithTimer.cs:
using System;
using System.Windows.Threading;
namespace WpfApplication5TimerTest
{
public class SingletonWithTimer
{
private static SingletonWithTimer Instance
{
get
{
if (_instance == null)
{
_instance = new SingletonWithTimer();
}
return _instance;
}
}
public static void Initialize()
{
SingletonWithTimer.Instance._timer = new DispatcherTimer();
SingletonWithTimer.Instance._timer.Interval = TimeSpan.FromSeconds(2);
SingletonWithTimer.Instance._timer.Tick += new EventHandler(SingletonWithTimer.Instance.OnTimerTick);
SingletonWithTimer.Instance._timer.Start();
Console.WriteLine("Timer is initialized");
}
private void OnTimerTick(object sender, EventArgs e)
{
Console.WriteLine("TimerTick");
}
private static SingletonWithTimer _instance;
private DispatcherTimer _timer = null;
}
}
It's because you've created the DispatcherTimer on another (non-UI) thread. Hence, it will be tied to the Dispatcher on that thread, not the one on the UI thread. Since nothing is running the Dispatcher on that thread, it will never fire.
Either create the DispatcherTimer on the UI thread, or use a constructor overload that allows you to pass in a specific Dispatcher to use.
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?
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.
I'm getting this Exception
System.InvalidOperationException was
unhandled by user code Message="The
calling thread cannot access this
object because a different thread owns
it."
whenever I run the following code
public partial class MainScreen : Window
{
Timer trm;
public MainScreen()
{
InitializeComponent();
trm = new Timer(1000);
trm.AutoReset = true;
trm.Start();
trm.Elapsed += new ElapsedEventHandler(trm_Elapsed);
}
void trm_Elapsed(object sender, ElapsedEventArgs e)
{
lblTime.Content = System.DateTime.Now;
}
}
guys any solution... I badly wann come out of it :(
Use DispatcherTimer instead:
public partial class MainScreen : Window{
DispatcherTimer tmr;
public MainScreen() {
InitializeComponent();
tmr = new DispatcherTimer();
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
}
void tmr_Tick(object sender, EventArgs e) {
lblTime.Content = System.DateTime.Now;
}
}
Any time you modify Windows controls you must do so on the UI thread (the one that created the controls).
See this question for lots of details.
To be short, you should use Dispatcher.Invoke method to update UI elements.