I'm developing a service using .NET on Windows platforms.
It had worked until yesterday... but today it doesn't want to start!!! It seems strange, and I feel I'm missing something...
I've also tried to revert sources to the last working version, but nothing else happens: net start outputs:
The service is not responding to the control function.
What could cause this malfunction?
Probably most of you wants to know more about it. So, let me show you some code:
The service code:
#if DEBUG
class iGeckoService : DebuggableService
#else
class iGeckoService : ServiceBase
#endif
{
static void Main()
{
#if DEBUG
if (Debugger.IsAttached == true) {
DebuggableService[] services = Services;
// Create console
AllocConsole();
// Emulate ServiceBase.Run
foreach (DebuggableService service in services)
service.Start(null);
// Wait for new line
Console.WriteLine("Press ENTER to exit..."); Console.ReadLine();
// Emulate ServiceBase.Run
foreach (DebuggableService service in services)
service.Stop();
} else
ServiceBase.Run(Services);
#else
ServiceBase.Run(Services);
#endif
}
#if DEBUG
static DebuggableService[] Services
{
get {
return (new DebuggableService[] { new iGeckoService() });
}
}
[DllImport("kernel32")]
static extern bool AllocConsole();
#else
static DebuggableService[] Services
{
get {
return (new ServiceBase[] { new iGeckoService() });
}
}
#endif
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public iGeckoService()
{
// Base properties
ServiceName = DefaultServiceName;
// Service feature - Power events
}
#endregion
protected override void OnStart(string[] args)
{
try {
...
} catch (Exception e) {
sLog.Error("Unable to initialize the service. Request to stop.", e);
}
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
...
}
}
[RunInstaller(true)]
public class iGeckoDaemonInstaller : Installer
{
/// <summary>
/// Default constructor.
/// </summary>
public iGeckoDaemonInstaller()
{
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = iGeckoService.DefaultServiceName;
si.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] {spi, si});
}
}
class DebuggableService : ServiceBase
{
public void Start(string[] args) { OnStart(args); }
}
The start script is:
installutil ..\bin\Debug\iGeckoService.exe
net start "Gecko Videowall"
while the stop script is:
net stop "Gecko Videowall"
installutil /u ..\bin\Debug\iGeckoService.exe
However, I think it is a system setting, since the application has worked well until the last day. (Sigh).
Update
When the service was working, I used log4net for logging service activity (I'm unable to attach the debugger to the running service...), and it has always logged.
From now, the log4net log it is never created (even if I enable internal debug option), even if I log at the Main routine!
Another update
It seems that the application is never executed. I've reduced every routine (Main, OnStart, OnStop), and I run an empty service. OnStart routine creates a file on a directory (fully writeable by everyone), but when the service is started, no file is created.
Yet another update
Stimulated by the Rob's comment, I've seen this message on the event viewer:
> Faulting application name: iGeckoService.exe, version: 1.0.0.0, time stamp: 0x4c60de6a
> Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b
> Exception code: 0x80000003
> Fault offset: 0x000000000004f190
> Faulting process id: 0x1258
> Faulting application start time: 0x01cb384a726c7167
> Faulting application path: C:\Users\Luca\Documents\Projects\iGeckoSvn\iGeckoService\bin\Debug\iGeckoService.exe
> Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
> Report Id: b096a237-a43d-11df-afc4-001e8c414537
This is, definitively, the reason on the service shutdown... not question becomes: "How to debug it?" (Thank you Rob, I've never thought about the event viewer until now!)
Debugging it running as console application it doesn't show any error, indeed it seems related to the service environment. The only thing that comes to my mind could be some DLL loading failure, since now the service is empty... any idea?
(Thank you all for following me... I'd like to offer you pizza & beer)
Solved!
The service was unable to start since a crash before the Main routine, caused by the installation and the setup of the MS Application Verifier (x64). After having uninstalled that application, everything worked as usual!
Thank you all!
In general every service must do following two simple things
if the service manager send him a control code like SERVICE_CONTROL_START, SERVICE_CONTROL_STOP and so on if should return in a short interval. Using SetServiceStatus function service can prolong this interval for example with calling SetServiceStatus with incremented dwCheckPoint value. (In .NET use can use ServiceBase.RequestAdditionalTime instead)
every service must answer to SERVICE_CONTROL_INTERROGATE control code just with return. This control code are used from the service manager to detect whether the service still living.
If your program don't follow one of the rules you receive the error "The service is not responding to the control function."
If you write a program in .NET you don't need to do directly the two things which I described before. The ServiceBase class do there for you. Nevertheless you can easy break this rules if create a thread running with priority higher as normal or if you do some too long work inside an OnXXX handle (OnStop, OnStart, OnPowerEvent etc) without calling of ServiceBase.RequestAdditionalTime. Some other tricks with additional threads can also make problems.
Usually this happens if you're trying to do too much work in the OnStart call. For example, if you start an endless loop in the same thread, you'll get this error message.
Generally the service should create a new thread in the OnStart call, and then cleanly terminate it in the OnStop call.
Of course that doesn't help if you're using code which was previously working. Have you tried rebooting it since the failure? I seem to remember that if you've already got a service which is borked, it can sometimes be tricky to get back to a working state without rebooting it. You may want to look in your process list and see whether you've got a copy still running, and kill it if so.
For me it just meant that an exception was being thrown. (Platform conflict in Configuration Manager, resulting in "bad image format".) Try running the .exe from the command line and see if you get an error.
I see that there is a code block
// Wait for new line
Console.WriteLine("Press ENTER to exit..."); Console.ReadLine();
as stated by #Jon since this is a service. when service starts it waits for a stipulated time within which it should respond.
there is a statement "Console.ReadLine()" you service will wait until key is pressed. since this is a service will keep waiting at this point
For me it was an error in the file that is configured to the windows service. I found a syntax error due to which I was getting this error code.
Fixed the syntax error and I was able to restart the service again.
Related
I'm trying to run some console app as windows service, I followed this question, and I made a few changes to make it fit to my app.
My main code looks like that:
public static class Program
{
public class Service : ServiceBase
{
public Service(string serviceName)
{
this.ServiceName = serviceName;
}
protected override void OnStart(string[] args)
{
Program.Start(args);
}
protected override void OnStop()
{
Program.Stop(this.ServiceName);
}
}
#endregion
static void Main(string[] args)
{
if (!Environment.UserInteractive)
// running as service
using (var service = new Service("TestService"))
ServiceBase.Run(service);
else
{
// running as console app
Start(args);
}
}
private static void Start(string[] args)
{
while(true)
{
//DO SOMTHING
}
}
private static void Stop(string serviceName)
{
//Writing to log that 'serviceName' stopped
}
}
I tried to run the following console app as a service, by using the following steps:
1) Use the command: sc create ServiceTestName123 binPath= "PATH TO THE EXE FILE IN THE PROJECT DEBUG FOLDER".
2) Use the command: sc start ServiceTestName123 "parameter1".
And I got an error:
"StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion"
I read about the error in the internet and found out that I can try to solve this problem by running the start function with another thread, so I updated the OnStart function to the following function:
protected override void OnStart(string[] args)
{
Thread t = new Thread(() => Program.Start(args));
t.Start();
}
After trying to re-create the service (delete the old one and create the service again with the new OnStart function) and re-run it I got the same error.
By the way, when I ran this code as console app it worked properly.
Could someone please explaing me what am I doing wrong?
Thanks a lot.
I tried your exact steps and it worked for me. I will highlight a few key points that I came across
OnStart should definitely return in a timely fashion. i.e. the work should happen in a separate process/thread. I used your code for thread and it worked fine for me.
Make sure the executable is on a local drive which can be accessed from your "Local System" account without any permission issues.
Make sure when you create the service, you provide the absolute path and not relative path.
Make sure the sc create ... command responds back with [SC] CreateService SUCCESS
Check the service was created in the service control panel
Make sure you can start it from the service control panel before attempting it from command line
Also, open task manager or process explorer to make sure the service executable is running or not (irrespective of what status is returned by service control panel or scm start)
For debugging, I logged the information into a local temp file - again watch out for permissions issues with Local System account.
If for whatever reasons you have to delete the service, make sure that it indeed disappeared from the service control panel
To debug what's going on, you can attach the debugger at the very beggining of your program start up.
This way, you can check what your program is doing.
You can also check in the Windows ever viewer, the error that windows is throwing.
Put this line at the start trace of your program:
System.Diagnostics.Debugger.Launch()
NOTE: I'm not doing anything similar to Topshelf installer requires me to press enter twice - why?
Service class (interesting parts):
public class ServiceCore
{
public ServiceCore(ServiceRuntimeConfiguration serviceRuntimeConfiguration)
{
_runningTasks = new List<Task>();
}
public bool Start(HostControl hostControl)
{
_hostControl = hostControl;
_messageProcessor.Start(); // Starts a System.Threading.Tasks.Task
StartListener(); // starts a System.Threading.Tasks.Task
return true;
}
}
Program.cs:
Host host = HostFactory.New(configurator =>
{
configurator.UseNLog();
// Configure core service
configurator.Service<ServiceCore>(svc =>
{
svc.ConstructUsing(theService => new ServiceCore(_serviceRuntimeConfiguration));
svc.WhenStarted((svc, hostControl) => svc.Start(hostControl));
svc.WhenStopped((svc, hostControl) => svc.Stop(hostControl));
});
// Configure recovery params
configurator.EnableServiceRecovery(recoveryConfigurator =>
{
recoveryConfigurator.RestartService(0);
recoveryConfigurator.OnCrashOnly();
recoveryConfigurator.SetResetPeriod(1);
});
// Execute HostConfigurator
host.Run();
}
The Problem
When I do this:
MyService.exe install --manual --localsystem
The service installs fine, but the command never returns:
Running a transacted installation.
Beginning the Install phase of the installation. Installing service
NotificationEngine.Main... Service NotificationEngine.Main has been
successfully installed.
The Install phase completed successfully, and the Commit phase is
beginning.
The Commit phase completed successfully.
The transacted install has completed.
^C (I have to press CTRL+C)
What should I do for the install command to complete and then return?
NOTE The same behaviour is observable if I run help (i.e. help displays but the command does not return):
MyService.exe help
Generally this means you don't release control of some resource and the process can't cleanly exit. However, this stuff is complicated, so it's hard to say for sure.
A few things I would try
What happens when you execute MyService start after an install/CTRL+C? I'm assuming it also blocks since help does.
Check logging, do you have any enabled? Is there file contention or permissions issues?
What else does your Main() entry point do? Is it doing something that after host.Run()? Your code above makes it looks like you're calling it from within the construction of that object, but I assume it's bad cut-n-pasting.
Make sure you aren't initializing resources before the ConstructUsing and When* callbacks are fired.
After this, I would take this to our mailing list at https://groups.google.com/forum/#!forum/topshelf-discuss.
ServiceCore : ServiceBase
The type T specified in the configurator.Service should subclass ServiceBase.
This fixed the problem for a service that would install fine but hang on the last step of install/uninstall.
As a First step I created Windows Service project configured it properly and
On second Step I have added TopShelf Version 3.1.135.0 in my project If I run my service through (F5 Run) then it is loading Top-shelf Console and service is completed successfully.
However When I am running it to install and Start it from command prompt I am having below TimeOut Error.
Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.Service
Process.TimeoutException: Time out has expired and the operation has not been co
mpleted.
public class AppService
{
LoggingService loggingService = new LoggingService(typeof(AppService).Name);
public void Start()
{
loggingService.Info("SampleService is Started");
ExtractProcess.Start();
TransformProcess.Start();
}
public void Stop()
{
loggingService.Info("SampleService is Stopped");
}
}
-- Updated Code to fix this issue
public void Start()
{
loggingService.Info("MPS.GOA.ETLService is Started");
ThreadStart myThreadDelegate = new ThreadStart(StartService);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();
}
private void StartService()
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000 * ServiceIntervalInMinutes; //1 minute 60000 milliseconds
timer.Enabled = true;
Process();
}
private void Process()
{
ExtractProcess.Start();
TransformProcess.Start();
}
Any Suggestions?
This error is happening because you are running the extract and process methods in the Start method of the service. This is OK in Visual Studio, but when you install the service and start it, the Service Control Manager waits for the Start method to return, and if it does not do so within a certain time (30 seconds by default) then it will return this error.
You have several options, all of which will allow the Start method to return immediately:
Invoke the extract and transform methods on a separate thread
Invoke the extract and transform methods asynchronously
Use a timer to start the extract and transform process
In case you (like me) is struggling to get the service to start - and all you've found so far is references to starting work in a separate thread (and you already did) this might be the solution right here..
My problem was that I had an external JSON config file being read from the project's directory path. What I needed was to get the assembly path, so that when the .NET application is published and installed with Topshelf - it looks for the config file at the right place.
string assemblyPath = Path.GetDirectoryName(typeof(MyConfigManagerClass).Assembly.Location);
var builder = new ConfigurationBuilder()
.SetBasePath(assemblyPath)
.AddJsonFile("config.json", optional: false);
myConfigurationObject = builder.Build();
Topshelf gave an error saying the service couldn't be started, but now I finally know why.
In my case it was neither of the above solutions that solved it, but actual permissions within the topshelf service, that required access to a file that resided in an external server.
TopShelf program running on test server
Log file located on Production server
Test server does not have access to external servers, for security
reasons.
So I changed the program to refer everything internally inside it's own server, and it worked fine.
First time posting long time reader.
I built a working filewatcher inside of a windows forms application functioning 100% properly before moving it to a windows Service and am now recieving two seperate issues. This file watcher reads a flatfile for line updates(lastwrite), deletes/recreates file(streamwriter), and finally parses through a strongly typed data set and then uploads to an SQL server.
(This is my first Windows Service)
Questions:
1. Does the double event trigger in filewatcher effect the service differently then a forms application?
2. Does anyone have an answer about why the thread will break if the class I am calling has no issue?
3. Are there any known issues with Windows Authentication through a windows service?
4. Does anyone have any strong debug methods for windows services?
Here is my code from the windows Service, thanks in advance and my apologies if there is a silly mistake in the code, again first time making a windows service.
FileMonitor m_FileMonitor;
public WindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread myThread = new Thread(DoTheWork);
myThread.Start();
}
catch
{
}
}
void DoTheWork()
{
m_FileMonitor = new FileMonitor(Properties.Settings.Default.PathToFileToWatch, Properties.Settings.Default.PathToErrorLog);
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
For debugging, make sure your project type is Windows Application, and then use this:
[DllImport("kernel32")]
static extern bool AllocConsole();
private static void Main(string[] args)
{
var service = new MyService();
var controller = ServiceController.GetServices().FirstOrDefault(c => c.ServiceName == service.ServiceName);
if (null != controller && controller.Status == ServiceControllerStatus.StartPending)
{
ServiceBase.Run(service);
}
else
{
if (AllocConsole())
{
service.OnStart(args);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
service.OnStop();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
If the code is running because the Windows Service was started, it will run as a Windows Service. Otherwise it will allocate a console, run the service, then wait for a key press before exiting the service. You could build on this for testing pause and continue.
For debugging:
You have to use the ServiceBase.Run method in Main() to execute as a windows service, but you can make a switch in the main method to run the same application as a normal console application (e.g. --standalone). I'm using this on all my services to make them easy to debug.
Regarding the other problems:
I'm not completely sure which problems you encounter and what you mean by "class break" and "double event trigger".
Windows services run under a special service account, which might or might not have permissions to watch the directory you are interested in. You can change the service account or give it permission for the directory if you need to.
Links:
Here is a link to a codeproject article who seems to have implemented a file watcher windows service. Maybe it helps:
http://www.codeproject.com/Articles/18521/How-to-implement-a-simple-filewatcher-Windows-serv
I have the following scenario:
My main Application (APP1) starts a Process (SERVER1). SERVER1 hosts a WCF service via named pipe. I want to connect to this service (from APP1), but sometimes it is not yet ready.
I create the ChannelFactory, open it and let it generate a client. If I now call a method on the generated Client I receive an excpetion whitch tells me that the Enpoint was not found:
var factory = new ChannelFactory<T>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe//localhost/myservice");
factory.Open()
var Client = factory.CreateChannel();
Client.Foo();
If I wait a little bit before calling the service, everything is fine;
var Client = factory.CreateChannel();
Thread.Sleep(2000);
Client.Foo();
How can I ensure, that the Service is ready without having to wait a random amount of time?
If the general case is that you are just waiting for this other service to start up, then you may as well use the approach of having a "Ping" method on your interface that does nothing, and retrying until this starts responding.
We do a similar thing: we try and call a ping method in a loop at startup (1 second between retries), recording in our logs (but ultimately ignoring) any TargetInvocationException that occur trying to reach our service. Once we get the first proper response, we proceed onwards.
Naturally this only covers the startup warmup case - the service could go down after a successfull ping, or it we could get a TargetInvocationException for a reason other than "the service is not ready".
You could have the service signal an event [Edited-see note] once the service host is fully open and the Opened event of the channel listener has fired. The Application would wait on the event before using its proxy.
Note: Using a named event is easy because the .NET type EventWaitHandle gives you everything you need. Using an anonymous event is preferable but a bit more work, since the .NET event wrapper types don't give you an inheritable event handle. But it's still possible if you P/Invoke the Windows DuplicateHandle API yourself to get an inheritable handle, then pass the duplicated handle's value to the child process in its command line arguments.
If you're using .Net 4.0 you could use WS-Discovery to make the service announce its presence via Broadcast IP.
The service could also send a message to a queue (MSMQ binding) with a short lifespan, say a few seconds, which your client can monitor.
Have the service create a signal file, then use a FileSystemWatcher in the client to detect when it gets created.
Just while (!alive) try { alive = client.IsAlive(); } catch { ...reconnect here... } (in your service contract, you just have IsAlive() return true)
I have had the same issue and when using net.pipe*://localhost/serviceName*, I solved it by looking at the process of the self-hosted application.
the way i did that was with a utility class, here is the code.
public static class ServiceLocator
{
public static bool IsWcfStarted()
{
Process[] ProcessList = Process.GetProcesses();
return ProcessList.Any(a => a.ProcessName.StartsWith("MyApplication.Service.Host", StringComparison.Ordinal));
}
public static void StartWcfHost()
{
string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var Process2 = new Process();
var Start2 = new ProcessStartInfo();
Start2.FileName = Path.Combine(path, "Service", "MyApplication.Service.Host.exe");
Process2.StartInfo = Start2;
Process2.Start();
}
}
now, my application isn't called MyApplication but you get my point...
now in my client Apps that use the host i have this call:
if (!ServiceLocator.IsWcfStarted())
{
WriteEventlog("First instance of WCF Client... starting WCF host.")
ServiceLocator.StartWcfHost();
int timeout=0;
while (!ServiceLocator.IsWcfStarted())
{
timeout++;
if(timeout> MAX_RETRY)
{
//show message that probably wcf host is not available, end the client
....
}
}
}
This solved 2 issues,
1. The code errors I had wend away because of the race condition, and 2
2. I know in a controlled manner if the Host crashed due to some issue or misconfiguration.
Hope it helps.
Walter
I attached an event handler to client.InnerChannel.faulted, then reduced the reliableSession to 20 seconds. Within the event handler I removed the existing handler then ran an async method to attempt to connect again and attached the event handler again. Seems to work.