Updating and restarting the current running Windows Service in C# - c#

I have a .NET 6 application compiled as a standalone executable that runs as a Windows service. What I want to add is a way to update and restart the service when it detects that a new version is available. The problem is that I can't find a way to actually restart a service with a single command in a way that can be triggered from C#.
The sc.exe can be used to create, modify, start and stop a service. But it does not have a restart command. My original plan was to modify the service and point it to the new binary, and then restart it using sc.exe, but then I noticed that it doesn't actually have a real restart command.
The Powershell cmdlet Restart-Service does what I want, but the C# Powershell integration seems to have some severe issues and bugs when the C# application is compiled as a standalone executable. It simply does not work at all for me.
I'm triggering the update from the running Windows service itself, so I can't just execute a stop command and then try to execute the start command, as my application won't be running anymore at that point.
One option might be to execute both sc.exe stop and sc.exe start in a way that isn't interrupted when the calling process is stopped, but I'm not sure which method would work reliably here. Another idea would be to slightly misuse the auto-restart on failure mechanism for Windows services. But I'm not sure I can trigger that without creating superfluous error messages in the Windows Event logs.
What options do I have to reliably restart a running Windows service from the running C# application itself?

Related

Starting NodeJS servers as a Windows Service

I want to create a windows service that will "restart" a node server or "run" npm run dev. I currently check that the server is not running by creating sockets to call to the server (localhost:8080), and increment a variable if there's no connection. Once that variable reaches a certain number, then we can assume that the server is no longer running, and that we would have to call npm run dev again.
I also don't want to use things like forever and pm2, though I do think that it should be used, just that it's not allowed..
Any help is greatly appreciated. I researched a lot on this topic, and realized that you can't call any GUI's (including shells) as part of a windows service. Let me know if there are any other alternatives.
Thanks in advance!
Currently, the process I have to 'restart' the server is through a batch script that just calls "CALL npm run dev". I have tried to run a console app in Windows Service. The console app itself work.

What is the best way to keep a C# Console app running [duplicate]

This question already has answers here:
How to keep a .NET console app running?
(9 answers)
Closed 6 years ago.
I have developed a console app which must run in the background. The app must constantly check a database for new records. If new records are returned they are processed. My app as it currently stands uses while(true) to keep the application running. Is using a while loop the best solution.
A snippet of my code:
static void Main(string[] args)
{
while(true)
{
// Query db for new records
if(record_count > 0)
{
// Process the records
}
Thread.Sleep(500);
}
}
Create as Windows Service Application
What a Windows Service is ?
Enables you to create long-running executable applications that run in their own windows session.
Can be automatically started when the computer boots, can be paused and restarted without any user interaction.
Easily installable by running the command line utility InstallUtil.exe and passing the path to the service's executable file.
Why a Windows Service?
One of the most common requirements of some businesses is long-running scheduled jobs based on some time interval. For example: sending a newsletter everyday afternoon or send an email alert to the customer for every one hour.
So building a Windows Service could be one of the reliable solutions to do the goal that can do the required job in the behind the scenes without interfering others users on the same computer.
Please refer the link for step by step implementation -
http://www.c-sharpcorner.com/UploadFile/naresh.avari/develop-and-install-a-windows-service-in-C-Sharp/
Your approach to keep your console application continuously running is absolutely fine. Only thing is that you want to keep it running in background silently without user to know anything. Since a console app has a windowed UI (a command console) the user will keep seeing it. Here is what you can do to get rid of command console. Since you already have your console application with you, here is what you need to do :
Go to project properties -> Go to application Tab -> Change the Output type to Windows Application
Phew! Now your same console application will run without a command console and your code will keep running.
Creating a windows service will be too much of a kill for such a simple logic. Also installing a windows service is an extra overhead, though I am not aware of the deployment you are looking forward to for your application in production.
Better option would be to use Windows service that run in background.
Creating a Windows Service Application
Develop and Install a Windows Service in C#
Just google and you can find lots of article and tutorial on Windows Service.
There is no need to make your program running as a services. Services aren't for these small tasks. You should simply create a Windows (GUI, WinForms) application with a hidden window. Or, just don't create a window and just keep the Main running. Main would launch a thread and would itself wait for that thread.
A service has to be installed as a service and not all users would have permission to do that. It is complex task to have service, manage it, have security attributes settled et. al.
The hidden application can simply run in current user account (the service would be running in high-privilege SYSTEM or NETWORK account). Your application won't demand any privilege from current user - it just need SQL database/table read access.
Create a windows service which will check if your console app is running. If console app is down, then windows service will execute it again.
Don't write your console app's code into windows service. Because if it will start automatically at windows start up, then it may not work correctly as your console app.

c# console app will not run as a scheduled task on specific server

I have a console application that performs some data work and then closes. If I run the executable manually it opens a command prompt, runs the program, and closes. No issues at all regardless of what Microsoft OS I'm using.
However, if I attempt to run the program as a scheduled task it fails on one specific server running Windows Server 2008 R2. It works as a scheduled task just fine on other servers, including another Windows Server 2008 R2 box in the same building. Unfortunately this one server is the server it needs to run on. I've tried adding logging, writing to the event logs, executing the application as an administration, forcing 32 or 64 bit, and launching it as a separate launch from a .bat file. Nothing. The program isn't crashing, it is just never opening.
Does anyone know what may be causing this? I'm at a loss and I don't know what to do.
Edit: I created a test .bat file that just launches a command prompt to see if it would open a command prompt window. It does not. The other tasks seem to run fine though.
Edit #2: I have been researched this and something that has come up is to set the task to enable with desktop. I can't find that option nor can I think of a reason why it would fix this issue but it seems to keep coming up.
After a bit of fiddling around this is what worked for me. When you point to the console application in the actions Tab, ensure that you fill in the 'Start in' field with the location where the executable is located even though it says that it is optional. Once you fill that in, it will work.

windows service working on windows 7 but not on windows server 2003

Solved the problem see the bottom of my post.
So I have a simple windows service that watches a specific folder and upploads files that come into it to a server using a web service.
It's working fine on my machine using windows 7 but when I try to start it on a windows server 2003, I receive an error: Error 1053: the service did not respond to start or control request in a timely fashion. But I get this message after only a few seconds.
I have created the ServicesPipeTimeout and set it to 60000 milliseconds.
I have tried running it from command line using sc query command and found out that the WIN32_EXIT_CODE is 0, which I think means that the service doesn´t even try to start because it find an error before it starts.
In the event viewer I get errors 7000 and 7009.
I am the Administrator on the windows server.
The only thing I haven´t tried is a hotfix I found from microsoft but I don´t want to use it because as I understand it, it is for when the service actually times out.http://support.microsoft.com/kb/886695
I have tried everything I can think of, is there anything that I am missing?
Gísli
EDIT: Re-installed the .NET framework and now I get a new error, Saying that the service controller can not be found.
EDIT: I setup the service with a setup project, not using the installutil command. This is because I need to get user input during the installation and save that in the registry.
EDIT: I have installed the .NET 4.0 framework, it wasn´t possible to install the service with out doing that.
In addition to what I wrote above I have also tried:
Rebooting.
Re-installing.
I have tried to change the permissions on the files that the service needs to access.
Changing permissions in the registry editor.
Edited the code so that the onStart function only starts one thread.
I think it is some kind of permission problem but I don´t have much experience dealing with Windows server.
Solution:
It turned out to be two seperate problems. The .NET framwork had to be repaired and I had to remove the try/catch clause that I had when starting the service. For some reason (unknown to me) the try catch block did something that made it impossible to start the service in a windows server 2003 but it ran fine on windows 7.
It would be very interesting to know why this is.
Thanks for all the help.
Gísli
Have you installed the right version of .NET Framework on the Server 2003 PC? What comes as standard on Windows 7 will need to be installed manually on an older OS.
You say "I have tried everything I can think of". Please edit the question to show what you have already tried so we don't suggest something you have already done.
EDIT:
Try also the Fusion Log viewer. Set it to log failures then start your service. Hit refresh then see if any errors are logged. Double-click a line for more details.
I'd guess that you installed the .NET 3.5 service using .NET 2.0? InstallUtil will work since the CLR is the same, but the service won't start because of .NET 3.5 dependencies.
See Also:
How to install a Windows service developed in .NET 3.5?
In your OnStart code you could wrap everything in a try-catch block and write the exception message and stack trace to a file using something like:
File.WriteAllText(#"C:\Temp\MyServiceLog.txt", exp.Message + exp.StackTrace);
This will help you analyze the problem. Also, I'm using a very simple way of debugging my services: I'm wrapping them in a WinForms wrapper if the session is interactive. For that, I need the following:
A form that creates an instance of the service class
New methods DoStart and DoStop in my service class, which are public and call the protected OnStart and OnStop methods
New code in above form's OnLoad and OnClose handlers, so the DoStart and DoStop methods of the service instance are called accordingly
Then I add the following code to the Main method in Program.cs:
if (Environment.UserInteractive)
{
Application.Run(new FormServiceHoster());
}
else
{
// ... old code to create service instance.
}
This way you're making the "service" run as an application when you just hit F5 in Visual Studio or double click the EXE in the Explorer. When the service is actually run as a service, the Forms-code is ignored.
Usually you can debug services by attaching to the process, however, that doesn't work for debugging the start and stop code. This method helps a great deal debugging the service start and stop code.
You will need to add references to System.Windows.Forms and System.Drawing manually.
This is the point where I bet you wish you had used some logging package like log4net, which might help tell how far your program gets.
Is it possible that the code in the OnStart event is actually taking longer than you expect. If so, you could move that code to a thread, so that the OnStart event finishes (and so Windows reckons the service has started) while your thread continues working.
Are you running the service as admin? If so, that usually rules out permissions issues. (If it still goes wrong, it will rule out the KB 886695 issue as that seems to only apply to local system).
Since you are using .NET 4.0 are you sure that either, the full version is installed, rather than the Client Profile, or that your application works with the client profile?

MessageBox not appearing when process starts when a WCF service calls Process.Start in C#

I want to debug a Windows managed (C++/CLI) process, which's being invoked by a WCF consumed service. It calls process.start on that process, but I am unable to pause that process becuase when its main method gets executed, MessageBox which's placed inside is not executed and prompted, so that after I can attach that process to VS Debugger. If I launch the process manually which's placed on the disk, it gives the message box, or if somehow I start the process with a test stub application which uses Process.Start, message Box appears.
I need to debug the C++/CLI managed process in the context of WCF consumer service written in C#, which actually dispatches the data as remoting objects after starting that process. Is there any way around this?
Regards,
Usman
Maybe messagebox doesn't appear because of WCF service launch it with a different user.
But if you can test your component, why "re-test" it under WCF?
Once you are sure there are not logical errors, all remaining bugs can be solved by properly trace execution ad data in your component and, if necessary, reproduce these errors in your test application.
i don't know c++ but if you have access to the .Net Framework you could just call Debugger.Launch
I was also facing the same issue. It got resolved after checking "Allow Service to interact with desktop" on LogOn property page of the Windows Service

Categories