Windows Service run only on restarting computer - c#

I have created a windows service which I would like to run whenever Windows starts. To run it after boot completion only, I have inserted below code in installer of service:
this.WinSvcInstaller.DelayedAutoStart = true;
The service is made to run immediately after installation using below code:
private void WinSvcInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(ServiceName);
sc.Start();
}
where ServiceName is property created in WinSvcInstaller.
Once the service completed whether successfully or unsuccessfully it made to stop using below code automatically:
ProjectInstaller projectInstaller = new ProjectInstaller();
ServiceController serviceController = new ServiceController(projectInstaller.ServiceName);
if (serviceController.Status.Equals(ServiceControllerStatus.Running)
|| serviceController.Status.Equals(ServiceControllerStatus.StartPending))
{
this.Stop();
}
My main problem is that the service doesn't run unless I reboot computer meaning, the service runs only if I restart the computer. If I do shut down and then start computer manually again after the shut down then the service doesn't run. Can anybody please help me why is this happening??? What I am missing?

Related

C# Service installer - Upgrade install not stopping service before uninstall

Please review the code below for my project installer BeforeInstall event. The event is being called, as the install completes successfully and will uninstall my service, before installing the new one, but ONLY if I stop the running service before running the installer for the new version.
For some reason, the code in the event is either not stopping the service, or it is not waiting for the service to stop, both of which I am telling it to do before going on to uninstall the service - which again, will complete successfully if the service is not running. It does not appear to even stop the service because after I get the error that resources are in use, I look in services and see that the service is indeed still running. For reference I have also included the AfterInstall event which successfully starts my service.
[EDIT]
It seems like the check to see if the resources are in use is occurring before my event fires. Actually, I've since tried multiple events from the installer and service installer to no avail. Such as OnBeforeUninstall... etc... I've tried multiple methods of shutting down the process including opening cmd.exe and running sc stop on my service. It does not even attempt to run cmd.exe before it checks if resources are in use. Is there a better place to run the service stop code before the resource check happens? I've even thrown it in before Initialize component on the project installer class. Does anyone know when the resource check happens?
void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == this.serviceInstaller1.ServiceName)
{
if(s.Status == ServiceControllerStatus.Running)
{
s.Stop();
s.WaitForStatus(ServiceControllerStatus.Stopped);
}
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new InstallContext();
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = s.ServiceName;
ServiceInstallerObj.Uninstall(null);
break;
}
}
}
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
using (ServiceController s = new ServiceController(serviceInstaller1.ServiceName))
{
s.Start();
}
}

Unable to Manually Start C# Windows Service

I have created a Windows Service project in Visual Studio Community 2015 on my Windows 10 laptop (upgraded from Windows 7 and fully updated), but I have been unable to successfully start my service manually, and I am unable to force kill the service once it has begun to start. When I attempt to start my service via the Services Console (services.msc), I get the following behavior:
A "Service Control" dialog pops up with a progress bar.
The progress bar fills slowly over the course of 90 seconds.
When the progress bar is full, I receive Error 1053.
The service's state changes to and remains infinitely at "Starting" (Start Pending).
The service can not be stopped by any means besides a forced reboot.
I've come to understand that Error 1053 is the result of a service that is unable to start after 30 seconds. However, there is no possibility of my service taking longer than 30 seconds to start. My OnStart, OnStop, and OnTimer methods are currently as follows:
protected override void OnStart(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 10000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected override void OnStop()
{
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
}
And my Main method looks like this:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyNewService()
};
ServiceBase.Run(ServicesToRun);
}
Strangely, if my service's startup method is set to "Automatic" then the service will indeed start on its own the next time Windows restarts. When it is started automatically, I am able to manually stop the service (this is the only time it will stop manually). However, after successfully stopping it manually, I still cannot re-start it manually. Attempting to do so produces the exact same behavior as described earlier, resulting again in Error 1053.
My service installs without error (via installutil), and I can uninstall without error. However, if I attempt to uninstall my service (via installutil /u) while the service is stuck in "Starting" (Start Pending) mode, the service does not stop, remains as "Starting", and the startup mode switches to "Disabled". Only upon restarting is the service completely removed.
My question:
Why does my service start automatically on Windows startup, but not by any other manual method? (I need it to start automatically, but also be able to manually start and stop it.)
Thank you for your time and expertise.
The issue was Avast anti-virus stopping the service silently. Annoyingly, Avast does not report the service as a virus or a threat of any kind and makes no log of the blocked service. I was able to successfully start and stop my service manually once I had disabled Avast. As a semi-permanent solution, I have added the path to my service to Avast's exceptions list by going to Settings -> Active Protection -> Customize (File System Shield) -> Exclusions, and clicking "Add."
To answer my original question, my service was able to start automatically on Windows startup because it was able to start before Avast was loaded. This led to the strange behavior I observed where I was able to stop it after it had started automatically, but not restart it manually since Avast was now running by that point.
You shoud cleanup service in method OnStop.
You create a timer and never stop it.
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Interval = 10000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer = null;
}

Unable to start and stop service using ServiceController

I have the below methods to start and stop a service. I call this method from another Console application to debug since I've used the methods in a Class Library(DLL).
The application is started with administrative rights.
public void ServiceStart()
{
ServiceController service = new ServiceController();
service.ServiceName = "ASP.NET State Service";
service.Start();
}
public void ServiceStop()
{
ServiceController service = new ServiceController();
service.ServiceName = "ASP.NET State Service";
service.Stop();
}
But when I call Start() or Stop() an exception with the following message is thrown:
Cannot open ASP.NET State Service service on computer '.'
Can someone help me out?
You have to pass the Service name, not the Display name.
Always check the service properties in the "Services" application.
Try again with
service.ServiceName = "aspnet_state";
Alternatively, you can create the ServiceController instance using the display name:
ServiceController service = new ServiceController("ASP.NET State Service");
since the documentation for the constructor argument says:
The name that identifies the service to the system. This can also be
the display name for the service.
Also note that a call to
service.Start();
returns immediately, without waiting for the service to start.
You should call
service.WaitForStatus(ServiceControllerStatus.Running);
if you want to make sure the service is running before your application continues.
Open Visual studio as Administrator

How can a windows service programmatically restart itself when another windows service is restarted?

I work on windows service project , i want to restart my windows service when Lync Front-End service was restarted
i know how i restart my windows service i use this answer , but i don't know how i restart it when the Front-End Service was restarted
and i know i can check the windows service status by use ServiceController Class
Run this code in your service :
EventLog log = EventLog.GetEventLogs().First(o => o.Log == "Security");
log.EnableRaisingEvents = true;
log.EntryWritten += (s, e) => {p.print(e); };
Write a method for event log
void test(EntryWrittenEventArgs entry)
{
//you can check event log in the log viewer and set
//EventLogEntryType and InstanceId accordingly.
EventLogEntry evntLog=entry.Entry;
if (evntLog.EntryType == EventLogEntryType.SuccessAudit &&
evntLog.InstanceId==123)
{
//Code to restart the service
}
}
I) Topshelf is an open source project for developing Windows Services easily. It will save you time and even if you decide not to use it, you can learn from it's source code.
II) The short answer is you have to poll the status of the other service. There is no (plain) event based mechanism for this.
If you can not make any modifications to the other service then you can poll over it's status by (in a separate Task):
var sc = new ServiceController(serviceName);
status = sc.Status;
And use the answer you've mentioned to restart yours (and again poll in OnStart until the other service get started completely).
But if you can modify the other service then you can use other means like pipes or named mutexes to do that (again needs polling in a separate Task or at OnStart and probably at OnStop).

How to auto start window service

I have a window service which i developed in c# (vs2008).
please tell me what should i do to make it auto start after installation and also auto start on every time when system gets restarted.
EDIT:
I am using setup & deployment project to install it.
Thanks
Follow the instructions given here to add an installer to your Service application. Pay particular attention to step 5, where you set the StartType property.
To start the service after installation, see Automatically start a Windows Service on install
Try following way,
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
var service = new ServiceController(serviceInstaller.ServiceName);
if (service.Status != ServiceControllerStatus.Running)
{
service.Start();
}
}

Categories

Resources