WPF Application Error Handleing - wpf

I followed the example below for global exception trapping in WPF. In the example he throws a null pointer exception in a try-catch block and then another outside the block. The second is supposed to be handled in the app.xaml.cs file in the Application_DispatcherUnhandledException() procedure. This procedure is subscribed to in the app.xaml file with DispatcherUnhandledException="Application_DispatcherUnhandledException".
For me it does not work. Any ideas why? I am in VS 2010 and I think this tutorial is for VS 2012. Perhaps the behavior changed between versions.
http://www.wpf-tutorial.com/wpf-application/handling-exceptions/
Greg

The version of visual studio wouldnt affect this sort of behaviour.
I tried the example you linked to and it worked as expected for me.
Are you running it in Debug? If so Visual Studio will catch the unhandled exception before your handler would do (depending on how you have exceptions set up). Try running it using 'Start without debugging' and see if you hit the secind Message Box.

Related

Explain critical bug in Visual Studio 2010 and up, WinForms and WPF

Try putting the following code inside Load event handler for WinForms or Loaded for WPF.
Dim doc As New XmlDocument
Dim nsmgr As New XmlNamespaceManager(Nothing) 'this line throws an exception
Problem is that exception is not thrown, and stack corruption happens. It may have different side effects, depending on the IDE - see below.
Affected IDEs are: 2008, 2010 and 2012 (those I could test). 2010 resets stack state, and returns from sub/handler, like nothing happened (but without proceeding with other statements there). 2012 may warn a user about a failed application and an attempt to run in compatibility mode. Next time after that it runs the same as 2010. 2008 properly throws an exception, but only on default configuration (AnyCPU). Switching platform target to x86 makes the problem reappear in 2008 as well.
Affected frameworks are WinForms and WPF. Console apps and ASP.NET
seem to work fine. .NET v2.0-4.5.
Affected scope is only Load event so far.
Putting this code into a button makes it work.
Affected build
configuration = any. Tried on default Debug and Release.
Why I consider it a bug is because it can leave objects in an unstable state - they did not finish initializing, which is not an expected behavior. What's critical about it is that nobody will know it happened, as it does not throw an exception. Depending on your design, you may end up with incorrect data in your database, which in the worst case may lead to severe consequences.
Does anyone have a good explanation to why this may be happening and if there is a workaround?
The problem is caused by the wow64 emulation layer that comes into play when you target x86 platform on a x64 OS.
It swallows exceptions in the code that is responsible to fire the Load event.
Thus the debugger doesn't see the exception and cannot step in to handle the situation.
This article seems to document well what's happening there,
This previous answer from Hans Passant (to which goes all the credits and upvotes) explains possible workarounds.
My preferite one is to move everything out of Form_Load event and put the problematic code in the form constructor. (Of course I don't know if it is applicable in your case)

Detecting Exceptions During Beta Testing

(see update below)
While running within the VisualStudio 2010 environment, I can easily tell if my Winform application causes an exception. I just have to go to Debug | Exceptions and make sure that both columns of checkboxes are checked. I then run the application and if any exceptions then I get dropped straight into the offending piece of code.
How do I determine exceptions during testing, when I give test build to a tester. I do not want the tester to run within Visual Studio, just as a regular user. I still want to know if there are exceptions and the pertinent details.
Obviosualy, I should be able to control the process, so that when the code gets released normal execution happens.
Yes, I know about and use try/catch blocks, but I am talking about a method similar to Visual Studio exception catcher and reporter, just possibly compiled into the product and used for deployment to beta testers.
Maybe Visual Studio has such a feature, in which case where and how to set up, or possibly a third party component.
[Update:
I added two sub-questions, which you can find at Unhandled Exception next line or exit.
The solution mentioned below sounds great and with a tweak probably works, just not at the moment.
Inside the Visual Studio both 2010 and now 2012 works great. The exception handler gets called, okay after VS breaks at the line and I say to continue. I decided to test outside the VS2012 IDE, good thing for that. The OS traps the bug, shows the standard an "An Unhandled Exception Occurred" dialog giving the details along with a continue and quit buttons. Selecting continue, just continues the application with no trapping into my uber exception handler. Selecting quite, whites-out the application and displays the standard close window dialog. The quit button also does not call my uber handler.
The purpose is so that my exception handler gets called. I do not need an uber exception handler if I am working inside the VS2012 IDE. The purpose of the handler is for end users and beta testers, namely anyone other than myself and who will not have my development station.
So unless I am missing something, the question is still open.
There are code samples in the other question, enough to copy and paste and create a test application in a couple minutes time.
]
Thanks in advance,
Sarah
I don't know of any automagical ways to reports error in Visual Studio but here is what I do.
Hook into the UnhandledException event for the application.
Use a logging framework like nLog or Log4Net to log the exception and other data you get from that event. Or just write to a text file.
Upload that data either from within your application or have the beta-tester send it to you.
Okay, the Google Uberlord took pitty upon me and I found this wonderful article solving the problem. Praise to the almighty Google.
Here is the link:
http://www.switchonthecode.com/tutorials/csharp-tutorial-dealing-with-unhandled-exceptions
Basically, JRadness had the right idea, just slightly in error. He should have used
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
rather than
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
The author on Switch on the Code talked of three methods, the first of which is what JRadness proposed and does not work for Windows forms.
The autor even solved my other question of Continue and Abort. The OS got bypassed.
Yeah!!

OpenFileDialog crashes under Windows XP, but not Windows 7

I've got a strange problem I haven't seen before. I can open an OpenFileDialog in Windows 7 without any problems. However, when I try my app on Windows XP, calling OpenFileDialog.ShowDialog() immediately crashes the application. It just vanishes! When running from the debugger, I don't get any unhandled exceptions. If I wrap the code in a try/catch block, nothing gets caught. I have also checked all thrown exceptions in Debug -> Exceptions, but nothing pops up. I'll try some of the other suggestions in the answers below and will report back.
Does anyone know how to resolve this problem? I found a post about something similar, but it was the opposite problem. I'll try tweaking the desktop settings to see if it's related to that, but I am dubious.
EDIT -- as a sanity check, I wrote a test WPF application that displays an OpenFileDialog directly via the main window as well as another Window that can be displayed by the main window. It totally works fine under Windows XP. So now I'm really confused. I have verified that I'm not doing something stupid like trying to display the dialog from a worker thread. The OpenFileDialog displays briefly, then disappears along with the application.
EDIT -- I'm going to try to reproduce this problem on another XP computer. For now, I'll try Windows XP mode and we'll see what happens.
I got a similar error when a DLL crashes when I open a OpenFileDialog. It turned out that OpenFileDialog changed the working directory so my dll tried to write to a relative file that did not exist.
Do you see any "First Chance" exceptions in the Output? Any entries in the event log? Does the default path you're using exist on the XP machine?
Try adding a handler to the App Domain's UnhandledException
Does the same happen when you use a brand new, stock FileOpenDialog without any tweaks? What about from a brand new app which does nothing but show a file open dialog?
See Galet's post
I cannot tell you what exactly the problem is, but here's what you could do to get a clue what's really happening. I assume you're using VS2008 or 2005.
1.Switch to release mode
2.Go to Debug\Exceptions, and mark all "Thrown" exceptions, like illustrated here: http://vvcap.net/db/JbWS_tzy2IpBoI7R7amm.htp
3.Run executable in debugger, ignore the warnings from VS that there's no debug info
It does seem that there's a win32 exception thrown some time during execution, but this way or another, you will get one or more messages from debugger explaining what kind of exception happened and where. In most cases those messages make it pretty clear what exactly went wrong
EDIT: One thing I forgot to mention is that unmanaged debugging must also be turned on, such like here (when you start program directly from IDE) or here (when you attach to running process)
link|edit|flag edited Apr 12 '09 at 22:32
answered Apr 10 '09 at 19:01
galets
1,2201924

Windows Form Design-Time Error

I am using Visual Studio 2008 and I get the following error message when trying to open one of my Forms:
Could not find endpoint element with
name 'WSHttpBinding_ICommon' and
contract 'CommonWCF.ICommon' in the
ServiceModel client configuration
section. This might be because no
configuration file was found for your
application, or because no endpoint
element matching this name could be
found in the client element.
And the following stack trace
at
System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object
component, Object value) at
System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager
manager, CodeAssignStatement
statement,
CodePropertyReferenceExpression
propertyReferenceEx, Boolean
reportError) at
System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager
manager, CodeAssignStatement
statement) at
System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager
manager, CodeStatement statement)
And yet I do have the element suggested in my App.Config and everything works at run-time. However, whenever I try to open the form I get this message, which is not too bad because I can ignore it, but when I do many of the controls (those with anchors on the right side and/or the bottom) are shifted and my grids automatically regain all the columns from their datasource which (the columns) I had previously removed.
Any suggestions/workarounds? Is this a Visual Studio 2008 bug?
There's another approach to debug the devenv process (visual studio) in design time, like stated
here
This helped when opening form in design mode throws exception (i.e. shows error to user).
Here is a summary from that article:
Open a new Visual Studio instance.
Open any source file. This is required so that Visual Studio lets you attach to a process.
Attach the new Visual Studio instance to the first one. The Visual Studio process is called devenv.exe. You only need to attach to managed code.
Set Visual Studio to break on Common Language Runtime exceptions - Thrown and User-handled.
Close the problematic form, and reopen it.
This should result in an exception caught inside your code in the second instance of Visual Studio!
Where are you using the endpoint? Do you really need it there or can you only call on it during runtime? You can use the Component.DesignMode property to determine whether you are in design mode so you can prevent the calls to the endpoint being made. To fully debug your design time experience follow the instructions in this article.
I use
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
return;
}
To check for Design Mode in both the Constructor if it does anything other than InitializeComponent() and the Load Method if it has one.
I had a similar error once in a form that tried to make a database call during constructor initialization.
Unfortunately, Component.DesignMode doesn't get set until after the constructor finishes!

What is causing ObjectDisposedException from SerialPort while debugging .NET winform?

Vista SP1
Visual Studio 2008 SP1
.NET 3.5 SP1
C#
I have a winforms app I'm playing with that uses a SerialPort object as a private variable. When the application is compiled and executed, it works great. It also works running in debug mode wihtout any breakpoints. 90% of the time when I stop at a breakpoint and try to step through code I get an 'unhandled exception ocurred' dialog with these details:
System.ObjectDisposedException was unhandled
Message="Safe handle has been closed"
Source="mscorlib"
ObjectName=""
StackTrace:
at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
at System.Threading.EventWaitHandle.Set()
at System.IO.Ports.SerialStream.AsyncFSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
The frustrating thing is, I do not have to be stepping over serial-related code! I just have to have done something with the port. So I might read a string, manipulate the string, add two numbers together, whatever, and then BANG.
Again, this works just fine when NOT debugging, or when debugging wihtout any breakpoints. There seems to be something about stopping at a breakpoint that makes the CLR dispose the SerialStream on a different thread.
There is a lot of chatter online about problems with renoving USB devices causing this. But I'm using the build-in motherboard port on COM1.
I don't think I had this issue in .NET 2.0 so I may have to go back to that...
I need to simplify the application quite a bit before I can post code - but has anyone seen behavior like this in the debugger before?
Thanks so much!
I had the same problem just this morning. Surprisingly, it simply has gone away when I DISABLED the following options in VS2008 Tools->Options->Debugging->General:
"Enable the exception assistant"
"Enable .NET Framework source stepping"
"Step over properties and operators"
"Enable property evaluation and other implicit function calls"
I have no idea why, but it worked for me.
Perhaps your port is getting closed by the OS as it does not get a response from your application (it is stopped at a breakpoint).
Well I'm not so sure this is an answer, but there was definately something about that project. It was originally written in 2.0 and converted to 3.5 by VS2008. I created a new project in C#-Express 2008 adding the original classes one-by-one and it works like a charm now! No idea what is different.
I have this too. This must be some kind of bug with the debugger. The above advice worked: Disable the "Enable property evaluation and other implicit function calls."
I have a class with properties that do serial I/O. I thought that perhaps the debugger was helpfully trying to display the property value when I hovered the mouse over it, thus doing the IO from the debugger thread. But that doesn't seem to be the case. I'm really unsure what the cause is.
I had the same problem and did the following:
serialPortLock = Monitor.TryEnter(serialPort, 3000);
Thread.Sleep(5);
serialPort.Write(msg, 0, msg.Length);
and the same for my Read().
Looks like it's a good workaround for me!

Resources