I would like to disable service programmatically through registry. To do that, I modify the following registry key : Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\SensorDataService\Start, where I set its value 0x4 which corresponds to disabled state. Now, when I check service in Windows Service Manager - it's reported as disabled and I can't start it.
However, if I try to have it started programmatically like this:
var serviceController = new ServiceController("SensorDataService");
try
{
serviceController.Start();
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Then service is started...
When I disable service through windows service UI or SC command line, then I got exception stating that can't start disabled service, exactly what I expect.
Does anyone know if setting above-mentioned value in registry is just not enough to disable the service?
Related
I'm a beginner, trying to develop a windows service that sends emails before the expiration date of an insurance policy. I set the service for auto start, yet it doesn't appear to start automatically (seen on Services console). And when I start it manually, it does send the alerts but stops with error 1064, which after checking the event viewer is caused by other instance of the service, already running. Yet, if I don't attempt to start the service manually no alerts are sent.
I tried to uninstall the service using installutil and reinstall it, to assure there's only a single instance running.
//According to event viewer this is the block of code where the issue occurs.
ServiceController[] services = ServiceController.GetServices();
// Iterating each service to check that if a service named
// EmailExpiracaoSeguroAuto is found then check that its status whether
// it is running or stopped. If found running then it will
// stop that service; else it starts that service
foreach (ServiceController x in services)
{
if (x.DisplayName == "EmailExpiracaoSeguroAuto")
{
if (x.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
x.Stop();
}
else
{
//More precisely HERE
x.Start();
}
}
}
}
My expectation is being able to overcome this error, having the service starting automatically and keep it running.
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.
I have created a windows service to send mail when service is started. The service works fine like it sends mail when i debug the service and run it via code. But the service is not working after i install it. It is not sending any mail after i install the service.
Can anyone please suggest me the solution?
There is an excellent chance that the service lacks permission to perform one or more actions when run as a service account.
Check the Windows Event Log for any related error messages. As a test, you can configure your service to run as the same user you log on with (just to make sure the issue is permission based... do NOT leave that configuration active as it is a major security hole).
Debugging service is a bit difficult.
use try..catch block with writing messages to file in every method; for example
try
{
..
}
catch(Exception ex)
{
SaveMessage(ex.ToString());
}
Save message method would be:
static void SaveMessage(string s)
{
StreamWriter sw = new StreamWriter(#"C:\service_exceptions_file.txt", true);
sw.WriteLine(s);
sw.Close();
}
Then you will see where is the problem.
Also you can add some messages in your code via abovementioned method to see what parts of code are working without problems
In your Main() method, just add the following lines before ServiceBase.Run(ServicesToRun); :
#if DEBUG
while(!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
#endif
Then install your service and launch it.
While it's launching, attach your debugger to your service's process (Debug Menu => Attach to process) and you should be able to debug it.
Don't forget to set your breakpoints before launching your service.
I have the windows service program which runs and sometime throw exception about system null reference. After my investigation, this is due to MySQL connection cannot establish due to MySql instance not up yet when startup computer. How to solve this problems???
thanks in advance
You can set in Windows the dependencies of each service.
You can go into Control Panel -> Administrative Tools -> Services (or run 'services.msc' from the command line). By double clicking any of the services and going to the Dependencies tab you can see what each service relies on.
Your service relies on the MySql service, so MySql should be in the dependencies list for it.
You can add items to the dependencies, here is a description of how to do this:
https://serverfault.com/questions/24821/how-to-add-dependency-on-a-windows-service-after-the-service-is-installed
This article can give you a hint on how code service dependencies:
http://bloggingabout.net/blogs/jschreuder/archive/2006/12/07/How-to_3A00_-Code-Service-Dependencies.aspx
Try the following code if you want to do it by yourself without dependencies
//Check if service is running
ServiceController mysqlServiceController = new ServiceController();
mysqlServiceController.ServiceName = "MySql";
var timeout = 3000;
//Check if the service is started
if (mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Stopped
|| mysqlServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Paused)
{
mysqlServiceController.Start();
try
{
//Wait till the service runs mysql
ServiceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, timeout, 0));
}
catch (System.ServiceProcess.TimeoutException)
{
//MessageBox.Show(string.Format("Starting the service \"{0}\" has reached to a timeout of ({1}) minutes, please check the service.", mysqlServiceController.ServiceName, timeout));
}
}
I have 2 other services running on a server and they start and stop without a problem, however one of them will not start. I can't see any difference in their implementation or config files. I'm receiving the following messages when attempting to start the service after installing it with InstallUtil:
The service is not responding to the control function
more help is available by typing NET HELPMSG 2186
NET HELPMSG 2186:
Explanation: The service cannot run your command at this time
Thanks very much in advance!
This is most likely due to service installed, then uninstalled and now you are trying to install again. Reboot the machine and try again.
UPDATE
According to the event log error, you are trying to run the service as the current logged in user (I guess you are connected using remote desktop). This is not the correct approach, you need to run the service as the LocalSystem. In the project properties window, change the identity of the service.
UPDATE 2
In the design view of the service/component class, click on serviceProcessInstaller1 (or similar) and then in tmhe properties you see a drop down: Account with 4 entries: User/LocalNetwork/LocalService/LocalSystem. Make it LocalSystem
On Start event can you put
try
{
//...
}
catch(Exception ex)
{
EventLog.WriteEntry(ex.Message + ex.StackTrace);
}
and watch whats happening?
or
attach (Tools > Attach To Process) your process to Visual Studio for DEBUG. You can see whats happening with debug, but EventLog works good aswell.