Service- how to catch exit code - c#

I would like to ask about Windows services.
My service code looks like following:
try
{
//...
}
catch
{
Environment.ExitCode = 1;
}
After I install my service I am using a scheduling system to run service at a specific time:
net start MyService
//or
sc start MyService
So my question is, how to get information if I had exception?
Is there any command to get this information? Now I am usually running my application, then after 10 mins. stopping service. I want to do intermediate scheduling task which will tell me if in the application error has occurred. I have tried all options of "sc"- but it gives only information about service.
Contraints:
I cannot log errors and exceptions into the event log or files
Prefer not to change my code
In the scheduling system I can use bat scripting (so this scipt is only place I can change something)

The standard way is to log errors and exceptions into the event log - either a specific one you create for your service, or simply using the service as a new source for the event log.
You can use WMI to then check the event log periodically for errors.

In the absence of being able to log to the event log, can you create your own "event log"? Using either a file or database table that the intermediate service polls periodically might serve your purpose.

Related

Detect is when a windows service has been deleted

Is there a way to detect when a windows service has been deleted? I've checked the event log but it doesn't pick up deleted actions only added.
I believe there may be a way using audit logs but I'm unsure how to do this?
Any help is much appreciated.
Thanks
While there is no trace of service deletion in Event or Audit logs, what you can do is create a small console app that detects if a service exists and attach this app to Windows Task Scheduler such that it is scheduled to execute based on frequency or a Trigger that you can customize to your requirements such that you will receive an alert if a service has been added or removed etc..
The console app is designed such that on the first run, it logs all
the services on the system and on the subsequent runs it will be
tracking changes made on the services via servicesRemoved and
servicesAdded, with this we can decide what action to take when a
service has been modified
Console App: ServiceDetector.exe
static void Main(string[] args)
{
var path = #"C:\AdminLocation\ServicesLog.txt";
var currentServiceCollection = ServiceController.GetServices().Select(s => s.ServiceName).ToList(); //Queries the most current Services from the machine
if (!File.Exists(path)) //Creates a Log file with current services if not present, usually means the first run
{
// Assumption made is that this is the first run
using (var text = File.AppendText(path))
{
currentServiceCollection.ForEach((s) => text.WriteLine(s));
}
return;
}
// Fetches the recorded services from the Log
var existingServiceCollection = File.ReadAllLines(path).ToList();
var servicesRemoved = existingServiceCollection.Except(currentServiceCollection).ToList();
var servicesAdded = currentServiceCollection.Except(existingServiceCollection).ToList();
if (!servicesAdded.Any() && !servicesRemoved.Any())
{ Console.WriteLine("No services have been added or removed"); return; }
//If any services has been added
if (servicesAdded.Any())
{
Console.WriteLine("One or more services has been added");
using (var text = File.AppendText(path))
{
servicesAdded.ForEach((s) => text.WriteLine(s));
}
return;
}
//Service(s) may have been deleted, you can choose to record it or not based on your requirements
Console.WriteLine("One or more services has been removed");
}
Scheduling Task
Windows Start > Task Scheduler > Create Basic Task > Set Trigger > Attach your exe > Finish
You're right that deleting a Windows Service does cause an event to be added to the System Event Log (source: https://superuser.com/questions/1238311/how-can-we-detect-if-a-windows-service-is-deleted-is-there-an-event-log-id-for-i).
AFAIK there's no audit policy to audit the deletion of a service and I think if there were I think it would be listed here: https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/basic-audit-process-tracking
I assume polling ServiceController.GetServices() is out of the question because your program might not be running when the service is uninstalled?
There are lots of ways to build instrumentation, until you learn what constitutes good instrumentation. My how-to is essentially taken directly from the Wikipedia entry https://en.wikipedia.org/wiki/Instrumentation.
Instrumentation How-to
http://www.powersemantics.com/e.html
Non-integrated
Primary data only
Pull not push
Organized by process
Never offline
The solution to the problem of measuring indicators exists, but you're stuck conceptualizing how to also have "push-based" instrumentation signal another system. As my E article explains, instruments should always pull data never push it. Event-driven signalling is a potential point of failure you don't need.
To clear up any indecisiveness or doubts you may have about building a separate application, monitors are normally independent (non-integrated as Wikipedia says) processes. So saying your monitor "might not be running" means you have not chosen to build a real non-integrated monitor, one which is always on. Your consumer system doesn't correctly model instrumentation, because it integrates the check in its own process.
Separate these responsibilities and proceed. Decide how often the instrument should reasonably poll for deleted services and poll the data with a timer. If you use the API call simon-pearson suggested, you can also detect when services have been added. Of course, the monitor needs to locally cache a copy of the service list so that indicators can infer what's been added or removed.

Create a Windows service without the use of a timer [duplicate]

I made a Window service and let it work automatically and under localsystem account, when the service starts it fires this message for me and then stops
The [service name] service on local computer started and then stopped. Some Services stop automatically if they are not in use by another services or programs.
What's the problem and what's the solution?
Either you are not starting any threads on the OnStart method to do work, or there is an exception raised within your OnStart method.
If an exception is thrown, it will appear in the Windows Event log. The Windows Event log is a good place to start in any case.
Generally an OnStart method looks like this:
Thread _thread;
protected override void OnStart(string[] args)
{
// Comment in to debug
// Debugger.Break()
// Do initial setup and initialization
Setup();
// Kick off a thread to do work
_thread = new Thread(new MyClass().MyMethod)
_thread.Start();
// Exit this method to indicate the service has started
}
This particular error message means what it says - that your service has started but then quite soon it exited for some reason. The good news is that your service is actually doing something, so you have the executable configured and running as a service properly.
Once started, for some reason it is quitting. You need to find out why this is. Add some debugging to tell you its up and running and known exit cases. If that doesn't reveal the problem then add some debugging to let you know it's still running and work backwards from when that stops.
Are you tracing out any debug information? Most likely an exception is being thrown during your initialization. I would trace out all your exceptions and use Debugview to view them.
I had a similar problem that occurred because my Event Logs were full and the service was unable to write to them. As such, it was impossible to debug by looking for messages in the Event Viewer. I put a try/catch and dumped the exception out to a file. I had to change the settings on my logs to fill as needed instead of every 7 days and this allowed the services to start.
Of course, the root of the problem for me is that I have a nVidia driver issue that is flooding my event logs and now I'm probably beating on the disk, but that's another issue.
Maybe you need to run the service as Local System Account. See this post by Srinivas Ganaparthi.
I had the same issue starting JBoss, then I changed the JAVA_HOME variable, it worked for me. It was the JBoss version that doesn't support the 1.6, it supports 1.5.
I had similar problem and it turned out in my case that the program simply crashed in OnStart method. It tried to read some file that it couldn't find but I suppose that any other program crash would give the same result. In case of Windows forms application you would get some error message but here it was just "your service started and stopped"
If you ever need, like me to read some files from the directory where Windows Service .exe is located, check this topic:
Getting full path for Windows Service
In my case, a method in my service, was being called recursively (as no terminate condition being true) and after specific time my service was being stopped.

Catching exceptions in console application C#

I have a console application written in C#. This application runs as automation to test a web service.
Flow:
Log in to network share (impersonate user)
copy mp3 file to local disc
convert mp3 to wav
downsample
trim wave
extract some useful data from wav
send http request
delete local files
write out some stuff to tsv
The application will run great for several hours (usually takes about 24 hours to complete the test). but every once and a while I will get this message: "The application has stopped working. I have been running this is VS 2012 in debug mode so, I can see what line throws any error. problem is, that I have not been able to catch the line (or method) that is throwing the error. I originally thought that the Domain controller was causing this issue due to power settings.
How can I capture exactly what error is bubbling its way up the stack?
Does all that run in a loop of some kind? Or on a timer?
Perhaps put a try-catch around the body of the loop or the method that runs all your code, add a logging framework of your choice (log4net or nlog seem good) and then in the catch log the exception. Most logging frameworks allow you to include the exception and will include stacktrace, etc.
Putting debug logging throughout the process can also help to narrow down where it's happening.
You can go to the Event Viewer on the operating system the console application is running on and then click on "Application". Event viewer logs and displays all exceptions thrown on any application running on the operating system.
try
{
// your code
}
catch (Exception e)
{
System.IO.File.WriteAllText(#"Z:\err.txt", e.ToString());
}
Note that access to windows drives are denied for non administrators so replace Z: with your choice.
I recommend you using a logging framework.
I use log4net in almost all applications. Its very simple to use and configure.
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
// do whatever
}
catch(Exception ex)
{
// Log an error with an exception
log.Error("Exception thrown", ex);
}
By using these kind of libraries you can get your log data output to file, database or even written to the windows event-viewer for instance.
It looks like the exception code you are getting happens when you try to use something that is already been garbage collected. Are you using anything after it is disposed?
Knowledge Base Article for 0xc0000005

What is the proper way for a Windows service to fail during its startup

I need my service to check for existence and structure of certain files during its startup and exit/fail/stop if some conditions aren't met.
I read this thread: What is the proper way for a Windows service to fail?
but it does not help.
I set the ServiceBase.ExitCode property non-zero and then call ServiceBase.Stop. But I get 5 event log entries. See below:
Starting service. (I log this event via code)
Config.xml file not found. (I log this ERROR event via code)
Service stopped successfully. (SCM logs this message)
Service started successfully. (SCM logs this message)
Service cannot be started. The handle is invalid (SCM logs this message)
As you see everything goes OK except for the last two entries. Why are they there? What can I do to properly shutdown the service during startup? Why doesn't SCM see the service as stopped/failed?
You don't provide enough code to really know, but I suspect you are trying to validate the service and stop it in either the constructor or the OnStart. The way I like to handle services is start my timer in the OnStart. In the first interval of the timer I can validate all the code, if its invalid close the Service. If its valid, reset the interval of the timer to how frequently I want it to run then set a bool that tells it not to check for validity of files again.
What is the return code you are using for your ExitCode? If it matches the corresponding windows ExitCode, then that is what will be recorded by SCM. I'm assuming you are returning a 6 for your ExitCode.
The other thing is if you can run on Default values do that, let Config.xml be missing and just record the problem in the EventLog. "Configuration file Missing"
If you really want it to just abort during OnStart, set your ExitCode and then Throw an Exception (InvalidArgumentException, InvalidOperationException) for example
This article also has some good advice. .NET: Which Exception to Throw When a Required Configuration Setting is Missing?
You are trying to start second instance of service (another service registered for the same .exe)

Set service dependencies after install

I have an application that runs as a Windows service. It stores various things settings in a database that are looked up when the service starts. I built the service to support various types of databases (SQL Server, Oracle, MySQL, etc). Often times end users choose to configure the software to use SQL Server (they can simply modify a config file with the connection string and restart the service). The problem is that when their machine boots up, often times SQL Server is started after my service so my service errors out on start up because it can't connect to the database. I know that I can specify dependencies for my service to help guide the Windows service manager to start the appropriate services before mine. However, I don't know what services to depend upon at install time (when my service is registered) since the user can change databases later on.
So my question is: is there a way for the user to manually indicate the service dependencies based on the database that they are using? If not, what is the proper design approach that I should be taking? I've thought about trying to do something like wait 30 seconds after my service starts up before connecting to the database but this seems really flaky for various reasons. I've also considered trying to "lazily" connect to the database; the problem is that I need a connection immediately upon start up since the database contains various pieces of vital info that my service needs when it first starts. Any ideas?
Dennis
what your looking for is SC.exe. This is a command line tool that users can use to configure services.
sc [Servername] Command Servicename [Optionname= Optionvalue...]
more specificly you would want to use
sc [ServerName] config ServiceName depend=servicetoDependOn
Here is a link on the commandlike options for SC.EXE
http://msdn.microsoft.com/en-us/library/ms810435.aspx
A possible (far from ideal) code solution:
In you startup method code it as a loop that terminates when you've got a connection. Then in that loop trap any database connection errors and keep retrying as the following pseudo code illustrates:
bool connected = false;
while (!connected)
{
try
{
connected = openDatabase(...);
}
catch (connection error)
{
// It might be worth waiting for some time here
}
}
This means that your program doesn't continue until it has a connection. However, it could also mean that your program never gets out of this loop, so you'd need some way of terminating it - either manually or after a certain number of tries.
As you need your service to start in a reasonable time, this code can't go in the main initialisation. You have to arrange for your program to "start" successfully, but not do any processing until this method had returned connected = true. You might achieve this by putting this code in a thread and then starting your actual application code on the "thread completed" event.
Not a direct answer put some points you can look into
Windows service can be started Automatically with a delay. You can check this question in SO for some information about it.
How to make Windows Service start as “Automatic (Delayed Start)”
Check this post How to: Code Service Dependencies

Categories

Resources