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.
Related
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?
I am developing an app that should be portable and I am using mongodb.
By portable I means that my app has a folder with all: dlls, exes, mongo files, mongo databases. Then with this folder I can run my app in any machine.
Then I need to know:
Is there some library that allow me to run the mongod process when the app start and end
the process when the app ends ?
Exists a good practice to do that stuff ?
Advices are welcome and thanks in advance.
According to the MongoDb installation instructions it should be quite simple.
Mongodb starts as a console application waiting for connections, so when your app starts, you should run mongodb hidden. We are always assuming that ALL the mongodb files are in place with your application files and database files are in the correct directory).
When your app terminates, you should kill the process.
Yo should set the correct paths on this example:
//starting the mongod server (when app starts)
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = dir + #"\mongod.exe";
start.WindowStyle = ProcessWindowStyle.Hidden;
start.Arguments = "--dbpath d:\test\mongodb\data";
Process mongod = Process.Start(start);
//stopping the mongod server (when app is closing)
mongod.Kill();
You can see more information about the mongod configuration and running here
I needed to do the same thing and my starting point was Salvador Sarpi's answer. But, I found a couple things that needed to be added to his example.
First, you need to set UseShellExecute to false for the ProcessStartInfo object. Otherwise, you may get a security warning when the process is started asking the user if they want to run it or not. I don't think this is desired.
Second, you need to call Shutdown on the MongoServer object before killing the process. I had an issue where it locked the database and required it to be repaired if I didn't call the Shutdown method before killing the process. See Here for details on repairing
My final code is different, but for this example I used Salvador's code as the base for reference.
//starting the mongod server (when app starts)
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = dir + #"\mongod.exe";
start.WindowStyle = ProcessWindowStyle.Hidden;
// set UseShellExecute to false
start.UseShellExecute = false;
//#"" prevents need for backslashes
start.Arguments = #"--dbpath d:\test\mongodb\data";
Process mongod = Process.Start(start);
// Mongo CSharp Driver Code (see Mongo docs)
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase database = server.GetDatabase("Database_Name_Here");
// Doing awesome stuff here ...
// Shutdown Server when done.
server.Shutdown();
//stopping the mongod server (when app is closing)
mongod.Kill();
I am getting an exception on my server side code, which is serving up a silverlight app,
Win32Exception - No such interface supported
Our server side C# code starts up a separate process for a short task because of a third party dll not being thread safe. So the error above occurs in part of the code like this,
Process process = new Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "PreviewGenerator.exe");
process.StartInfo = processStartInfo;
process.Start(); // THIS IS WHERE THE EXCEPTION OCCURS
process.WaitForExit();
The PreviewGenerator.exe process does not start when it is not working, the exception occurs where the comment is above.
UPDATE:
I have run process monitor on the IIS server when the issue occurs. This shows that the w3wp process does this,
Thread Create
Access the file PreviewGenerator.exe
Hive unloaded (this is the registry)
Thread Exit
And it does this before calling the other process. If I compare this with a the process monitor log when it is working it does this,
Thread Create
Access the file PreviewGenerator.exe
Process Start
Does heaps of stuff with PreviewGenerator.exe including reading / writing / registry, etc.
Process Exit
Hive unloaded
Thread Exit
But process monitor does not show any information as to why the first case doesn't work.
Is there a way I can see why the thread exits prematurely?
Also I think this problem relates to when my server is being loaded up more, and much more memory is being used. How can I prove this?
I had a similar issue, I used
processStartInfo.UseShellExecute = false;
and that fixed it for me.
http://www.progtown.com/topic31343-process-start-processstartinfo-startinfo.html
I found the best thing to do was to create a separate app pool for my application in IIS and set an upper limit for the amount of RAM it could use. Also I found it useful to turn on the 'Generate Recycle Event Log Entry' items under the app pool settings.
You can then go to the system event log and filter out the items with a source of 'WAS' to understand what is going on in the app pools, when they are restarting and when they stop from being idle etc.
I think the main problem in our case is that the IIS box was running out of memory. Tuning the app pools and adding some extra RAM seems to have solved it.
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.
I want to know how to run my console application from ASP.NET, which is in one solution.
I want to run and stop the application.
On a client machine or on the server ?
if you are thinking client machine there is no way !
anyway this is how you do it on the application's server
Var process = new Process();
process.StartInfo.FileName = "Notepad.exe";//in your case full path with the application name
process.StartInfo.Arguments = " ";//arguments
process.Start();
// Do your magic here
process.Kill();//Dont forget to kill it when you are done
Just start it like you'd start any normal EXE.
var proc = Process.Start(#"C:\myconsole.exe");
You should place the console EXE file at a proper place though.
And you can end it with:
proc.Kill();
...
Note: that starting the process on a single request might not be a good idea. It might be better to start it on another thread and lets it spin so you can response to your users faster.