How can I invoke app on server from ASP.NET web app? - c#

This question could be a can of worms, but I've always wondered if it were possible to invoke an executable application from inside a web application on the web server?
I can easily set this up as a scheduled task to run and check every few minutes, but it would be nice to be able to invoke the application on demand from the a web page.
The site is an ASP.NET 2.0 website using C# and the application is an executable console app written in C#.

You need to start a new process. This is an example how to do it.
Process proc = new Process();
StringBuilder sb = new StringBuilder();
string[] aTarget = target.Split(PATH_SEPERATOR);
string errorMessage;
string outputMessage;
foreach (string parm in parameters)
{
sb.Append(parm + " ");
}
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = sb.ToString();
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : (int)TimeSpan.FromMinutes(timeout).TotalMilliseconds //Per SLaks suggestion. Thanks!
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
A link to MSDN:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.71).aspx
You'll also need to check to make sure that the account the Web application is running under has the appropriate permissions to execute the program.

Process.Start

I think you could do that using the following code.
Process p= new Process();
p.StartInfo.WorkingDirectory = #"C:\whatever";
p.StartInfo.FileName = #"C:\some.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();
where the Process type is from the namespace System.Diagnostics.Process

Related

msinfo32.exe can't collect information on a sharepoint page ASP.net

I am creating a new process on my Sharepoint web application. I've run the same command as below and works on my OS but not on my web app. I wanted to know why and if this is even possible. Here's code that creates the process.
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"report.txt");
Process proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "msinfo32.exe";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.Arguments = "/report " + filePath;
proc.Start();
proc.WaitForExit();
proc.Close();
It creates a file with every filed as Can't collect information, example:
Can't Collect Information
[Hardware Resources]
[Conflicts/Sharing]
Can't Collect Information
[DMA]
Am I doing it wrong, are there settings to enable on sharepoint in order to run msinfo32?
WMI is enabled on my OS.
Found the answer. Sharepoint requires an elevated security state to run this command. Wrapping the code in this helped run msinfo32.exe. Thanks to Amal Hashim and Method Man for recommending this
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Your code goes here
});
I went to the directory where my debug folder is running a console app on my side
here is what I did and it work..
change the name of your Report.txt to out.log open the out.log file and just type anything in it.. save it and close it .. and run the following code below and you will se the SystemInformation window pop up. add this in the Page_Load event to test it
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "out.log");
Process proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "msinfo32.exe";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.Arguments = "/out " + filePath;
proc.Start();
proc.WaitForExit();
proc.Close();
I just tested this from my Page_Load in my web page and it works like a charm.. what you need to add to the header of the webpage that you are launching it from is the following
using System.Diagnostics;
using System.IO;

Run "tf.exe status" in C# and save the result

I´m trying to create a small console app in c#. I want to run the program and save all pending changes in TFS to a .txt file. But I cant get the arguments to work. Can someone help me?
Here is my code i haved done so far:
string argument = "#tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt";
try
{
Process process = new Process();
process.StartInfo.Arguments = "#call" + " " + "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\Tools\\VsDevCmd.bat";
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Verb = "runas";
process.StartInfo.Arguments = argument;
process.StartInfo.CreateNoWindow = false;
process.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
aI'm not really sure that I understand what you're trying to call, exactly.
Let's assume you want to run the following command line from a C# application, as if you would call it from a command line:
tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt"
I would use this code:
string arguments = #"/C tf.exe status /collection:http://tiffany:8080/tfs/ /user:* /format:detailed >c:\\Status\\Detailed.txt";
this.process = new Process();
this.process.StartInfo.FileName = #"cmd.exe";
this.process.StartInfo.Arguments = arguments;
this.process.Start();
Edit:
If that's all your console app does, why not consider creating a batch (.BAT / .CMD) file instead of a C# application?
Instead of running a command line tool you could leverage the TFS API.
There are many articles out there, e.g. Code project article on topic
and
Sample code directly from the MSDN
I suppose you have to read standard error and output from process started:
Process process = new Process();
process.StartInfo.Arguments = #"status PATH /recursive";
process.StartInfo.FileName = "tf.exe";
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
var st = process.StandardOutput.ReadToEnd();
var err = process.StandardError.ReadToEnd();
But parsing tf output is not easy and I'd like to suggest to use TFS API as #Mare said
You do not need to create an application in C # to save in a text file. Just use the parameters (...) > [file name].txt at the end of the command.
The ">" symbol send the result of any command to a file.

Running Phantomjs using C# to grab snapshot of webpage

I'm trying to grab snapshots of my own website using phantomjs - basically, this is to create a "preview image" of user-submitted content.
I've installed phantomjs on the server and have confirmed that running it from the command line against the appropriate pages works fine. However, when I try running it from the website, it does not appear to do anything. I have confirmed that the code is being called, that phantom is actually running (I've monitored the processes, and can see it appear in the process list when I call it) - however, no image is being generated.
I'm not sure where I should be looking to figure out why it won't create the images - any suggestions? The relevant code block is below:
string arguments = "/c rasterize.js http://www.mysite.com/viewcontent.aspx?id=123";
string imagefilename = #"C:\inetpub\vhosts\mysite.com\httpdocs\Uploads\img123.png";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.FileName = #"C:\phantomjs.exe";
p.StartInfo.Arguments = arguments + " " + imagefilename;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
I check the errors that phantomjs throws during its process.
You can read them from Process.StandardError.
var startInfo = new ProcessStartInfo();
//some other parameters here
...
startInfo.RedirectStandardError = true;
var p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit(timeToExit);
//Read the Error:
string error = p.StandardError.ReadToEnd();
It will give you an idea of what happened
The easiest way for executing phantomjs from C# code is using wrapper like NReco.PhantomJS. The following example illustrates how to use it for rasterize.js:
var phantomJS = new PhantomJS();
phantomJS.Run( "rasterize.js", new[] { "https://www.google.com", outFile} );
Wrapper API has events for stdout and stderr; also it can provide input from C# Stream and read stdout result into C# stream.

start process issue

I am using VSTS 2008 + C# + .Net 3.5 to develop a console application. And I want to start an external process (an exe file) from my C# application, and I want current C# application to be blocked until the external process stops and I also want to get the return code of the external process.
Any ideas how to implement this? Appreciate if some sample codes.
using (var process = Process.Start("test.exe"))
{
process.WaitForExit();
var exitCode = process.ExitCode;
}
public static String ShellExec( String pExeFN, String pParams, out int exit_code)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(pExeFN, pParams);
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false; // the process is created directly from the executable file
psi.CreateNoWindow = true;
using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi))
{
string tool_output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
exit_code = p.ExitCode;
return tool_output;
}
}
you'll find all the needed documentation here: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(VS.80).aspx

trying to pass file name from aspx page to console.exe

i want to pass the value of a lable or textbox in an aspx page to a console.exe application
such that the if the value is sample.doc it changes to that.
i am calling from the aspx page with
string f = TextBox1.Text;
System.Diagnostics.Process.Start("C:/DocUpload/ConsoleApplication1.exe", f);
i have tried converting to string then using the string vatiable inplace of sample.doc but no luck
object FileName = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "sample.doc");
any help or ideas will be welcomed.
thank u
You're probably trying to process a file that is in a different folder.
If so, you need to pass the full path of the file, like this:
Process.Start(#"C:\DocUpload\ConsoleApplication1.exe",
Path.Combine(#"C:\path\to\folder", TextBox1.Text));
Here is what I use to start processes from calling applications. Since you are calling it from a web-app you are going to need to make sure you have appropriate permissions.
Process proc = new Process();
StringBuilder sb = new StringBuilder();
string[] aTarget = target.Split(PATH_SEPERATOR);
string errorMessage;
string outputMessage;
foreach (string parm in parameters)
{
sb.Append(parm + " ");
}
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = sb.ToString();
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : (int)TimeSpan.FromMinutes(timeout).TotalMilliseconds
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
A link to MSDN:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx
You'll also need to check to make sure that the account the Web application is running under has the appropriate permissions to execute the program.

Categories