I have the method created in C# (as below) which executes a few npm/newman commands via C# console-app. The current code handles if the cmd hangs/failed, but it does not handle the case if the nmp/newman execution hangs or fail.
Can you please help with this?
public string Runner ()
{
var psiNpm = new ProcessStartInfo
{
FileName = "cmd",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
var pNpmRun = Process.Start(psiNpm);
pNpmRun.StandardInput.WriteLine("npm install -g newman");
pNpmRun.StandardInput.WriteLine("newman run " +
"\"C:\\Postman\\Test.postman.json\" " +
"--folder \"TestSearch\" " +
"--environment \"C:\\Postman\\postman_environment.json\" " +
"--disable-unicode");
pNpmRun.StandardInput.WriteLine("exit");
var tenMin = 10 * 60 * 1000;
if(pNpmRun.WaitForExit(tenMin)) {
return pNpmRun.StandardOutput.ReadToEnd();
} else {
pNpmRun.Kill();
throw new TimeoutException("Command didn't complete in 10 minute timeout");
}
}
You can check the exit code of your npm
and newman
commands and return them to the calling process:
public string Runner ()
{
var psiNpm = new ProcessStartInfo
{
FileName = "cmd",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
var pNpmRun = Process.Start(psiNpm);
pNpmRun.StandardInput.WriteLine("npm install -g newman");
pNpmRun.StandardInput.WriteLine("if not "%ERRORLEVEL%" == "0" exit 1");
pNpmRun.StandardInput.WriteLine("newman run " +
"\"C:\\Postman\\Test.postman.json\" " +
"--folder \"TestSearch\" " +
"--environment \"C:\\Postman\\postman_environment.json\" " +
"--disable-unicode");
pNpmRun.StandardInput.WriteLine("if not "%ERRORLEVEL%" == "0" exit 2");
pNpmRun.StandardInput.WriteLine("exit 0");
var tenMin = 10 * 60 * 1000;
if(pNpmRun.WaitForExit(tenMin)) {
var exitCode = pNpmRun.ExitCode;
if(exitCode != 0) {
throw new Exception("Command failed " + exitCode);
}
return pNpmRun.StandardOutput.ReadToEnd();
} else {
pNpmRun.Kill();
throw new TimeoutException("Command didn't complete in 10 minute timeout");
}
}
After each command check the errorlevel
, which is a "virtual environment variable", representing the exit code of the previous command. If it wasn't 0 (success, usually), then it exits the cmd
process back to your C# code. Your C# code checks the ExitCode
of the process, and if it isn't success (0), it throws an exception containing the ExitCode so you know which of the two commands failed. This relies on the npm
and newman
processes returning a non-zero exit code on failure.
That should handle "failure". Handling "hanging" would be more difficult. There isn't really any way to know if the process is ever going to return (read: halting problem (the one thing I learned at university)).