I use MAF and I have a problem with activating the addin. Let me explain my plan.
First I create a secondary AppDomain then I try to activate the addin:
MyAddIn = Token.Activate<AddInHostView>(domain);
My AddIn is very simple and referenced only one helper assembly. If this helper assembly is in the directory of the AddIn, all things work like a charm.
AddIns
MyDemoAddIn.dll
Helpers.dll
If I delete the Helpers.dll the whole application crash:
A first chance exception of type 'System.IO.FileNotFoundException' occurred in MyDemoAddIn.DLL
'PresentationHost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_de_b77a5c561934e089\mscorlib.resources.dll'
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in System.AddIn.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in System.AddIn.dll
I tested all things with exception handling. I can't catch the exception from the Host, AddInView or my created AppDomain :-(
Does anyone have an idea?
Your addin cannot run without Helpers.dll
Because it works across AppDomain boundaries, the addin needs it own set of DLLs to be loaded into its own AppDomain.
If you don't need cross AppDomain functionality, you can use Token.Activate<AddInHostView>(AppDomain.CurrentDomain) to load it if you have helpers.dll referenced in your host project.
The answer is easier than you think... The problem was a error in the Finalizer() Method from the AddInView.dll which is an interlayer of the MAF. Here is my solution.
Demo (Host)
try
{
MyAddIn = Token.Activate<AddInHostView>(domain);
}
catch (Exception ex)
{
try
{
AppDomain.Unload(domain);
domain = null;
}
catch (ThreadAbortException threadAbortException)
{
//ToDo: Logging
}
catch (CannotUnloadAppDomainException cannotUnloadAppDomainException)
{
//ToDo: Logging
}
catch (Exception exception)
{
//ToDo: Logging
}
}
AddInView
[AddInBase]
public class AddInView : UserControl
{
//Necessary constructor to handle the exception.
//Normal constructor is not called when an error occurs at startup!!!
static AddInView()
{
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
}
//Normal constructor
public AddInView()
{
//Do other things...
//e.g. Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
//To cleanup and stuff
}
}
Now, if an error occurs (Activate<>) the exception handler catches the error (FileNotFound Helpers.dll not found) and unload the whole AppDomain without crash the main AppDomain :-)
Related
In the application I"m working with, there is some communication with the remote service using WCF (basic http binding, no fancy stuff). Since the client is lightweigh, the details of the server are irrelevant, you may assume that there is just a method that always return true (like ping or something).
The proxy is generated using a Task option, the new client instance is created each time the operation is called. Something like this could be spinning inside the timer:
void Foo()
{
var client = new PingServiceClient();
try
{
bool result = client.PingAsync().GetAwaiter().GetResult();
}
catch
{
//log something
}
finally
{
client.Abort();
}
}
My question is, how should I correctly handle the cases when the network is down? Because the behavior is different. I either get an application crashing (I assume on a task finalizer, which is for some reason not handled neither in AppDomain.CurrentDomain.UnhandledException nor in TaskScheduler.UnobservedTaskException), or sometimes it just silently outputs tons of error messages, but not crashing anything. Messages like these:
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.ServiceModel.EndpointNotFoundException' in System.ServiceModel.Internals.dll
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
Exception thrown: 'System.AggregateException' in mscorlib.dll
I'm struggling to find a graceful way of handling these, so if anybody has some knowledge regarding this please share the approach.
Thanks in advance.
UPD:
I have tried to re-create the proxy with Begin/End pair and override the end method implementation in a partial class:
public partial class PingServiceClient : IPingServiceClient, PingService
{
public Task<bool> PingSync()
{
return Task.Factory.FromAsync(BeginPing(null, null), HandledEndPing);
}
private bool HandledEndPing(System.IAsyncResult result)
{
var res = false;
try
{
res = EndPing(result);
}
catch (Exception e)
{
;
}
return res;
}
}
Still the same barrage of messages in the output as before (the catch is working, though).
In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?
You can use Win32Exception and use its NativeErrorCode property to handle it appropriately.
// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155;
void OpenFile(string filePath)
{
Process process = new Process();
try
{
// Calls native application registered for the file type
// This may throw native exception
process.StartInfo.FileName = filePath;
process.StartInfo.Verb = "Open";
process.StartInfo.CreateNoWindow = true;
process.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||
e.NativeErrorCode == ERROR_ACCESS_DENIED ||
e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
{
MessageBox.Show(this, e.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
Catch without () will catch non-CLS compliant exceptions including native exceptions.
try
{
}
catch
{
}
See the following FxCop rule for more info
http://msdn.microsoft.com/en-gb/bb264489.aspx
The interop layer between C# and native code will convert the exception into a managed form, allowing it to be caught by your C# code. As of .NET 2.0, catch (Exception) should catch anything other than a nonrecoverable error.
Somewhere using a .NET Reflector I've seen the following code:
try {
...
} catch(Exception e) {
...
} catch {
...
}
Hmm, C# does not allow to throw an exception not deriving from the System.Exception class. And as far as I known any exception cautch by the interop marshaller is wrapped by the exception class that inherits the System.Exception.
So my question is whether it's possible to catch an exception that is not a System.Exception.
This depends on what type of native exception you are talking about. If you're referring to an SEH exception then the CLR will do one of two things.
In the case of a known SEH error code it will map it to the appropriate .Net exception (i.e. OutOfMemoryException)
In the case of an un-mappable (E_FAIL) or unknown code it will just throw an SEHException instance.
Both of these will be caught with a simple "catch (Exception)" block.
The other type of native exception which can cross the native/managed boundary are C++ exceptions. I'm not sure how they are mapped/handled. My guess is that since Windows implements C++ exceptions on top of SEH, they are just mapped the same way.
With .Net Framework 4.8 IF the exception is handled nicely within the native code then you can catch it with a standard try catch.
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
HOWEVER, if the native code is in a 3rd party dll you have no control over, you may find that the developers are inadvertently throwing unhandled exceptions. I have found NOTHING will catch these, except a global error handler.
private static void Main()
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
try
{
//call native code method
}
catch (Exception ex)
{
//unhandled exception from native code WILL NOT BE CAUGHT HERE
}
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
//do stuff
}
There is a reason for this. Unhandled native exceptions can indicate a corrupted state that you can't recover from (eg stack overflow or access violation). However, there are cases you still want to do stuff before terminating the process, like log the error that just tried to crash your windows service!!!
A bit of History
None of the following is required any more.
From .Net 2.0 - 3.5 you could use an empty catch:
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
catch
{
//do same stuff but without any exception detail
}
From .Net 4 they turned off native exceptions being abled to be caught by default and you needed to explicitly turn it back on by decorating your methods with attributes.
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
private static void Main()
{
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
}
also required was a change to the app.config file:
<configuration>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true" />
</runtime>
</configuration>
Almost, but not quite. You will catch the exception with
try
{
...
}
catch (Exception e)
{
...
}
but you will still have potential problems. According to MSDN, in order to insure exception destructors are called you would have to catch like:
try
{
...
}
catch
{
...
}
This is the only way to insure an exception destructor is called (though I'm not sure why). But that leaves you with the tradeoff of brute force versus a possible memory leak.
Incidentally, if you use the (Exception e) approach you should know the different types of exceptions you might come across. RuntimeWrappedException is what any managed non-exception type will be mapped to (for languages that can throw a string), and others will be mapped, such as OutOfMemoryException and AccessViolationException. COM Interop HRESULTS or exceptions other than E___FAIL will map to COMException, and finally at the end you have SEHException for E_FAIL or any other unmapped exception.
So what should you do? Best choice is don't throw exceptions from your unamanaged code! Hah. Really though if you have a choice, put up barriers and failing that make the choice of which is worse, a chance of a memory leak during exception handling, or not knowing what type your exception is.
A standard try catch should do the trick i believe.
I run into a similar problem with a System.data exception throwing a sqlClient exception which was uncaught, adding a try..catch into my code did the trick in the instance
If you use a
try
{
}
catch(Exception ex)
{
}
it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.
I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. So here is what I am doing:
try
{
//The code which I want to handle for exception
}
catch (Exception e)
{
ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
}
where ErrorStatus is my TextBlock.
However, the only line in my catch block is giving me an exception during the runtime. The exception is:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Am I doing something wrong syntactically? I am new to C# programming as well as Windows Phone programming.
Edit:
More details of the exception:
System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException:
You need to show your message from the UI thread: web calls always callback on a background worker thread. So, you need to call the Dispatcher to get this to run on the UI thread.
Also you can just use Exception.ToString() to show the message content as a string. This has the advantage of also showing any nested exceptions inside the one you're handling.
As a temporary measure try:
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
}
}
More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code.
This is the best way to print out your exception message so that you may know where the problem is:
try{}
catch(Exception ex)
{
await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}
I have simple application with single AppDomain which is periodicaly launched on a server. Sometimes unhandled exception occurs in the aplication and default abort/retry/ignore dialog pops up. I need to somehow prevent the edialog from showing and just output the exception on StrErr and close the application. So I enclosed all the code in main method with try-catch statement, but it didn't help at all - the exception dialog is still shown sometimes.
The Main() code looks like this:
try
{
RunApplication();
}
catch (Exception exc)
{
Console.Error.WriteLine(exc.ToString());
Console.Error.WriteLine(exc.StackTrace);
if (exc.InnerException != null)
{
Console.Error.WriteLine(exc.InnerException.ToString());
Console.Error.WriteLine(exc.InnerException.StackTrace);
}
Environment.Exit(666);
}
This try-catch clause shoud catch all unhandled exceptions and the exception dialog should never popup AFAIK. Am I missing something? Or is there any setting (registry etc) on the server which controls some special behaviour related to the exception dialog/application error code?
There's an unhandled exception event you can subscribe to in the application domain.
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
//some code here....
}
/// <summary>
/// Occurs when you have an unhandled exception
/// </summary>
public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//here's how you get the exception
Exception exception = (Exception)e.ExceptionObject;
//bail out in a tidy way and perform your logging
}
Have you considered the possibility that your catch clause may be throwing exceptions?
Do you spawn threads in your main app?
In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?
You can use Win32Exception and use its NativeErrorCode property to handle it appropriately.
// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155;
void OpenFile(string filePath)
{
Process process = new Process();
try
{
// Calls native application registered for the file type
// This may throw native exception
process.StartInfo.FileName = filePath;
process.StartInfo.Verb = "Open";
process.StartInfo.CreateNoWindow = true;
process.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||
e.NativeErrorCode == ERROR_ACCESS_DENIED ||
e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
{
MessageBox.Show(this, e.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
Catch without () will catch non-CLS compliant exceptions including native exceptions.
try
{
}
catch
{
}
See the following FxCop rule for more info
http://msdn.microsoft.com/en-gb/bb264489.aspx
The interop layer between C# and native code will convert the exception into a managed form, allowing it to be caught by your C# code. As of .NET 2.0, catch (Exception) should catch anything other than a nonrecoverable error.
Somewhere using a .NET Reflector I've seen the following code:
try {
...
} catch(Exception e) {
...
} catch {
...
}
Hmm, C# does not allow to throw an exception not deriving from the System.Exception class. And as far as I known any exception cautch by the interop marshaller is wrapped by the exception class that inherits the System.Exception.
So my question is whether it's possible to catch an exception that is not a System.Exception.
This depends on what type of native exception you are talking about. If you're referring to an SEH exception then the CLR will do one of two things.
In the case of a known SEH error code it will map it to the appropriate .Net exception (i.e. OutOfMemoryException)
In the case of an un-mappable (E_FAIL) or unknown code it will just throw an SEHException instance.
Both of these will be caught with a simple "catch (Exception)" block.
The other type of native exception which can cross the native/managed boundary are C++ exceptions. I'm not sure how they are mapped/handled. My guess is that since Windows implements C++ exceptions on top of SEH, they are just mapped the same way.
With .Net Framework 4.8 IF the exception is handled nicely within the native code then you can catch it with a standard try catch.
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
HOWEVER, if the native code is in a 3rd party dll you have no control over, you may find that the developers are inadvertently throwing unhandled exceptions. I have found NOTHING will catch these, except a global error handler.
private static void Main()
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
try
{
//call native code method
}
catch (Exception ex)
{
//unhandled exception from native code WILL NOT BE CAUGHT HERE
}
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
//do stuff
}
There is a reason for this. Unhandled native exceptions can indicate a corrupted state that you can't recover from (eg stack overflow or access violation). However, there are cases you still want to do stuff before terminating the process, like log the error that just tried to crash your windows service!!!
A bit of History
None of the following is required any more.
From .Net 2.0 - 3.5 you could use an empty catch:
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
catch
{
//do same stuff but without any exception detail
}
From .Net 4 they turned off native exceptions being abled to be caught by default and you needed to explicitly turn it back on by decorating your methods with attributes.
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
private static void Main()
{
try
{
//call native code method
}
catch (Exception ex)
{
//do stuff
}
}
also required was a change to the app.config file:
<configuration>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true" />
</runtime>
</configuration>
Almost, but not quite. You will catch the exception with
try
{
...
}
catch (Exception e)
{
...
}
but you will still have potential problems. According to MSDN, in order to insure exception destructors are called you would have to catch like:
try
{
...
}
catch
{
...
}
This is the only way to insure an exception destructor is called (though I'm not sure why). But that leaves you with the tradeoff of brute force versus a possible memory leak.
Incidentally, if you use the (Exception e) approach you should know the different types of exceptions you might come across. RuntimeWrappedException is what any managed non-exception type will be mapped to (for languages that can throw a string), and others will be mapped, such as OutOfMemoryException and AccessViolationException. COM Interop HRESULTS or exceptions other than E___FAIL will map to COMException, and finally at the end you have SEHException for E_FAIL or any other unmapped exception.
So what should you do? Best choice is don't throw exceptions from your unamanaged code! Hah. Really though if you have a choice, put up barriers and failing that make the choice of which is worse, a chance of a memory leak during exception handling, or not knowing what type your exception is.
A standard try catch should do the trick i believe.
I run into a similar problem with a System.data exception throwing a sqlClient exception which was uncaught, adding a try..catch into my code did the trick in the instance
If you use a
try
{
}
catch(Exception ex)
{
}
it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.