I have a windows service which should stop after some particular date time.
I am able to stop the service programmatically using:
try
{
ServiceController service = new ServiceController(servicename);
//or
//ServiceController service = new ServiceController(servicename,computer name);
service.Stop();
}
catch(Exception ex)
{
}
finally
{
ServiceController service = new ServiceController(servicename);
service.Stop();
}
But it throws an exception and does not stop if we remove the finally part.
It stopped only after I used the finally statement but obviously the exception persists.
Exception message:
Cannot open "Service Name" service on computer '.'
detailed exception:
Cannot open Service Control Manager on computer 'computer name'. This operation might require other privileges.
I did refer but it does not help also it is not addresses my problem:
Stackoverflow Question
How can I stop the service programmatically without this exception
Right click on the program and choose "Run As Administrator". If you are debugging it, ensure the IDE ( ie Visual Studio I suppose ) is opened with "Run as Administrator".
When I had this problem I went to the machine in question, and tried to stop the service manually though the interface, and received this pop-up:
I was able to stop the service by finding the task in Task Manager and ending that task. Not sure what exactly hung up the service but this works if you have access to the machine and task manager.
I was able to start the service and use the ServiceController code without any issues after.
Related
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.
I created a windows service which watches a directory. When a file is dumped into it, it takes the data and puts it into a database. Then this file is moved to another directory and deleted. It works fine in debug mode. But when i install it on my computer it stops after throwing the data into the database and the file in question is neither moved or deleted. I suspect a permission issue is involved. I tried to create a event log:
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
So i have three questions.
(1) What could be causing my service to work as described in debug but fail when installed on my computer.(2) I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method.(3) Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools? stored as a file on some directory?
Here is edit to this post in lieu of the grateful advice given below.
try
{
File.Move(e.FullPath, finalString);
File.Delete(e.FullPath);
}
catch(Exception q)
{
EventLog.WriteEntry("MySource", q.ToString(), EventLogEntryType.Error);
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["fmd"], true))
{
w.Write(DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss"));
w.Write(q.ToString());
}
}
As per suggestion i put a try-catch around the file move and delete plus i added a OnShutdown method:
protected override void OnShutdown()
{
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["ond"], true))
{
w.Write("stop OnShutdown");
}
//EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
}
I do not know how to pass any system error message to the shutdown method, so any advice appreciated. When i installed my modified code as a service, it again stopped before moving or deleting the files. Neither of my two logs accessed by a stream recorded anything. Plus the event viewer showed nothing either?
You can write as following,
if (!EventLog.SourceExists("MySource"))
EventLog.CreateEventSource("MySource", "Application");
EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
to view the event log messages, Goto Administrator Tools -> Event Viewer and look for the source you have created. or Just simply type eventvwr in run window.
When Services installed, it works under SYSTEM User account where service might not have access to some resources. Please put logs and see where exactly the issue is.
If you service installed in your development machine, use attach to process option under DEBUG Menu in Visual Studio to find out.
What could be causing my service to work as described in debug but fail when installed on my computer?
Permissions. The service is likely running under LocalSystem or Network Service if you didn't provide a different identity.
I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method?
Yes, you're assumption is correct.
Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools?
Just hit Windows Key+R to get the Run dialog and type eventvwr.
Well i found the reason for all the commotion. I eventually found some logs in the event viewer. They were listed in Administrative events in custom logs. There were three error logs: .Net runtime; Application error & Service Control Manager. In '.Net Runtime' the stack showed a unhandled exception for system.windows.forms. I stupidly included a pop up box in my release version. But even when i commented this away; i got a error. So i went back and found other message boxes, primarily in try catch statements. Removed these and solved the issue.
I have a Windows service that runs on my local PC. My operating system is windows 7. I want to Start my service via C# code without going through "Computer Management > Services".
When I run the code below it gives me the following Exception:
"Service {ServiceName} was not found on computer '.'."
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
I've been through many posts regarding this scenario and all mention that this is a security feature of Windows 7. Is there a way to run this service without middling the Admin Groups?
You're probably running into a UAC problem. You need to add a manifest file to your app the indicates the app must be run as an administrator. This will cause Windows to prompt for elevation when your program runs. Here's an article that walks you through the issue/solution:
http://www.codeproject.com/Articles/17968/Making-Your-Application-UAC-Aware
And a related stackoverflow post:
How do I force my .NET application to run as administrator?
It can be about ur framework couldnt selected. U can select it then refresh ur IIS.
I am currently working on an application where I am creating a ServiceHost, then getting rid of it, then recreating it later. The problem is that once I get rid of the service host when I try to recreate it I get the exception "A registration already exists for URI after stop/start." The weird thing is I have three separate hosts and one works and two don't. I assume something is not being disposed of properly but I'm not sure why.
I am creating the hosts like this
host = new ServiceHost(typeof(MyService));
host.Open();
Then getting rid of them like so
if (host != null)
{
host.Close();
host = null;
}
I have also tried abort instead of close without any luck.
Though I am not sure about the exact issue, I can give you a little thought on it and some workaround.
If you are working in Windows 7, any URL you create as part of your hosting has to get registered. Netsh command usually helps us register and unregister the URLs.
For both registering and unregistering URIs you need to have admin permission.
You may try the following.
If you are running your exe, try running it in Administrator mode. (Right click and select admin mode).
If you are trying out with visual studio, try to restart the visual studio in admin mode and run the app.
Try to unregister the URI and try again using Netsh.
http://saravananarumugam.wordpress.com/2011/03/01/http-could-not-register-url/
may help you.
I have a standard windows server that inherits from the ServiceBase class.
On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.
For example:
protected override void OnStart(string[] args)
{
if (condition == false)
{
EventLog.WriteEntry("Pre-condition not met, service was unable to start");
// TODO: Convert service state to "Stopped" because my precondition wasn't met
return;
}
InnitializeService();
}
Anybody have a good example for how a service can control its own state?
Throw an Exception. This will cause the services MMC to get an error - and the exception message and stack will automatically be logged to the event log. I use ApplicationException in this case.
In addition, the service will return to the "not running" state.
If you need to stop later on, you can call the Stop method on your ServiceBase.
The error shown the user in the "Computer Management" MMC app does not seem to get the exception text correctly in Vista. It shows the following:
The "your service name here" service
on Local Computer started and then
stopped. Some services stop
automatically if they are not in use
by other services or programs.
However it writes correctly to the Event Log just fine.
Very Cool. Thanks.