Handle exception on service startup - c#

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

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.

Auto restart windows service

I am trying to a Window Service in C#, which should be running always. If there is a crash or shutdown, then it should automatically restart. I considered using Service controller class, but the problem is how to handle if both Service Controller & Service go down at same time.
Is there a watchdog functionality in Windows with which I can register and it takes care of the service start up?
You could consider using recovery options of service. It can be set through properties of the service when running services.msc.
Please look here and here for more information.
Adding to the above recommended pattern, probably it's a good idea to
Catch the unhandled exception by subscribing to the appdomain.unhandledexception event.
And unload the application domain so that the windows service manager will
initiate the recovery procedure.
AppDoamin.currentAppDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Environment.Exit(-1);
}
One recommended pattern here is to set the service start up options to 'Auto' and also, ensure the core functionality of your service is wrapped in a try/catch block.
try
{
// core code here.
}
catch (Exception ex)
{
// log it for debugging and swallow so that service doesn't crash.
}
this ensures that your service is always running. the code will not crash it, and when the machine reboots etc., the service is auto started.

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.

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.

Categories