Windows Phone 8 Application fails with the 'ExecutionEngineException' - c#

In some cases my Windows Phone application fails with the ExecutionEngineException.
There are no real steps to reproduce the fail, so I'm not quite sure where to dig in.
The documentation states that this exception is deprecated and no more thrown in the runtime.
Mostly this exception occurs during the navigation between views (At different places in the code). Sometimes I'm getting this exception while trying to get the response. Particular code below:
void ResponseCallback(IAsyncResult ar)
{
var request = ar.AsyncState as HttpWebRequest;
try
{
if (request == null) return;
var response = request.EndGetResponse(ar); // at this point I'm getting the exception.
SetLicenseResponse(response.GetResponseStream());
}
catch (WebException e)
{
Console.LogError("ResponseCallback exception:" + e.InnerException);
}
}
The external libraries used in the application are:
Microsoft.Web.Media.SmoothStreaming
Microsoft.Phone.Controls.Toolkit
As well the application consumes two external web services.
The service reference generated is wrapped in async-await service consumers with the usage of the TaskCompletionSource classes.
As well there are several quite big ListBoxes that are using the VirtualizingStackPanel's as Items Panels.
According to the information I've found in the internet the exception may be caused if garbage collection is invoked from the parallel threads, however I'm not invoking the GarbageCollector in the code explicitly.
Please advice where to start.
Thanks in advance.
Note: The application fails with the particular exception mostly while debugging on the device. I'm not using the emulator for the debugging purposes. I haven't noticed that exception in logs while running the application in normal mode, however there is a possibility that the exception was not handled properly to appear in logs.

Related

windows update is causing my custom service to hang

I am using visual studio professional 2015, c# .net framework 4.
I have created a service for windows that sends and receives data on the serial port. It is intended to start when the computer starts and shutdown when the computer is shutdown. It should not hang or stop otherwise.
I have been running tests and find that when windows does an update it causes my service to hang. I have no idea how to debug this hang.
I would appreciate any ideas on how to start tracking down this bug.
thanks.
Here's something that might help.
When I write a service, I typically add an event handler to this AppDomain event called UnhandledException.
It's sort of a catch-all exception handler and has come in handy on a number of occassions and helps you improve your error handling, in general.
// Add this code to the Service Start method or the constructor
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Then add this method to your service class, it will be invoked when
// your code encounters an exception that is not trapped by a try/catch/finally
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
Trace.TraceError("Unhandled Exception occurred in service: {0}", ex);
}
Feel free to replace the Trace logging with your own logging framework if necessary.
Hope this helps.

Unexpected exit code from a .NET console application

I have written a console application and a companion class library to export some data from a cloud service. The application is called by SQL Server Integration Services which relies on the exit code returned by the application to determine if it worked correctly or not.
Intermittently the application returns an exit code of -532462766 (0xE0434352) which is the generic error code for a .NET unhandled exception. I'm totally flummoxed as to why this is happening.
The log files generated by the applications do not show any issues and they look like everything has completed successfully.
There are no entries in the Application Event Viewer logs.
The application even has an unhandled exception handler:
AppDomain.CurrentDomain.UnhandledException += UnhandledErrorHandler;
...
private void UnhandledErrorHandler(object sender, UnhandledExceptionEventArgs e) {
logWriter.Write(e.ExceptionObject.ToString(), logLevel.Fatal);
logWriter.Write("Exiting now...", logLevel.Fatal);
Dispose();
}
I've even written a batch file to execute the application and log the exit code before passing it along to SSIS. The exit codes that SSIS are receiving are the ones that seem to be returned by the application. But I cannot see an unhandled exception happening anywhere.
The console application returns the exit code by defining Main() like so:
class Program {
static int Main(string[] args) {
...
return (Success) ? 0 : 1;
}
Because it is intermittent (and the data extraction can take a couple of hours) I can't just run it in Visual Studio and debug it. I have a suspicion it might be related to the fact that the application does run for such a long time but I can't seem to confirm that.
Is there anything else that can cause a .NET application to return that exit code? Am I missing something in my troubleshooting?
quick check: wrap your entire code inside a try catch block and save the exception in a log file.
static int Main(string[] args)
{
try
{
//your existing code....
}
catch(Exception Ex)
{
//write your log results here.
}
}
Check if you are using multiple app domains. I encountered this same issue when an exception X was thrown in AppDomain B and could not cross to AppDomain A because it was not serializable. See also best practices for exceptions (search for 'across app domains'):
When you create user-defined exceptions, you must ensure that the
metadata for the exceptions is available to code that is executing
remotely, including when exceptions occur across app domains. For
example, suppose App Domain A creates App Domain B, which executes
code that throws an exception. For App Domain A to properly catch and
handle the exception, it must be able to find the assembly that
contains the exception thrown by App Domain B. If App Domain B throws
an exception that is contained in an assembly under its application
base, but not under App Domain A's application base, App Domain A will
not be able to find the exception, and the common language runtime
will throw a FileNotFoundException exception. To avoid this situation,
you can deploy the assembly that contains the exception information in
two ways:
Put the assembly into a common application base shared by
both app domains.
or
If the domains do not share a common application base, sign the assembly that contains the exception information with a strong name
and deploy the assembly into the global assembly cache.

IIS: Unexpected behavior in case of unhandled exception in Application_Start

I'm using Windows 7, IIS 7.5.7600.16385 and currently .NET 4.6.1 is installed and we have a MVC application.
Some days ago we had some strange behavior at our application. Unfortunately a service which is called inside Application_Start was not available and an unhandled exception was thrown inside. My expected behavior was that the Application_Start() is called again with the next request or the the next request is starting directly with Application_BeginRequest() like mentioned in What happens if an unhandled exception is thrown in Application_Start?.
Unfortunately I get the following result:
In case of exception inside Application_Start() I get an error 500 at the first request. That's ok.
After this all other requests are returning the exception which is thrown at the first request. I verified it by throwing an exception with timestamp inside at my local environment. Each response contains the exception with the timestamp from first request and the HTTP answer is still 500. It has no dependency which url is called. At our code no breakpoint is hit but the IIS log show the requests. It seems that the answer is cached somewhere.
Personally I like the behavior because the application doesn't respond to the requests with undefined initialization status.
And yes I know that calling other service resources inside Application_Start() is not the best idea and we will probably remove it next time :)
My Questions:
Is it possible to configure the behavior in case of an exception is thrown at Application_Start()?
Maybe somebody know when this behavior was changed or does it exists already a long time?
Well I analyzed this scenario and search through many sites, but coould not find any info about it. However, I managed to observe so behavior:
When unhandled error is thrown inside Application_Start then IIS returns error page and web app starts to shut down.
During the shutdown (in my case that was 10 sec.) any new request are handled by IIS and the response is the same as in the first request. If you think about it its logical, because IIS knows that website is shutting down so its obvious that last error cause it.
After some time application raises Application_End event to let know that shutting down is complete. After that event the next request to the website will raise Application_Start again and new response will be generated.
I don't think you can alter this behavior, because application just need some time to restart.
Today I had some time to check the behavior again. We introduced Serilog some releases ago and it seems that the configuration has an effect to the restarting behavior.
protected void Application_Start()
{
SerilogManager.Configure(); //own class
using (LogContext.PushProperty(SerilogManager.PROPERTY_NAME_ComponentName, "xxx")){}
throw new Exception(DateTime.Now.ToString("hh:mm:ss"));
}
If I remove the PushProperty line from Application_Start then the restart will work without any problem. With this line no Application_End will be called.
Now I can reproduce it on private und business computer. Not sure why my demo application didn't call Application_end on my business machine last time.

Application Insights: How to track crashes in Desktop (WPF) applications?

I'm using Application Insights for a WPF Application. Tracking of PageViews and custom events is working.
Now I would like to track crashes. My idea was to:
private void AppDispatcherUnhandledException(object sender,
DispatcherUnhandledExceptionEventArgs e)
{
telemetryClient.TrackException(e.Exception);
telemetryClient.Flush();
}
The code is called when a unhandled exception occurs but it is not shown as "Crash" in the Application Insights portal. I have read somewhere that TrackException does not count as "Crash" when the application does not really crash.
Desktop (e.g. WPF) applications must use the low level API of Application Insights. I have not found a way to tell Application Insights that the WPF Application is crashing.
How could I do that?
For WPF applications, there is no inherent support for capturing crashes. Your statement "The code is called when a unhandled exception occurs but it is not shown as "Crash" in the Application Insights portal. I have read somewhere that TrackException does not count as "Crash" when the application does not really crash." - is true.
Here is the documentation describing it.
If you still want to treat the exceptions that you are handling to be treated as crashes, the one way that you can do that is by treating the tracked exception as unhandled.
Here is how -
var exceptionTelemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(new Exception());
exceptionTelemetry.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.Unhandled;
telemetryClient.TrackException(exceptionTelemetry);

Windows service performs differently after reboot

I may have a problem in understating the behaviour of windows services or the life itself.
THE PROBLEM:
The service stopped unexpedetly and no recovery actions fired despite being set.
The service stopped after ServiceHelper.ChangeStartMode method call
try
{
normalnekurwalogowanie(Constants.Values.service_name);
ServiceController svc = new ServiceController(Constants.Values.service_name);
if (svc != null)
{
ServiceHelper.ChangeStartMode(svc, (automatic ? ServiceStartMode.Automatic : ServiceStartMode.Manual));
svc.Close();
}
else
normalnekurwalogowanie("null");
}
catch (Exception ex)
{
//Logger.Instance.Error("Error message: {0}\nError Stack Trace: {1}", new object[] { ex.Message, ex.StackTrace });
normalnekurwalogowanie(ex.ToString());
}
In my log file there was an error Open Service Manager Error:Unable to open Service Manager
Now, few interesting facts:
- As you can see the exception was caught and printed to the file yet the service stopped
- The error occured only after reboot; it doesn't occur after service installation before system reboot
THE SOLUTION:
After I removed reference to external Logger class (not written by me, I don't have the code) the problem disappeared. I don't know why.
THE QUESTIONS:
How can caught exception still crash the service (and in a way recovery actions are not performed)?
How can code perform differently after reboot? It goes thru exactly same sequence.
Even if the external class may have impact on my code it wasn't called anywhere before the line that threw the exception.BTW the externall class used in winforms app works fine, in service before reboot works fine.
I will try to acquire external class code and update the question.
How can caught exception still crash the service (and in a way recovery actions are not performed)?
The original exception may not crash the service, but if you have a second exception in your first exception handler, the service will crash. I'd check if Logger.Instance.Error() is throwing an exception by putting a try/catch around it.
How can code perform differently after reboot? It goes thru exactly same sequence.
While it might be the same sequence in your code, we don't know what residual state was left over on disk before the last crash. This might be the reason for the difference.

Categories