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.
Related
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.
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.
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.
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.
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