Unable to Manually Start C# Windows Service - c#

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;
}

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();
}
}

Restarting a service after a fatal crash

I have several services that run correctly 99.9% of the time. However, they work with network and database and occasionally an error that I have not anticipated makes it into the code and causes the service to crash. In this instance, restarting the service usually fixes the problem.
My service creates a new thread where the main code is run. I have added error handling to the service class that catches and logs any unhandled exceptions from this thread. What I am wondering is if I can call OnStop and then OnStart from the service class to restart my service?
The code that I am using is in located in the same class as OnStart and OnStop. I have posted it below:
private void ExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
log.Append("Fatal Exception:\n" + args.ExceptionObject);
eventLog.WriteEntry(log.ToString());
log = new StringBuilder();
OnStop();
if (numberOfCrashes++ < 10)
{
Thread.Sleep(60000);
OnStart(null);
log.Append("The service has been restarted " + numberOfCrashes + " times.");
eventLog.WriteEntry(log.ToString());
log = new StringBuilder();
}
}
What I am wondering is if I can call OnStop and then OnStart from the
service class to restart my service?
This will depend on how you've implemented your OnStart and OnStop logic.
For example, if your OnStart is able to determine if the working thead is already started and, if so, it stops and starts it again, then yes, you may be able to simulate a service restart by directly calling these methods.
Thus, your actual code on OnStart and OnStop is the right answer to your question, and it's up to you to refactor it to cover your requirement of programatically-restarting your service without restarting the service at the operating system level.

Windows Service output not showing up in Event Log

I am trying to follow this walkthrough.
I'm using Visual Studio 2010 Premium.
The only events I see in Server Explorer or in Event Viewer are "Service started successfully." and "Service stopped successfully."
Here is the service code:
namespace MyNewService
{
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
if (!EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
}
}
I had the same issue with Visual Studio 2010 Professional on Win 7 64. My newly compiled service was installed with InstallUtil.exe running as Administrator. It started and stopped correctly. No exceptions but no amount of refreshing the Event Viewer revealed a new event log. Fran71's suggestion worked for me: I closed the Event Viewer and reopened. VoilĂ , the newly created application log file appeared.
FWIW, I ran into this problem in Win8 and found that Refreshing the Event Viewer did not cause my newly created Event Log to show up, but closing and reopening Event Viewer did. Was driving me insane since no exceptions were being thrown when Creating the Event source or writing a log entry.
Probably a permissions problem. Like the commenter said, try running VStudio or your compiled service as an Administrator.
Also, you can still debug a service - put a thread.Sleep(up to 20 seconds) as your first line (to give yourself time to attach the debugger), then put a break point on the line after that. Then go Tools --> Attach To Process and select your .exe. If you get that done before the end of your Thread.Sleep() then you should break.
Keep in mind that the service must complete the OnStart within IIRC 30 seconds or Windows will think it is not responding and kill your process, so move your code out of the service start if you are going to do much debugging. Just throw a timer in there or something.
To make it easier to debug, consider moving your functionality to a DLL and then keep your service to just enough code to call into your DLL - this will ease unit testing and debugging - but don't forget that lots of things change when you're actually running it as a service.

C# about Windows service

What would be a short example with a Windows service and how to install and run it?
I've searched on the Internet, but what I've tried didn't have anything written on the On Start method. Plus, when I've tried to install it the error OpenSCManager keeps popping up.
Find install util at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
Then run InstallUtil.exe "c:\myservice.exe"
Go to services.msc and then locate and start your service
Here are some examples about how to write and install a Windows service in C#:
A Windows Service Application
Simple Windows Service Sample
ASP.NET Tutorials : Creating Windows Service in C#
Creating a Windows Service in C#
How to Create and Work With Windows Services in C#
Creating a Simple Windows Service in C#
My answer to this question gives you step-by-step instructions for creating a Windows service in C#.
Easiest language for creating a Windows service
My answer to this question shows you have to modify the service so that it can install and uninstall itself from the command line.
How to make a .NET Windows Service start right after the installation?
InstallUtil.exe has been part of .NET since 1.1, so it should be on your system. However, you likely can't use it from a 'normal' command prompt. If you have Visual Studio installed, open the Visual Studio command prompt. That'll define the appropriate environment variables that make InstallUtil accessible without path information.
The OnStart() callback gives you an opportunity to start the business logic of your service. If you don't do anything in the OnStart() callback, your service will immediately shut down. Typically, you'll start a thread that performs the work you're interested in. Here is a small example to show you what it looks like.
private static System.Timers.Timer _timer;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Write a message to the event log.
string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime);
EventLog.WriteEntry(msg, EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
// Create a timer with a 10-econd interval.
_timer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Signal the timer to raise Elapsed events every 10 seconds.
_timer.Start();
}
protected override void OnStop()
{
// Stop and dispose of the timer.
_timer.Stop();
_timer.Dispose();
}
Doing something like this will effectively keep your service running until it shuts down. Hope this helps.

Why doesn't System.Threading.Timer callback fire?

I'm not using a Windows Form Timer--I'm using a System.Threading.Timer. No exceptions are raised when instantiating the timer, and to my understanding, System.Threading.Timer's do not need to be explicitly started.
I've tried using a System.Timers.Timer (See comments in code) and changing the signature of the callback with no luck. Inside the callback method, I stubbed in some EventLog writes, and not even the first writes to the event log. All I see in the Event Log is MyService.OnStart fired followed by MyService started (these are both from the OnStart event). Why aren't the timer callback events firing?
public partial class MyService : ServiceBase
{
private static System.Threading.Timer timer;
public MyService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MyService"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MyService", "MyServiceLog");
}
eventLog1.Source = "MyService";
eventLog1.Log = "MyServiceLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("MyService.OnStart event fired");
// setup timer to poll and execute an event
//Timer timer = new Timer(new TimerCallback(CheckCalls), null, 0, 10000);
try
{
timer = new System.Threading.Timer(new System.Threading.TimerCallback(CheckCalls), null, 0, 10000);
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message + " Stacktrace: " + ex.StackTrace);
}
eventLog1.WriteEntry("MyServicestarted");
GC.KeepAlive(timer);
}
}
and the callback method, CheckCalls:
private static void CheckCalls(object objectState)
{
EventLog eventLog1 = new EventLog("MyServiceLog", "DAVIDWIN7", "MyService");
eventLog1.WriteEntry("MyService is polling");
}
Arg--For some reason when you Build->Clean Solution, then Build->Build Solution, Visual Studio does not rebuild your setup project. I believe my code above works fine, but I had tried many different fixes without explicitly right-clicking the setup project and selecting Build.
I thought Clean Solution would force all projects to be rebuilt on next build???
it's got to be an error with the timer thread writing to the event log.
I got it working on my computer but I replaced all the eventlog with Console.writeline because I didn't want to mess with my event log permissions.
Did you check if the account under which the service is running has access to the eventlog?
Please can you go and download this test application which mirrors exactly the scenario you are talking about:
https://docs.google.com/leaf?id=0Bw_NnV9fhgmgMThjNDgzOTgtODNiOC00NDE1LWEyMTYtNzVhOTMyNzlmZjZk&hl=en&authkey=CMuupNkC
I've just created this. It's a service that effectively uses the same code as you. The only difference is that I have used the toolbox to drag and drop an eventlog on to the service designer - setting the log to 'Application' and the source to 'Service1'.
Open a VS command prompt at the project folder, go to bin\debug and run installutil windowsservice1.exe - specifying some credentials (so you're installing the dev service directly from your bin output folder).
Start the service and monitor the application log - it will write every ten seconds as you expect to see from your code.
Assuming this works on your machine(tm) like it does on my machine(tm) then I would suggest that the problem is the event logging itself, or, horror of horrors - your service isn't running from your build output folder (most of the devs in my team insist on running their dev services from a different folder and then swear when they forget to actually update the binaries when they start debugging it!).
As I suggested in my comment, you really need to be able to attach the debugger to this and breakpoint the callback to verify that it's not getting fired. I never rely on the eventlog for diagnostics messages simply because the log might be full, or permissions might prevent you etc etc - it might be a windows platform component, but it's not as reliable as I would like.
The debugger, however, rarely lies (unless the deployed binaries are out of date ;) ). Compile a debug build of your project and make sure it's the one that is installed in the services list, start it up and then attach directly to the service exe (there's no point trying to attach to [service].vshost.exe - VS cannot auto-attach or host windows services as the only way they can run is via svchost.exe shelling them).
Hope this helps.

Categories

Resources