Unexpected exit code from a .NET console application - c#

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.

Related

C# COM application crash debugging

The C# console application running .NET 4.5.2 (app1) opens a COM application (app2) and does some work with that app2's API. So far all of the work is successful, but sometimes when app1 attempts to close app2, app2 hangs permanently.
If the process for app2 is ended with task manager then app1 reports access denied. Does that occur because the terminated process is no longer available or does it occur because it was blocking a thread in app1 and it was unable to report the error until the thread was allowed to continue?
The code used to terminate app2 is
private static void CloseSW(SldWorks swApp, Process sw_proces)
{
// Close with API call
if (Task.Run(() => { swApp.CloseAllDocuments(true); swApp.ExitApp(); }).Wait(TimeSpan.FromSeconds(20)))
return;
// Kill process if API call failed
if (Task.Run(() => { SWHelper.CloseSW(sw_proces); }).Wait(TimeSpan.FromSeconds(20)))
return;
// Unable to close SolidWorks, ignore error and continue
// This will eventually cause SolidWorks to crash and the crash handler will take over
}
This code should never take much more than 40 seconds to complete, but maybe the COM interop is causing some unexpected behaviour?
I am unable to reproduce this error on a development machine. What it the best way to trace the exact point of failure? It is possible that the failure is not in CloseSW but some point before this. Is there a better way to trace the error than to write each line to a log file?
It is also worth noting that this code works for 60 - 150 runs before it has any errors and both applications are closed between each run.
I have control of the remote environment so remote debugging is an option, but I've never set that up before.
Typically with COM interops causing issues is that IIS is having issues with the object using the current ISAPI.dll. Please verify that your permissions are configured within your assembly to work with your current version of IIS>
A few questions to help assist would be, which framework version are you using, which version of IIS and what is your Application Pool using for a framework.
HTH

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.

Windows Phone 8 Application fails with the 'ExecutionEngineException'

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.

Why does my c# Windows service stop running without any messages being written to the application event log?

I am fairly new to Windows services. I created an installer for my c# Windows service and the installation on the server (Windows Server 2003) appears to have worked. When it's started, it writes Service started successfully to the log. When it's stopped, it writes Service stopped successfully. However, sometimes the service stops running without writing anything to the log, so I start it back up manually. When I look at the log afterward, it says Service started successfully as expected. It's weird seeing that in the log twice in a row being that it's obviously missing an entry where the service had somehow stopped running.
What could be the potential causes for this? I have the service set up as automatic and installed it to run for all users. I was under the impression that this means the service starts automatically whenever the machine boots up. How can I find out why it stopped? Do services that crash automatically write to the event log or do I have to handle exceptions in such a way that they log their own reason for the crash?
Edit: Some additional info:
I have it set up to log on as Local System Account
Under Recovery options, I have it set up to restart on first failure. I don't have anything for second or subsequent failures.
Update: An answerer recommended a global exception handler. While I won't implement this as a permanent fix, it will at least help me figure out where the problem is occurring. I actually tested this with my installed service and it works. I found out that unhandled exceptions actually do crash the service without writing anything to the log at all. I thought it'd at least report some application error, but it doesn't.
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//other code here
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.WriteIt(e.ExceptionObject as Exception);
}
It's always best to handle the exceptions. At least use a global exception handler and write it to a logfile
It sounds like your service is failing unexpectedly without doing any form of exception-handling and/or logging. Windows services do not automatically write exceptions to the Event Log - it's up to you to handle exceptions and (if they're fatal) write them out somewhere so that you can diagnose the problem.
At the very least, I'd recommend a logfile somewhere (perhaps in the service executable folder, or preferably somewhere else that's easy to get to and won't run afoul of permissioning issues) and a standard logging method that all your exception-handlers call to write their messages to.
If a service quits unexpectedly because of some exception, I am not sure it would end up in the Event Log automatically.
I would highly recommend a logging suite like log4net for more thorough logging. You'll be able to provide a multitude of logging 'levels' (debug traces to see if you reached some code, info traces for important events, error traces to log exceptions).
You can look here for an example of a EventLogAppender. However, I would suggest starting with getting a FileAppender, one of the easiest logs to create, working first and then add a second appender for the Event Log.

Handle exception on service startup

I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.
The sample below accomplishes three things.
Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
Calling Stop results in a "Service successfully stopped" message in the Application log.
throwing the exception results in a useful log entry in the Application log.
protected override void OnStart(string[] args) {
try {
// Start your service
}catch (Exception ex) {
// Log exception
this.ExitCode = 13816;
this.Stop();
throw;
}
}
if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.
ref [devnewsgroups] (http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)
(news group gone)
Move all of your startup logic to a separate method, and Throw exceptions (or call OnStop) from that seperate method.
OnStart has some oddities when starting up. I have found that if OnStart() has no more than one line in it, then I dont get the "The service started and then stopped.Some services stop automatically if they have no work to do" message, and thrown exceptions will terminate the process and log to the app event log.
Also with the seperate startup method, you can use a technique like this to debug it without attaching. http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx

Categories