Allow UnhandledException event handler to run when debugging using Visual Studio 2013 Ultimate - vb.net

I have a WinForms application that uses Application.UnhandledException to display a dialog to prompt user to report the error. When the application is published and run on its own, it works fine (apart from the obvious problem that there is an unhandled exception floating around).
To test changes to it, I've been trying just throwing an exception on clicking a button. Unfortunately, the debugger gets in the way. It will break at the exception (which is not a problem in other cases because I want to know something is wrong) and not let me continue into the UnhandledException handler, instead telling me that the exception is unhandled every time I click the continue button. I've tried disabling breaking on any exception, specific types of exception and the Just My Code option in the Options screens to no avail.
Is there any way of disabling this behaviour?
Repro code below, as requested. It's from a bog-standard, common-or-garden WinForms app with a single button (ThrowButton) on the startup form. Application Framework is enabled by default on creating the project.
Form1.vb
Public Class Form1
Private Sub ThrowButton_Click(sender As Object, e As EventArgs) Handles ThrowButton.Click
Throw New Exception
End Sub
End Class
ApplicationEvents.vb
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
MsgBox("Application event")
End Sub
End Class
End Namespace
I've also put a copy of the solution up on Drive, in case that would be helpful. I scanned it before uploading it, but obviously can't vouch for what happens to it after that.
https://drive.google.com/file/d/0By6VJrYK_X0-QklFWWYtSDBPblU/view?usp=sharing

This answer was given for C# code, before OP prepared VB.NET code for download. May it still be useful for someone. If you disagree, flag it as not-an-answer.
The C# behavior follows the MSDN steps for exception dispatching, which says in step 3:
... but the process is being debugged, the system notifies the debugger a second time.
Considering code like
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
throw new Exception("Help! I am unhandled!");
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Caught unhandled exception.");
Console.WriteLine(e.IsTerminating ? "Terminating" : "Not terminating");
}
I'd say the behavior of Visual Studio is expected.
The unhandled exception handler is executed (which you can verify by looking at the console output)
The process is going to terminate, because you can't set the exception as handled in the handler
Before the process terminates, the debugger jumps in
The same happens not only in Visual Studio but in WinDbg (running the same executable):
0:000> .exr -1
ExceptionAddress: 750bc42d (KERNELBASE!RaiseException+0x00000058)
ExceptionCode: e0434352 (CLR exception)
ExceptionFlags: 00000001
NumberParameters: 5
Parameter[0]: 80131500
Parameter[1]: 00000000
Parameter[2]: 00000000
Parameter[3]: 00000000
Parameter[4]: 713e0000
0:000> !pe
Exception object: 02573148
Exception type: System.Exception
Message: Help! I am unhandled!
InnerException: <none>
StackTrace (generated):
SP IP Function
0038F0DC 001D04B4 UnhandledExceptionHandler!UnhandledExceptionHandler.Program.Main(System.String[])+0x6c
StackTraceString: <none>
HResult: 80131500
Where the exception flags tell us that this is a second chance exception.

Related

How it is possible to debugging Windows.UI.Xaml.Markup.XamlParseException

During the methode
InitializeComponent()
in the main class of a customized control occurs the error with the follow message:ยจ
Message "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Windows.UI.Xaml.Markup.XamlParseException: Der Text zu diesem Fehlercode wurde nicht gefunden.\r\n\r\nCannot create instance of type 'Uwp.UI.Control.OneNotePicker.OnenotePicker' [Line: 37 Position: 42]\r\n at Windows.UI.Xaml.Application.LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)\r\n at TestEnvironment.Uwp.MainPage.InitializeCom" string
This error is an unhandled exception and is shown with a debug break under App.g.i.cs
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
It seems, there is an error during parsing the Xaml file. My question is now, how I can find exactly the row of the Xaml file, where the error occurs.
Thanks for help
The issue might be caused by a spelling mistake of the resource name that you defined in the Page.Resources or App.Resources.Please check where you are setting the resources and make sure the spelling is correct.

ReflectionTypeLoadException in ASP.NET Core MVC application

I'm running into a problem running an ASP.NET Core 1.0 application targeting .NET Framework 4.6. The problem didn't occur until we tried to run the application on a server running Windows Server 2016. The app is hosted in IIS and I have the .NET Core 1.0 Windows Hosting Bundle installed on the server.
Upon loading the site a 500 error is returned and this is written to the Logs:
An unhandled exception has occurred: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. (fc7986d0)
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Researching this it appears to relate to a missing dll or mismatched version, and that I should look at the LoaderExceptions property to get more info, but I'm not sure how to do that in this instance. The log entry is created just from setting up the loggerFactory in the Configure() method of Startup.cs.
I tried adding an IExceptionFilter ActionFilter implementation and reading the LoaderExceptions property if the exception is of type ReflectionTypeLoadException, but it doesn't get hit when ran on the server.
Is there a way to drill down into the Exception to read the LoaderExceptions property (in a production environment, there is no error when running in Visual Studio so debugging didn't help), or else another way to troubleshoot the original error to determine what is wrong with the server setup?
Instead of using IExceptionFilter, I wrote my own Middleware for catching this sort of exception and was able to log each exception from the LoaderExceptions property and determine what my problem is. Here is what I added to log the LoaderExceptions:
public class ExceptionCatchMiddleware
{
private readonly RequestDelegate _delegate;
private readonly ILogger _logger;
public ExceptionCatchMiddleware(RequestDelegate requestDelegate, ILogger<ExceptionCatchMiddleware> logger)
{
_delegate = requestDelegate;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _delegate(context);
}
catch (ReflectionTypeLoadException e)
{
foreach (Exception ex in e.LoaderExceptions)
{
_logger.LogCritical(ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
}
And then I just needed to add the Middleware to the Configure() method in Startup.cs:
app.UseMiddleware<ExceptionCatchMiddleware>();
In my case it was a missing dll that wasn't included in the project but since it was in my dev machine's GAC it ran there just fine.

asp.net mvc exception in controller not beign handled at custom ErroHandler

I have a global ErrorHanlder (Derive from HandleErrorAttribute) that works fine and catches all errors that occur. But I have a situation in which, home controller can throw exception. I inspected and saw that error thrown from controller is not handled in my custom ErrorHandler and asp.net gives this:
Exception of type 'Exception' was thrown.
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Would you help me please ?
Code:
public HomeController()
{
_ServiceAsync = new ServiceAsyncProvider();
}
class ServiceAsyncProvider
{
public ServiceAsyncProvider()
{
throw new Exception();
}
}
While your code snippet is a little unclear on this point, it looks like your _ServiceAsync is being initialized in your controller's constructor. Exceptions thrown during controller construction are not handled by the HandleError filter.
See this related question for more information: Handling Exceptions that happen in a asp.net MVC Controller Constructor
You are throwing an exception in the constructor. These exceptions are not handled by the filter.

The type initializer for 'NHibernate.Cfg.Configuration' threw an exception

After upgrading from nhibernate 1.0.4.0 to nhibernate 3.3 im encountering the following error when I try to run "Configuration cfg = new Configuration();"
System.TypeInitializationException was caught
Message="The type initializer for 'NHibernate.Cfg.Configuration' threw an exception."
Source="NHibernate"
TypeName="NHibernate.Cfg.Configuration"
StackTrace:
at NHibernate.Cfg.Configuration..ctor()
at KEH.Web.Data.NHibernateUtil..cctor() in F:\Projects\KEH nHibernate\KEHWeb\Data\Data\NHibernateUtil.cs:line 24
InnerException: System.NotSupportedException
Message="The invoked member is not supported in a dynamic assembly."
Source="mscorlib"
StackTrace:
at System.Reflection.Emit.AssemblyBuilder.get_Location()
at log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly)
at log4net.Core.DefaultRepositorySelector.GetInfoForAssembly(Assembly assembly, String& repositoryName, Type& repositoryType)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType)
at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly)
at log4net.Core.LoggerManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Type type)
at lambda_method(ExecutionScope , Type )
at NHibernate.Log4NetLoggerFactory.LoggerFor(Type type)
at NHibernate.LoggerProvider.LoggerFor(Type type)
at NHibernate.Cfg.Configuration..cctor()
InnerException:
Any help would be greatly appreciated.
The NHibernateUtil class code is as follows :
public class NHibernateUtil
{
private static readonly Configuration cfg;
private static readonly ISessionFactory sessionFactory;
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static NHibernateUtil()
{
try
{
logger.Debug("Before Initializing NHibernate");
cfg = new Configuration();
cfg.AddAssembly("KEH.Web.Data");
sessionFactory = cfg.BuildSessionFactory();
logger.Debug("Initialized NHibernate");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static ISession OpenSession()
{
logger.Debug("Before Getting Connection");
return sessionFactory.OpenSession();
}
}
I had the same problem.
The actual reason was i used a library that used old version of log4net.
NHibernate tries to use it if find.
So i had to force it to use (or actually not use) other logger by adding such line:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
Not sure why it's not working, but I'd just replace
cfg.AddAssembly("KEH.Web.Data");
with
cfg.AddAssembly(typeof(Entity).Assembly);
where Entity is some class that exists in the assembly of your mapping files.
For the benefit of others who might find this question via Google:
For us, this error was a red-herring. Our app ran fine until we deployed a new component AND it would fail (in an unknown way) AND IIS would recycle the app pool. The problem was an HTML to JPG component we were using was erroring somehow and causing all of our w3wp.exe worker processes to consume maximum CPU. When the app pool was recycled via IIS, the entire site would go down and NHibernate would throw this error continuously until an iisreset. Before the recycle, the site would still be very responsive even with the CPU load.
While we still don't know how the component was failing or why it was cascading to problems with NHibernate initializing, the point is it was a red-herring. Be sure to watch for this error "suddenly" occurring shortly after a new deployment, and keep logs of your CPU utilization so it can help spot when trouble is brewing. Finally, if the downtime is happening near the same time every day, it's probably an automatic IIS app pool recycle, and that should be another clue that something is bugging out your application and surfacing during the recycle.
Ultimately, we disabled the HTML to JPG component until a workaround can be found and our up-time sprung back to 100%.
Hope this helps someone.

Is there a way to get error feedback on asynchronous WCF calls?

I have a WCF service which works 100% in the synchronous (blocking) mode and I now need to rework a call so that it uses the async pattern.
The service uses authentication and performs a chunked file transfer from client to server so I have reworked it to use the 'Begin' async prefix to kick off the call.
Now I'm testing for errors by deliberately mangling the user credentials which causes the call to timeout on each part of the file chunk it tries to transfer, which takes ages. The problem is that I don't get any error feedback and can't see how to get any if the async call fails. This leads to some very large files failing to upload at all, but the client being unaware of it as no exceptions are thrown.
I have the Debug->Exceptions->All CLR exceptions ticked to see if there are any exceptions being swallowed but still nothing.
So in summary, how do you get error feedback from async calls in WCF?
Thanks in advance,
Ryan
The server caches the exception for you and if you call the end operation completion method for your async call it will throw any exceptions that occured.
private void go_Click(object sender, EventArgs e)
{
client.BeginDoMyStuff(myValue, new AsyncCallback(OnEndDoMyStuff), null);
}
public void OnEndDoMyStuff(IAsyncResult asyncResult)
{
this.Invoke(new MethodInvoker(delegate() {
// This will throw if we have had an error
client.EndDoMyStuff(asyncResult);
}));
}