I need to control a Windows service (slave) from another one (master) on the same machine (Windows 7 or Server 2008). It's unable to either start or stop the service. What do I need to do to be control the service? The master service is written in C#
UPDATE:
The master service is meant to be a sort of watchdog - it monitors an HTTP connection to the slave and restarts the slave if the slave is non-responsive (not returning any HTTP data).
You can have the master service create a new process that creates a hidden command window with an argument that causes it to call the windows command and start or stop the service. We use this model all the time at my job, the /C will cause the command window to exit as soon as the service finishes changing state.
System.Diagnostics.Process p = new System.Diagnostics.Process ();
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo ( "cmd.exe", "/C net [start or stop] [service name]");
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo = psi;
P.Start();
You will need to replace the bracketed sections of the command, and sorry if there are any syntax errors I am typing this on my tablet.
The best way to handle windows services is to use System.ServiceProcess namespace. Check it on:
https://ourcodeworld.com/articles/read/363/how-to-start-stop-and-verify-if-a-service-exists-with-c-in-winforms
But you will have some problems trying that because you will need administrator permissions to turn other services off, so you can handle that by following this link (for debug purposes you can open your VS as admin and everything will work):
How do I force my .NET application to run as administrator?
Related
I have a web API project that has a call that allows the user to basically start a separate application on the server.
Basically my web API is a gateway to remotely call this application from an MVC project.
Problem:
The problem I am facing is that the Process.Start() method is working perfectly (as in I can see the process starting on the server's task manager) but no window is popping up? I can run the application directly and see it start in its own window.
Web API Code:
public void ReconnectEPLAN()
{
if (CheckEplanConnection() == false)
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = #"C:\Program Files\EPLAN\Pro Panel\2.8.3\Bin\W3u.exe"; //works but no ui poopup
process.StartInfo.CreateNoWindow = false;
process.Start();
}
}
What can I do to force the started process's app window to appear as well?
On your server, IIS runs as a service (unlike IIS Express, which runs in the user space).
Since Windows Vista, services can no longer interact with the user's desktop directly.
See:
How to run console application from Windows Service?
https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/f8f91e8f-5954-43a7-8bc4-80ed2ff1e3b1/quotallow-service-to-interact-with-desktopquot-does-not-work-on-vista?forum=windowssdk
https://www.codeproject.com/Questions/1239551/Why-does-process-start-goes-to-background-when-sta
Services cannot interact directly with the user at all: this is because services can run on a machine that doesn't have a user logged in at all, so there is no way to interact with them.
A requirement has arisen that I need to start a Node.js server from a C# application, this is as simple as running a server.js script within the Node.js console. However, I'm not entirely certain how exactly to achieve that.
Here's what I've looked into so far:
In the Node.js installation, there's a file called C:\Program Files (x86)\nodejs\nodevars.bat, this is the command prompt window for Node.js. To start the server, I could possibly be using the following steps:
Execute the nodevars.bat file.
SendKeys to the new process console window to start the server.
This approach feels a bit fragile. There's no guarantee that the target user will have their Node.js installation in the same place, also sending keys to a process may not be an ideal solution.
Another method could be:
Write a batch file that executes nodevars.bat.
Execute the batch file from the C# application.
This seems like a better approach. However, the only problem here is that the nodevars.bat opens in a new console window.
So to the question(s), is there a way I can start a node.js server script using functionality built into the node.js installation? Perhaps sending arguments to the node.exe?
If it is to serve multiple users, i.e. as a server, then you can use the os-service package, and install a Windows service. You can then start and stop the service using the standard API.
If you are to start the server as a "single purpose" server, i.e. to serve only the current user, then os-service is the wrong approach. (Typically when using this approach you will specify a unique port for the service to use, which will only be used by your application).
To start a batch file or other Console application, from C#, without showing a console window, use the standard method, but be sure to specify:
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false; // This is important
psi.CreateNoWindow = true; // This is what hides the command window.
psi.FileName = #"c:\Path\to\your\batchfile.cmd";
psi.Arguments = #"-any -arguments -go Here"; // Probably you will pass the port number here
using(var process = Process.Start(psi)){
// Do something with process if you want.
}
There are a few different ones but I recommend the os-service package.
I have a self hosted wcf service that is using legacy c++ code via dll import and pinvoke. There are some instances in the old code where exceptions arise from the functions (that were handled in the old app, but not in the service) and when they occur my service is stopping. The exceptions are rare; however, I do not want my service just randomly stopping as a result of a crash in another assembly. The exceptions are not bubbling up to the service so I cannot try/catch them in the service. Is there a way to automatically have the service restart on crash?
It is self hosted, not through IIS.
Thanks in advance!!
On the machine where the service is running, you can open up the Services management console (start > run > services.msc). Find your service, right-click it and choose Properties. In the popup, click on the Recovery tab. Set First, Second, and Subsequent failures all to Restart the Service.
If you are using WIX to install your project, you can also set these properties using the util:ServiceConfig element.
If you're using a standard ServiceInstaller, these options aren't built in. I'd recommend having a look at the ServiceInstaller Extension class which exposes properties through a standard service installer interface.
Well I'm assuming that you are creating a Windows Service project for what you are doing. Go into your ProjectInstaller and find the "AfterInstall" method. Here you will need to add code to execute a command on the Service Controller to set recovery options. Unfortunatly, even though .NET has a ServiceController you will need to execute the command through a process start.
using (var process = new Process())
{
var startInfo = process.StartInfo;
startInfo.FileName = "sc";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
// tell Windows that the service should restart if it fails
startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);
process.Start();
process.WaitForExit();
exitCode = process.ExitCode;
process.Close();
}
Note: I stole this code from another question
I need to call a console application to load data into another desktop application on the remote server that located within the corporate domain.
Users will enter the web page and upload data to asp.net web server, which after transformation should call that console application. Users are located remotely and do not have any other access except the web server.
I decided to lower the security web application context and let the asp.net working process to start the console application on the current IIS 6.0 web server
What I have done:
I changed the security account for the application pool for Local System;
I added ASPNET Account and IIS_WPG IIS Process Account to Administrators group;
I added “Allow service to interact with desctop” for “IIS Admin Service” and “World Wide Web Publishing Service” processes and restarted the machine;
I tried to start BAT-file at server side through the test page code-behind, but failed:
protected void btnStart_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = #”C:\run.bat”;
process.StartInfo.UseShellExecute = false;
process.Start();
process.WaitForExit();
}
The error was access denied.
Please help me to find any workable idea how to start the bat-file at web server side.
Thanks
Try setting UseShellExecute to true instead of false. After all, batch files run in a shell - so you need a shell to execute it. (Another option is to run cmd.exe and pass the name of the batch file in as an argument, e.g. "cmd.exe /k c:\run.bat")
You might also want to try creating a simple .NET app which just (say) creates a file with a timestamp in. That way you can test the "can I start another process" bit separately from the "can I get the batch file to work" bit.
Put that particular batch file in your application itself.
string str_Path = Server.MapPath(".") + "\\run.bat";
ProcessStartInfo processInfo = new ProcessStartInfo(str_Path);
processInfo.UseShellExecute = false;
Process batchProcess = new Process();
batchProcess.StartInfo = processInfo;
batchProcess.Start();
Take a look at this example: Run Interactive Command Shell or Batch Files From ASP.NET
It uses little different approach. They suggest running cmd.exe and executing command line by line.
In a .NET windows application to to modify a remote machine config file that is used by an ASP.NET application. However, I keep getting the error:
System.IO.IOException: The process cannot access the file '[file name]' because it is being used by another process.
Now, this may not be the problem, but I'm figuring that if I can stop the IIS, then I can modify the machine config file (without getting the exception), and then I can restart the IIS using this code:
Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "iisreset";
proc.StartInfo.Arguments = serverName;
try
{
proc.Start();
proc.WaitForExit();
...
1) Is there a way to stop the IIS without restarting it, and 2) Doe this approach to changing the server.config file even make sense?
(note, I am modifying the file with regular expressions search and replace; is this a problem?)
You should be able to do something like this. I don't have windows, so I can't check the exact name of the service, but I think it is "IISADMIN" or "w3svc". Remember this should be the service name and not the display name you see in the service control panel.
ServiceController controller = new ServiceController();
controller.MachineName = "."; // or the remote machine name
controller.ServiceName = "IISADMIN"; // or "w3svc"
string status = controller.Status.ToString();
// Stop the service
controller.Stop();
// Start the service
controller.Start();
You can also use
net stop w3svc
or
net stop IISADMIN
from the commandline or in your process in your code
Strange. A .config file should not be locked exclusively.
But to answer your question, you can also use the net command for this:
net stop w3svc
to stop the www service, and
net start w3svc
to start it again.
You can also do this programmatically as described by #monkeyp
Note that I would advice against this and first try to determine (and resolve) the cause of the lock as described by #RichardOD.
Using System.Diagnostics;
//to stop ISS
ProcessStartInfo startInfo = new ProcessStartInfo("iisreset.exe", " /stop");
System.Diagnostics.Process.Start(startInfo);
//to start ISS
ProcessStartInfo stopInfo = new ProcessStartInfo("iisreset.exe", " /start");
System.Diagnostics.Process.Start(stopInfo);
You can use the IISRESET /STOP command.
If you type IISRESET /? you will get a list of other available options.
[Edit: Pass the "/STOP" switch as the arguments property on the process' startinfo object.]
Should be "iisreset /STOP" to stop the services, then "iisreset /START" to restart them.
Use a tool like wholockme or unlocker to find the root cause of the locking.
Update- another option is to use Process Explorer (thanks fretje)- this is a good option as lots of developers have this utility on their PC.
You can often just recycle or stop/start the Application Pool IIS is running, rather than restarting IIS altogether.