Error 'specified method is not supported'. Get call stack - c#

My application is giving an error 'specified method is not supported' on a client pc. I do not know where the problem is coming from. He does not have Visual Studio installed so its impossible to debug.
Is there any way to get a call stack in WPF if I write some debug code in the application and give him the new exe?

You can subscribe to DispatcherUnhandledException to capture the unhandled exception at application level and to log stack trace of exception.
Example of DispatcherUnhandledException in App.xaml.cs
public App() {
this.DispatcherUnhandledException += OnDispatcherUnhandledException;
}
void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
e.Handled = true;
}
In a big picture you can capture a exception at :
You can trap unhandled exceptions at different levels:
AppDomain.UnhandledException From all threads in the AppDomain.
Dispatcher.UnhandledException From a single specific UI dispatcher
thread.
Application.DispatcherUnhandledException From the main UI
dispatcher thread in your WPF application.
TaskScheduler.UnobservedTaskException from within each AppDomain
that uses a task scheduler for asynchronous operations. You should
consider what level you need to trap unhandled exceptions at.
Deciding between #2 and #3 depends upon whether you're using more than one WPF thread.

Related

Why does my program loop on exception when debugging? [duplicate]

(This looks very similar to C# UnhandledException from another thread keeps looping, but am not trying to catch the exception here, just get the chance to log something)
I have some very simple C# code that sets up an UnhandledException event handler, then throws an exception:
class Program
{
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
//currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
currentDomain.UnhandledException += (sender, eventArgs) =>
{
var exception = (Exception) eventArgs.ExceptionObject;
Console.WriteLine("Unhandled exception: " + exception.Message);
};
throw new AccessViolationException("Bleurgh");
}
}
It behaves as I expect from the console:
Unhandled exception: Bleurgh
Unhandled Exception: System.AccessViolationException: Bleurgh
at UnhandledExceptions.Program.Main(String[] args) in c:\code\sandbox\UnhandledExceptions\UnhandledExceptions\Program.cs:line 20
But when I attempt to debug it in Visual Studio it enters a loop, going into the event handler then dropping out to rethrow the Exception.
The same thing happens when I express the handler as a distinct static method.
Any ideas what's going on?
This is in Visual Studio 2010. EDIT: and .NET 4.
It seems to be down to the behaviour of the ExceptionAssistant specfically. When you continue, the assistant unwinds the call stack to the point at which the exception was thrown -- which causes the exception to be rethrown. I assume this is to allow you to make changes that would allow you to avoid the exception.
If under Tools\Options\Debugger\General you uncheck "Unwind the call stack on unhandled exceptions" then it'll just behave as an independent process would behave, and you'll see the process terminate.
This is how the debugger works, or shall we say, a "feature". If process is created by a debugger (F5) then debugger will prevent process termination, and point you to the line of code that would cause the process termination. Those "unhandled exceptions" are actually handled by the debugger, and so the execution never reaches to your code.
If debugger is attached to the process after the process was created (Ctrl+F5, and then attach) then debugger will eventually reach the unhandled exception "handler", but after exiting the handler it will still prevent process termination, and bring you back to the point where exception occurred.

Why is Visual Studio looping when debugging UnhandledException events

(This looks very similar to C# UnhandledException from another thread keeps looping, but am not trying to catch the exception here, just get the chance to log something)
I have some very simple C# code that sets up an UnhandledException event handler, then throws an exception:
class Program
{
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
//currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
currentDomain.UnhandledException += (sender, eventArgs) =>
{
var exception = (Exception) eventArgs.ExceptionObject;
Console.WriteLine("Unhandled exception: " + exception.Message);
};
throw new AccessViolationException("Bleurgh");
}
}
It behaves as I expect from the console:
Unhandled exception: Bleurgh
Unhandled Exception: System.AccessViolationException: Bleurgh
at UnhandledExceptions.Program.Main(String[] args) in c:\code\sandbox\UnhandledExceptions\UnhandledExceptions\Program.cs:line 20
But when I attempt to debug it in Visual Studio it enters a loop, going into the event handler then dropping out to rethrow the Exception.
The same thing happens when I express the handler as a distinct static method.
Any ideas what's going on?
This is in Visual Studio 2010. EDIT: and .NET 4.
It seems to be down to the behaviour of the ExceptionAssistant specfically. When you continue, the assistant unwinds the call stack to the point at which the exception was thrown -- which causes the exception to be rethrown. I assume this is to allow you to make changes that would allow you to avoid the exception.
If under Tools\Options\Debugger\General you uncheck "Unwind the call stack on unhandled exceptions" then it'll just behave as an independent process would behave, and you'll see the process terminate.
This is how the debugger works, or shall we say, a "feature". If process is created by a debugger (F5) then debugger will prevent process termination, and point you to the line of code that would cause the process termination. Those "unhandled exceptions" are actually handled by the debugger, and so the execution never reaches to your code.
If debugger is attached to the process after the process was created (Ctrl+F5, and then attach) then debugger will eventually reach the unhandled exception "handler", but after exiting the handler it will still prevent process termination, and bring you back to the point where exception occurred.

Getting exception that caused program to crash without being in debug mode

I have an application in C# that I want to run by just running the .exe from my desktop. However, I'm pretty sure there will be some type of error that will make the program crash. Is there a way to write the problem that caused the program to crash to a text file, so that I can see what caused the issue when users are using the program? I know I can use debug mode to do this but I want to run the application as a stand alone not inside of VS.
Thanks,
I am aware of the try catch blocks and I am already using those where problems might occur. But I am speaking in general. For example if I wasn't sure where the problem would occur. There is no way to print this specific error to a file.
You can try the global try/catch method except that if there is an exception on a background thread it won't be caught. You can use AppDomain.UnhandledException if you want to be notified of any unhandled exception in the appdomain (msdn). You would signup in main before the rest of your program executes like so:
static void Main(string[] args)
{
AppDomain.UnhandledException += WriteUnhandledExceptionToFile;
// rest of program
}
static void WriteUnhandledExceptionToFile(object sender, UnhandledExceptionEventArgs args)
{
// write to where ever you can get it.
string path = Path.Combine(Environment.CurrentDirectory, "UnhandledException.txt");
File.WriteAllText(path, args.ExceptionObject.ToString()); // will print message and full stack trace.
}
Edit
Note that by default Windows Forms and WPF catch any exceptions that are thrown on the UI thread. You will have to subscribe to the Application.ThreadException event (forms) or Application.DispatcherUnhandledException event (wpf) to be notified of exceptions on those threads. The code would be very similar to the code above for the AppDomain event.
Have a global exception handler that writes the exception details to a file.
If you wrap the code in your Main method in a try{}catch{} block, you can write out the exception details in the catch block.
try
{
// Calls to application code
}
catch(Exception ex)
{
// log `ex.ToString()`
throw; // rethrow to ensure termination optionally: `Application.Exit`
}
Even if you aren't logging the problem, you can usually get the error in question from the event viewer within windows.
The first thing you want to look at is the try/catch construct in C#. This is probably your first building block to handling errors.
As for how you handle the errors, that's entirely up to you. Currently your only stated goal is to log them to a file. You can get a lot of details out of the Exception object that you catch and you can write those details to a file. Additionally, you can use logging libraries to help with that sort of thing.
Proper error handling is something of a big subject, really. One thing to keep in mind is logically where you want to catch the exception. Ideally, you want to catch it where you can handle it. That is, where your code can sufficiently recover from the error. If it's a fatal error and the application should stop entirely, then you can throw the exception further up the stack and let it go unhandled (though still logged where you caught it).
If, however, you're in a logical condition where you can just log the error and move on, then the catch block allows you to do just that. Log the details, update the state of any objects/data which need to be updated, and continue with the flow of the application.
you can surround your one of the starting method with try catch block
try
{
///Your code
}
catch(Exception exception)
{
System.IO.File.WriteAllLines("ErrLog.txt", exception.Message);
}
As a permanent solution you can create extension method ToLog and use it whenever you want.
public static void ToLog(this Exception Exception)
{
using (var file = File.AppendText("ErrorLog.txt"))
{
file.WriteLine(DateTime.Now + " : " + exception.Message);
}
}
You can use it in catch block like this
catch(Exception exception)
{
exception.ToLog();
}
See initial information here http://www.csharp-examples.net/catching-unhandled-exceptions/
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");
}
The UnhandledException event handles uncaught exceptions thrown from the main UI thread. The ThreadException event handles uncaught exceptions thrown from non-UI threads.
I would replace the MessageBox with some actual logging (log4net or others). This would give you the ability to log out the errors to another server for distributed applications, file system for local users, event logs, options are fairly unlimited if you're willing to put in the time.

Getting Windows error reporting dialog

In my C# app, even I handle exception :
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
and then in handler showing dialog box and doing Application.Exit
still getting windows error reporting dialog with Send, Don't Send...
How to prevent windows error reporting dialog from popping up?
In fact if the exception is thrown from main form constructor then the program ends up with Windows error report dlg. Otherwise if from some other location of UI thread, then as expected.
You'll need to terminate the app yourself. This will do it:
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
var ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.ToString());
if (!System.Diagnostics.Debugger.IsAttached)
Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(ex));
}
The dialog that presents the choice to send or not send an error report to Microsoft is beyond exceptions. This might happen if you use unsafe{} blocks or you use p/invoke's which perform some illegal operation.
I think you should not be fighting the symptoms of your problem. The unhandled exceptions should not happen in the first place.
Do you have any clues on what is causing them?

How can I set up .NET UnhandledException handling in a Windows service?

protected override void OnStart(string[] args)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Thread.Sleep(10000);
throw new Exception();
}
void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
}
I attached a debugger to the above code in my windows service, setting a breakpoint in CurrentDomain_UnhandledException, but it was never hit. The exception pops up saying that it is unhandled, and then the service stops. I even tried putting some code in the event handler, in case it was getting optimized away.
Is this not the proper way to set up unhandled exception handling in a windows service?
The reason that the UnhandledException event on the current AppDomain does not fire is how services are executed.
User sends a Start command from the Windows Service Control Manager (SCM).
The command is received by the framework's ServiceBase implementation and dispatched to the OnStart method.
The OnStart method is called.
Any exception which is thrown by OnStart is handled in the base class, logged to the Event Log, and translated into an error status code returned to the SCM. So the exception never propagates to the AppDomain's unhandled exception handler.
I think you would find that an unhandled exception thrown from a worker thread in your service would be caught by the AppDomain's unhandled exception handler.
In a Windows Service you do NOT want to be running much code in the OnStart method. All you want there is the code to launch your service thread and then return.
If you do that you can handle exceptions that happen in your service thread just fine.
e.g.
public static void Start()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
running = true;
ThreadStart ts = new ThreadStart(ServiceThreadBody);
thread = new Thread(ts);
thread.Name = "ServiceThread";
thread.Priority = ThreadPriority.BelowNormal;
thread.Start();
}
When I was working on my own Windows Service, it was stoping itself oddly enough. I thought it was because of unhanded exception. At the moment I am catching unhanded exceptions on text file. First of all you have to create new file ServiceLog.txt on C locations due to logging excaptions on text file. With below coding I got all unhanded exceptions with them line numbers.
using System.Security.Permissions;
using System.IO;
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
protected override void OnStart(string[] args)
{ AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
...
Your codes...
....
}
void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
WriteToFile("Simple Service Error on: {0} " + e.Message + e.StackTrace);
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
Know this thread is a bit old, but thought it would be useful to add some comments based on personal experience developing Windows services in .NET. The best approach is to avoid developing under the Service Control Manager as much as you can - for this you need a simple harness that mimics the way services get started - something that can create an instance of your service class (that you already derived from ServiceBase) and call your OnStart, OnStop etc methods. This harness can be a console app or a Windows app as you desire.
This is pretty much the only way I have found of debugging service start-up issues in .NET - the interaction between your code, Visual Studio and the real Service Control Manager just makes the process impossible otherwise.
HTH.
Just curious, what are you trying to accomplish: avoiding service crashing, or reporting errors?
For reporting, I think your best bet is to add top-level try/catch statements. You can try to log them to the Windows event log and/or a log file.
You can also set the ExitCode property to a non-zero value until you successfully stop the service. If the system administrator starts your service from the Services control panel, and your service stops suddenly with a non-zero exit code, Windows can show an error message with the description of the error.

Categories

Resources