Unhandled Exception in Winforms Application - winforms

I have a simple WinForms app that is used to enter test cases. Ever since I upgraded this application to .NET 4.0 and added a new tab page to the tab page control for validating XML against XSD schema the application has been randomly crashing. I've been unable to reproduce the exception.
The error my QA guy receives is the generic Windows message:
TestCaseViewer has encountered a problem and needs to close. We are sorry for the inconvenience.
To try to get to the real error I've added the following code to the beginning of the Main method of program:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_ThreadException;
The event handlers look like this:
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
MessageBox.Show(e.Exception.ToString(), #"Thread Exception",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
Application.Exit();
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
var ex = (Exception)e.ExceptionObject;
MessageBox.Show(ex.ToString(), #"Unhandled Exception",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
Application.Exit();
}
}
Unfortunately this hasn't helped and whatever is thowing the error continues to do so in a way that generates the unhandled error that is bubbling up to the OS.
Can anyone give me any other ideas about trapping this exception?

Try adding the following to your app.config
<runtime>
<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>

If you're using Visual Studio, you can set it to break on all unhandled exceptions and even any time that an exception is thrown, regardless of whether or not it is handled by your code.
To do this, select "Exceptions" from the "Debug" menu. You'll get a dialog box that looks like this:
If you really want to get serious, try checking all of the boxes. Then, find out from your QA guy what exactly is being done to trigger the exception, and reproduce those actions exactly while running under the debugger within the development environment. Whenever the exception is thrown, Visual Studio will break and you'll see the offending line of code along with a complete stack trace.

Related

How to validate XML file against XSD schema and list all validation errors

I am validating xml against xsd, when first validation error is encountered its throwing first exception, But, through this approach, we cannot get information about all validation errors in the XML file in a single run. If an XML file has multiple validation errors, then in first run, the exception will be thrown as soon as the first error will be encountered and we do not get to know about remaining errors. To know about the subsequent errors, we need to fix the previous error and validate the file again and again till no exception is thrown.
onException( SchemaValidationException.class )
.handled(true)
.to("file:invalid-data")
from("file:in-data?noop=true")
.to("validator:file:my.xsd")
.to("file:out-data");
Which Apache Camel version are you using? In 2.20, the validation code do handle all the errors after validating:
try {
LOG.trace("Validating {}", source);
validator.validate(source, result);
handler.handleErrors(exchange, schema, result);
} catch (SAXParseException e) {
throw new SchemaValidationException(exchange, schema, Collections.singletonList(e), Collections.<SAXParseException>emptyList(), Collections.<SAXParseException>emptyList());
}
The validation is performed by javax.xml.validation.Validator class, though. Please see this question that has a similar discussion. The docs stated that:
Errors found during the validation is sent to the specified ErrorHandler.
If a document is valid, or if a document contains some errors but none of them were fatal and the ErrorHandler didn't throw any exception, then the method returns normally.
Maybe the errors you are facing are fatal? If it's the case, I think that's out of Camel's component control. :(

How to use ReactiveUI with WinForms

I have decided to learn ReactiveUI after seeing what can be done with it, but my enthusiasm has been broken at the first attempt to run a simple project. I have recreated the example from this article, using reactiveui-winforms.Net40 version 6.5.0 from NuGet. Everything compiles ok, but i get an exception during runtime at the following line
var OKCmdObs = this.WhenAny(vm => vm.EnteredText,
s => !string.IsNullOrWhiteSpace(s.Value));
System.InvalidOperationException occurred
HResult=-2146233079
Message=The current thread has no Dispatcher associated with it.
Source=System.Reactive.Windows.Threading
StackTrace:
at System.Reactive.Concurrency.DispatcherScheduler.get_Current()
at ReactiveUI.PlatformRegistrations.<>c.<Register>b__0_7() in C:\workspace\git-perso\ReactiveUI\ReactiveUI\Platform\Registrations.cs:line 75
InnerException:
Does anyone have any idea of what's happening ?
The mentioned article does not have the compiled project available for download, and i didn't find any complete "Hello-World" project for reactiveui-winforms.
My test project can be downloaded here.
In Visual Studio, if i Continue(F5), another exception occures :
System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ReactiveUI
StackTrace:
at ReactiveUI.IROObservableForProperty.<>c__DisplayClass1_0.<GetNotificationForProperty>b__6(IReactivePropertyChangedEventArgs`1 x) in C:\workspace\git-perso\ReactiveUI\ReactiveUI\IROObservableForProperty.cs:line 44
InnerException:
If i continue to hit F5 i get :
System.Exception was unhandled by user code
HResult=-2146233088
Message=An OnError occurred on an object (usually ObservableAsPropertyHelper) that would break a binding or command. To prevent this, Subscribe to the ThrownExceptions property of your objects
Source=ReactiveUI
This exception is caused because RxUI always tries to initialize for WPF, even though (because you're also using the winforms package) it'll override this setting with a Winforms-based scheduler right after.
It should be harmless though, as it's catched and ignored. You're probably hitting it within VS ?

RESTEasy - Stacktrace in logs when throwing WebApplicationException

I am using Resteasy 2.3.3, bundled with JBoss-AS-7.1.3. I'm trying to
throw a new WebAppliationException, and the output (to the client) seems
fine, but I'm left with an unwanted stack trace in my log. I have a few
other Exceptions mapped, and I was wondering if the mapping was somehow
causing an issue ­ trying to wrap this Exception.
Simple example:
public class SimpleService {
#GET
#Path("stuff")
public String getStuff(final #QueryParam("param1") String param1,
#QueryParam("param2") String param2) throws ActionException {
if (param1==null && param2==null) {
throw new WebApplicationException();
}
I get the following exception:
[WARN] org.jboss.resteasy.core.SynchronousDispatcher#error - failed to execute: javax.ws.rs.WebApplicationException
Any ideas what this error might mean? How I could get rid of the messages?
I stumbled across another class in the javadoc - NoLogWebApplicationException, and it says:
WebApplicationExceptions are logged by RESTEasy. Use this exception
when you don't want your exception logged
https://docs.jboss.org/resteasy/docs/2.3.3.Final/javadocs/org/jboss/resteasy/spi/NoLogWebApplicationException.html

How to catch an exception of Interbase on Connect when gdb file doesn't exist on a given path

I have fib+ comps installed on my machine and
trying to catch Interbase exception on connecting but one exception I cannot catch
try {
DM->dBase->Connected=false;
DM->dBase->DBName=DBPATH;
DM->dBase->Connected=true;
} catch (Exception &e) {
ShowMessage("Exception "+ (AnsiString(e.Message)));
}
if i change the DBPATH to a non-existent gdb file it throws an exception like
Unsuccessful execution caused by a system error that precludes successful exection of subsequent statements. I/O error for file .Error while trying to open file
Is it possible to catch this exception????
I debugged my code but cursor didn't come till try catch exception block and before that my aforementioned exception comes on!!!
If yes how can i catch this kind of exception????
Could it be that the exception is not inherited from the base exception class Exception, if so have you tried adding a catch(...) as well?
I'm not sure I understand your post entirely, but is it possible that what you see is not, that your program isn't catching the exception. It is that the debugger presents it to you before it is being handled by your catch statement? If this is the case then you can tell the debugger to not present this exception type for you.
Does the exception arrive if you run the program outside the debugger?

How to detect broken WPF Data binding?

While trying to answer a question in the vicinity 'Unit Testing WPF Bindings' I had the following niggling question..
What's the best way to find if you have WPF Data Binding wiring setup incorrectly (or you just broke something that was wired up correctly) ?
Although the unit-testing approach seems to be like Joel's 'ripping off your arm to remove a splinter'.. I am looking around for easier less Overhead ways to detect this.
Everyone seems to have committed themselves to data binding in a big way with WPF.. and it does have its merits.
In .NET 3.5 it was introduced a new way to specifically output tracing information about specific data bindings.
This is done through the new System.Diagnostics.PresentationTraceSources.TraceLevel attached property that you can apply to any binding or data provider. Here is an example:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="Debug Binding Sample"
Height="300"
Width="300">
<StackPanel>
<TextBox Name="txtInput" />
<Label>
<Label.Content>
<Binding ElementName="txtInput"
Path="Text"
diag:PresentationTraceSources.TraceLevel="High" />
</Label.Content>
</Label>
</StackPanel>
</Window>
This will put trace information for just that particular binding in Visual Studio's Output Window, without any tracing configuration required.
Best I could find...
How can I debug WPF Bindings? by Beatriz Stollnitz
Since everyone can't always keep one eye on the Output Window looking for Binding errors, I loved Option#2. Which is add this to your App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Windows.Data" switchName="SourceSwitch" >
<listeners>
<add name="textListener" />
</listeners>
</source>
</sources>
<switches>
<add name="SourceSwitch" value="All" />
</switches>
<sharedListeners>
<add name="textListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="GraveOfBindErrors.txt" />
</sharedListeners>
<trace autoflush="true" indentsize="4"></trace>
</system.diagnostics>
</configuration>
Pair that up with a good regex scan script to extract out relevant info, that you can run occasionally on the GraveOfBindErrors.txt in your output folder
System.Windows.Data Error: 35 : BindingExpression path error: 'MyProperty' property not found on 'object' ''MyWindow' (Name='')'. BindingExpression:Path=MyProperty; DataItem='MyWindow' (Name=''); target element is 'TextBox' (Name='txtValue2'); target property is 'Text' (type 'String')
I use the solution presented here to turn binding errors into native Exceptions: http://www.jasonbock.net/jb/Default.aspx?blog=entry.0f221e047de740ee90722b248933a28d
However, a normal scenario in WPF bindings is to throw exceptions in case the user input cannot be converted to the target type (for instance, a TextBox bound to a integer field; the input of a non-numeric string results in a FormatException, the input of number that is too large results in an OverflowException). A similar case is when the Setter of the source property throws an exception.
The WPF way of handling this is via ValidatesOnExceptions=true and ValidationExceptionRule to signal the user the supplied input is not correct (using the exception message).
However, these exception are also send to the output window and thus 'caught' by the BindingListener, resulting in an error...clearly not the behaviour you'd want.
Therefore, I expanded the BindingListener class to NOT throw an Exception in these cases:
private static readonly IList<string> m_MessagesToIgnore =
new List<String>()
{
//Windows.Data.Error 7
//Binding transfer from target to source failed because of an exception
//Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule
//To cope with these kind of errors
"ConvertBack cannot convert value",
//Windows.Data.Error 8
//Binding transfer from target to source failed because of an exception
//Normal WPF Scenario, requires ValidatesOnExceptions / ExceptionValidationRule
//To cope with these kind of errors
"Cannot save value from target back to source"
};
Modified lines in public override void WriteLine(string message):
....
if (this.InformationPropertyCount == 0)
{
//Only treat message as an exception if it is not to be ignored
if (!m_MessagesToIgnore.Any(
x => this.Message.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)))
{
PresentationTraceSources.DataBindingSource.Listeners.Remove(this);
throw new BindingException(this.Message,
new BindingExceptionInformation(this.Callstack,
System.DateTime.Parse(this.DateTime),
this.LogicalOperationStack, int.Parse(this.ProcessId),
int.Parse(this.ThreadId), long.Parse(this.Timestamp)));
}
else
{
//Ignore message, reset values
this.IsFirstWrite = true;
this.DetermineInformationPropertyCount();
}
}
}
You can use the trigger debugging feature of WPF Inspector. Just download the tool from codeplex and attach it to your running app. It also shows binding errors on the bottom of the window.
Very useful tool!
Here's a useful technique for debugging/tracing triggers effectively. It allows you to log all trigger actions along with the element being acted upon:
http://www.wpfmentor.com/2009/01/how-to-debug-triggers-using-trigger.html
This was very helpful to us but I wanted to add to those who find this useful that there is a utility that Microsoft provides with the sdk to read this file.
Found here: http://msdn.microsoft.com/en-us/library/ms732023.aspx
To open a trace file
1.Start Service Trace Viewer by using a command window to navigate to your
WCF installation location (C:\Program
Files\Microsoft
SDKs\Windows\v6.0\Bin), and then type
SvcTraceViewer.exe. (although we found ours in \v7.0\Bin)
Note: The Service Trace Viewer tool
can associate with two file types:
.svclog and .stvproj. You can use two
parameters in command line to register
and unregister the file extensions.
/register: register the association of
file extensions ".svclog" and
".stvproj" with SvcTraceViewer.exe
/unregister: unregister the
association of file extensions
".svclog" and ".stvproj" with
SvcTraceViewer.exe
1.When Service Trace Viewer starts, click File and then point to Open.
Navigate to the location where your
trace files are stored.
2.Double-click the trace file that you want to open.
Note: Press SHIFT while clicking
multiple trace files to select and
open them simultaneously. Service
Trace Viewer merges the content of all
files and presents one view. For
example, you can open trace files of
both client and service. This is
useful when you have enabled message
logging and activity propagation in
configuration. In this way, you can
examine message exchange between
client and service. You can also drag
multiple files into the viewer, or use
the Project tab. See the Managing
Project section for more details.
3.To add additional trace files to the collection that is open, click File
and then point to Add. In the window
that opens, navigate to the location
of the trace files and double-click
the file you want to add.
Also, as for the filtering of the log file, we found these this link extremely helpful:
http://msdn.microsoft.com/en-us/library/ms751526.aspx
For anyone like me looking for a pure programmatic way of enabling all WPF Tracing at a given Trace Level, here is a piece of code that does it. For reference, it's based on this article: Trace sources in WPF.
It doesn't requires a change in the app.config file, and it does not require to change the registry either.
This is how I use it, in some startup place (App, etc.):
....
#if DEBUG
WpfUtilities.SetTracing();
#endif
....
And here is the utility code (by default it sends all Warning to the Default Trace Listener):
public static void SetTracing()
{
SetTracing(SourceLevels.Warning, null);
}
public static void SetTracing(SourceLevels levels, TraceListener listener)
{
if (listener == null)
{
listener = new DefaultTraceListener();
}
// enable WPF tracing
PresentationTraceSources.Refresh();
// enable all WPF Trace sources (change this if you only want DataBindingSource)
foreach (PropertyInfo pi in typeof(PresentationTraceSources).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
if (typeof(TraceSource).IsAssignableFrom(pi.PropertyType))
{
TraceSource ts = (TraceSource)pi.GetValue(null, null);
ts.Listeners.Add(listener);
ts.Switch.Level = levels;
}
}
}
My suggestion at 2021:
The Best way is to use Benoit Blanchon small library from Nuget
His original post at here: https://stackoverflow.com/a/19610384/6296708
His GitHub link and more info about how to use it + Nuget command: https://github.com/bblanchon/WpfBindingErrors
Its features (until now!):
throw exception on binding errors (+ line number)
If source Variable throw any exceptions, this library will catch it and show it.
Unit Test supports too!
Happy Coding!

Resources