Create Angular build(ng build) from C# - c#

So I need to make a Angular build (ng build --prod --aot-false) for a C# project(ashx page) with the Angular folder as a part of the project.
What I have tried right now is make a bat file inside the Angular folder outside the "src" folder as follows:
test.bat:
mkdir a
ng build --prod --aot=false
mkdir b
When I execute the commands the directories "a" & "b" are created instantly but the build is never made.
To execute the process I use:
filehandler.ashx:
System.Environment.CurrentDirectory =
context.Server.MapPath("~/ZipFiles/AngularProject_test/AngularProject/");
System.Diagnostics.Process.Start("test.bat");

This thread is a bit old but maybe this will help someone else. The following snippet will run ng build from C#:
// this will be the path to your app
var workingDirectory = #"C:apps\angular-hello-world";
// location of ng command
var command = #"C:\Users\Owner\AppData\Roaming\npm\ng.cmd";
// any arguments you want to pass to ng
var arguments = "build --prod --base-href /helloworld/ --output-path=prod";
var process = new Process();
var currentDirectory = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = workingDirectory;
process.StartInfo.FileName = command;
process.StartInfo.Arguments = arguments;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
// wait for the app to run and grab any output/errors generated
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
var errors = process.StandardError.ReadToEnd();
Console.WriteLine("Output: " + output);
Console.WriteLine("Errors: " + errors);
}
finally
{
Environment.CurrentDirectory = currentDirectory;
}

Related

Show the output of Powershell script in a WPF application

I have a WPF application that executes a Powershell script and then displays a message in a textbox in the application. The Powershell script is executed like this:
string scriptPath = folderPath + "/EXECUTE.ps1";
string powershellPath = #"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
string outputLog = folderPath + "output.log";
bool is64 = IntPtr.Size == 8;
var ENV = "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* "
+ (is64 ? ",HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*" : "")
+ " | Select-Object DisplayName";
ProcessStartInfo startInstall = new ProcessStartInfo(powershellPath, ENV);
startInstall.UseShellExecute = false;
startInstall.Arguments = scriptPath;
startInstall.EnvironmentVariables.Add("RedirectStandardOutput", "true");
startInstall.EnvironmentVariables.Add("RedirectStandardError", "true");
startInstall.EnvironmentVariables.Add("UseShellExecute", "false");
startInstall.EnvironmentVariables.Add("CreateNoWindow", "true");
Process Install = Process.Start(startInstall);
Install.Close();
Console.WriteLine("Script executed successfully");
Console.WriteLine("Output available at: " + outputLog);
The last two lines in Console.WriteLine are printed out in a textbox. I was wondering, is there a way that I can show the output of the Powershell terminal window inside of this textbox named txtboxExecutionResult? I am not executing any Powershell command from my application, just starting and executing the EXECUTE.ps1 file from the application. I'd really appreciate any help to point me in some direction.
I had a similar issue once with reading output from another application and I solved it by reading the standard output of the process.
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "example.exe";
process.StartInfo.Arguments = args;
process.Start();
output = await process.StandardOutput.ReadToEndAsync();

How to get the cmd.exe output as a string in C#?

I tried to get the output of passed argument in the cmd.exe via c# code. But when the code string outw = cmd.StandardOutput.ReadToEnd().ToString(); executing takes more and more time. Here my command prompt arguments work perfectly.
Here is my code
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("git init && git remote add gitlab https://gitlab.company.com/test2.git && git push gitlab --delete branchname");
cmd.StandardInput.WriteLine("git remote remove gitlab");
string outw = cmd.StandardOutput.ReadToEnd().ToString();//Here my code strucks
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Where I made the mistake? I waited for more than 30 min but I did not get the output in the string outw. How could I get the output test as a string in string outw?

Run Bash Commands from Mono C#

I am trying to make a directory using this code to see if the code is executing but for some reason it executes with no error but the directory is never made. Is there and error in my code somewhere?
var startInfo = new
var startinfo = new ProcessStartInfo();
startinfo.WorkingDirectory = "/home";
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
Console.WriteLine ("Shell has been executed!");
Console.ReadLine();
This works best for me because now I do not have to worry about escaping quotes etc...
using System;
using System.Diagnostics;
class HelloWorld
{
static void Main()
{
// lets say we want to run this command:
// t=$(echo 'this is a test'); echo "$t" | grep -o 'is a'
var output = ExecuteBashCommand("t=$(echo 'this is a test'); echo \"$t\" | grep -o 'is a'");
// output the result
Console.WriteLine(output);
}
static string ExecuteBashCommand(string command)
{
// according to: https://stackoverflow.com/a/15262019/637142
// thans to this we will pass everything as one command
command = command.Replace("\"","\"\"");
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = "-c \""+ command + "\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
}
This works for me:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
My guess is that your working directory is not where you expect it to be.
See here for more information on the working directory of Process.Start()
also your command seems wrong, use && to execute multiple commands:
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
Thirdly you are setting your working directory wrongly:
proc.StartInfo.WorkingDirectory = "/home";

Running batch file containing NuGet commands from C#

I have a batch file containing the following commands:
cd C:\myfolder
NuGet Update -self
NuGet pack mypackage.nuspec
myfolder contains mypackage.nuspec and NuGet.exe. I try to run this command with C# using the following function:
private static int ExecuteCommand(string path)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
ProcessInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
// *** Read the streams ***
string output = Process.StandardOutput.ReadToEnd();
string error = Process.StandardError.ReadToEnd();
int ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
However, my commands are not executed. What is causing this behavior and what is the solution? Those strings will probably be used in the future, I'll update my question then (just to prevent chriticism :)).
This is the final version of the function:
private static ShellCommandReturn ExecuteCommand(string path)
{
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo(path);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
processInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
int exitCode = process.ExitCode;
process.Close();
return new ShellCommandReturn { Error = error, ExitCode = exitCode, Output = output };
}
ShellCommandReturn is a simple custom class with a few data members where error, output and exit code of a shell command are stored.
Thanks.
EDIT: After a certain amount of collaboration :)
The problem is that this is executing in the context of a web application, which doesn't have the same environment variables set.
Apparently setting:
startInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true"
(using the naming of my final code below) fixes the problem.
Old answer (still worth reading)
Look at this code:
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = true;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
Process = Process.Start(path);
You're creating a ProcessStartInfo, but then completely ignoring it. You should be passing it into Process.Start. You should also rename your variables. Conventionally local variables start with lower case in C#. Additionally, it's a good idea to initialize variables at the point of first use, where possible. Oh, and import namespaces so you don't fully qualified names such as System.IO.FileInfo in your code. Finally, object initializers are useful for classes like ProcessStartInfo:
var startInfo = new ProcessStartInfo(path) {
CreateNoWindow = false,
UseShellExecute = true,
WorkingDirectory = new FileInfo(path).DirectoryName;
};
var process = Process.Start(startInfo);

Execute command line using C#

All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.

Categories

Resources