Running Console application from ASP.NET - c#

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.

Related

How to handle exception in .net Process() while executing the another console in it

I am executing one .net console from another console App.
Eg MyTool.exe < input.txt
Where Input.txt will have all the input required by tool.
The input in the input file should be dyanmic, so to achive this.
I created another wrapper console App MyWrapper.exe.
This is first crating the input.txt file and then calling the MyTool.exe using .Net Process().
Content of batch file
MyTool.exe < input.txt
var proc = new Process();
proc.StartInfo.FileName = "MyBatchFIle.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
Now here is the question.
Say in case of error or incorrect input, there is possibility that MyTool.exe can go to infinite loop.
So I want to detect this kind of error and stop the execution.
My plan is to execute the MyWrapper.exe from Windows scheduler.
Thanks,
Siraj
You could wait for the process to finish + Timeout. If the process did not finished within the timeout, you can kill it:
if(!proc.WaitForExit(timeout))
{
proc.Kill();
}
Another option is to communicate with the process via IPC (e.g. named pipes). But that requires the extension of both tools and increases complexity.
A third option is to communicate via files. For instance: having a status file that can be written by 'MyTool.exe' in format similar to "[process_ID] status". Then the wrapper could read that infomation periodically and kill the process, restart it or whatever is needed.

See the window of a batch file that I start from IIS ASP.NET WebAPI thread

In my project I need to start a batch file from a thread on the server and wait for it to finish. My code is:
var process = new Process();
process.StartInfo.FileName = batchFilePath;
process.StartInfo.Arguments = "-0";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();
and in the batch is simply put "pause".
The problem is that is don't see any window open and the thread is stuck and wait for the batch to finish.Only when I close the process by the windows task manager the program continues. The problem happens also if I put in the batch "cmd". How can I see the window? I want to make sure that the batch is running correctly.
This is a batch file running on the server? And you are not logged into the server, but into a web client?
You won't be able to see the console window from a web client, because it's running on a different machine.
If you are logged into the server, but still aren't seeing the window, you could try researching and experimenting with the ProcessStartInfo properties CreateNoWindow or UseShellExecute.
You might also want to look into RedirectStandardInput and RedirectStandardOutput if you need to see (or inspect programmatically) what the process writes to the console window.

Break out of a C# instantiated batch script to get a shell?

I am attempting to verify the security of an application. The scenario is this:
A C# WinForms application is run by a limited user via Terminal Services (no desktop, just the app). One of the things this C# app can do is execute a batch file that runs a lengthy process with elevated privileges. I am afraid that the limited user may be able to interrupt the batch script (vua Ctrl+C or some other method) and gain access to the underlying elevated shell.
I have tried to do this myself with various combos of Ctrl+C and Ctrl+Break, etc. All I can get is the "Teminate batch job? (Y/N)" prompt, and if you choose terminate, then control is immediately returned to the C# app (which is good). I have not found a way to break this but it seems dangerous to me.
Does anyone know of a way to break out of a C# instantiated batch script and access the underlying shell without returning to the C# app?
No, don't think there is one. But if you're really worried, why not set the CreateNoWindow property on the ProcessStartInfo object you are presumably using to true to prevent user interaction at all?
Not quite an answer to your described scenario but a different way to look at it.
If possible, I would have a "jobs server" who sole responsibility is to run the jobs your Terminal Services-run apps create. Then you would communicate the job (or just it parameters) via WCF to the server. The users would have no access to the server and very little control of the jobs (possibly just a cancel option and success/failure status reports).
You could do something like this (with a Textbox on your app)
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = "/C ping 127.0.0.1";
info.WindowStyle = ProcessWindowStyle.Hidden;
info.CreateNoWindow = true;
info.FileName = "cmd.exe";
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
using (Process process = Process.Start(info))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
textBox1.Text += result;
}
}
Then you can see the results of the batch without the users being able to actually see the window at all, that way it's only visible as a process so they can't interupt it.

What Does No such interface supported Mean

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.

Can I stop an IIS?

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.

Categories

Resources