System.Diagnostics.Process.BeginErrorReadLine()

Here are the examples of the csharp api System.Diagnostics.Process.BeginErrorReadLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

538 Examples 7

19 View Source File : SysProxyHandle.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private static void ExecSysproxy(string arguments)
        {
            // using event to avoid hanging when redirect standard output/error
            // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
            // and http://blog.csdn.net/zhangweixing0/article/details/7356841
            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                using (Process process = new Process())
                {
                    // Configure the process using the StartInfo properties.
                    process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
                    process.StartInfo.Arguments = arguments;
                    process.StartInfo.WorkingDirectory = Utils.GetTempPath();
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;

                    // Need to provide encoding info, or output/error strings we got will be wrong.
                    process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
                    process.StartInfo.StandardErrorEncoding = Encoding.Unicode;

                    process.StartInfo.CreateNoWindow = true;

                    StringBuilder output = new StringBuilder();
                    StringBuilder error = new StringBuilder();

                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            output.AppendLine(e.Data);
                        }
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };
                    try
                    {
                        process.Start();

                        process.BeginErrorReadLine();
                        process.BeginOutputReadLine();

                        process.WaitForExit();
                    }
                    catch (System.ComponentModel.Win32Exception e)
                    {

                        // log the arguments
                        throw new Exception(process.StartInfo.Arguments);
                    }
                    string stderr = error.ToString();
                    string stdout = output.ToString();

                    int exitCode = process.ExitCode;
                    if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
                    {
                        throw new Exception(stderr);
                    }

                    //if (arguments == "query")
                    //{
                    //    if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
                    //    {
                    //        throw new Exception("failed to query wininet settings");
                    //    }
                    //    _queryStr = stdout;
                    //}
                }
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {
            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {

            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

19 View Source File : ProcessExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<ProcessResult> StartProcessAsync(this Process process, ProcessStartInfo startInfo, bool showDebug = false, CancellationToken cancellationToken = default)
        {
            Debug.replacedert(!startInfo.UseShellExecute, "Process Start Info must not use shell execution.");
            Debug.replacedert(startInfo.RedirectStandardOutput, "Process Start Info must redirect standard output.");
            Debug.replacedert(startInfo.RedirectStandardError, "Process Start Info must redirect standard errors.");

            process.StartInfo = startInfo;
            process.EnableRaisingEvents = true;

            var processResult = new TaskCompletionSource<ProcessResult>();
            var errorCodeResult = new TaskCompletionSource<string[]>();
            var errorList = new List<string>();
            var outputCodeResult = new TaskCompletionSource<string[]>();
            var outputList = new List<string>();

            process.Exited += OnProcessExited;
            process.ErrorDataReceived += OnErrorDataReceived;
            process.OutputDataReceived += OnOutputDataReceived;

            async void OnProcessExited(object sender, EventArgs args)
            {
                processResult.TrySetResult(new ProcessResult(process.ExitCode, await errorCodeResult.Task, await outputCodeResult.Task));
                process.Close();
                process.Dispose();
            }

            void OnErrorDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    errorList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.LogError(args.Data);
                }
                else
                {
                    errorCodeResult.TrySetResult(errorList.ToArray());
                }
            }

            void OnOutputDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    outputList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.Log(args.Data);
                }
                else
                {
                    outputCodeResult.TrySetResult(outputList.ToArray());
                }
            }

            if (!process.Start())
            {
                if (showDebug)
                {
                    UnityEngine.Debug.LogError("Failed to start process!");
                }

                processResult.TrySetResult(new ProcessResult(process.ExitCode, new[] { "Failed to start process!" }, null));
            }
            else
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                CancellationWatcher(process);
            }

            async void CancellationWatcher(Process _process)
            {
                await Task.Run(() =>
                {
                    try
                    {
                        while (!_process.HasExited)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                _process.Kill();
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                });
            }

            return await processResult.Task;
        }

19 View Source File : OVRPlatformTool.cs
License : MIT License
Project Creator : absurd-joy

static void Command(TargetPlatform targetPlatform, string dataPath, string uploadCommand)
		{
			string platformUtilPath = CheckForPlatformUtil(dataPath);

			activeProcess = true;
			InitializePlatformUtilProcess(platformUtilPath, uploadCommand);

			ovrPlatUtilProcess.Exited += new EventHandler(
				(s, e) =>
				{
					activeProcess = false;
				}
			);

			ovrPlatUtilProcess.OutputDataReceived += new DataReceivedEventHandler(
				(s, e) =>
				{
					if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b"))
					{
						OVRPlatformTool.log += e.Data + "\n";
					}
				}
			);
			ovrPlatUtilProcess.ErrorDataReceived += new DataReceivedEventHandler(
				(s, e) =>
				{
					OVRPlatformTool.log += e.Data + "\n";
				}
			);

			try
			{
				ovrPlatUtilProcess.Start();
				ovrPlatUtilProcess.BeginOutputReadLine();
				ovrPlatUtilProcess.BeginErrorReadLine();
			}
			catch
			{
				if (ThrowPlatformUtilStartupError(platformUtilPath))
				{
					Command(targetPlatform, dataPath, uploadCommand);
				}
			}
		}

19 View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy

public Process RunCommandAsync(string[] arguments, DataReceivedEventHandler outputDataRecievedHandler)
	{
		if (!isReady)
		{
			Debug.LogWarning("OVRADBTool not ready");
			return null;
		}

		string args = string.Join(" ", arguments);

		ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
		startInfo.WorkingDirectory = androidSdkRoot;
		startInfo.CreateNoWindow = true;
		startInfo.UseShellExecute = false;
		startInfo.WindowStyle = ProcessWindowStyle.Hidden;
		startInfo.RedirectStandardOutput = true;
		startInfo.RedirectStandardError = true;

		Process process = Process.Start(startInfo);
		if (outputDataRecievedHandler != null)
		{
			process.OutputDataReceived += new DataReceivedEventHandler(outputDataRecievedHandler);
		}

		process.BeginOutputReadLine();
		process.BeginErrorReadLine();

		return process;
	}

19 View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy

public int RunCommand(string[] arguments, WaitingProcessToExitCallback waitingProcessToExitCallback, out string outputString, out string errorString)
	{
		int exitCode = -1;

		if (!isReady)
		{
			Debug.LogWarning("OVRADBTool not ready");
			outputString = string.Empty;
			errorString = "OVRADBTool not ready";
			return exitCode;
		}

		string args = string.Join(" ", arguments);

		ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
		startInfo.WorkingDirectory = androidSdkRoot;
		startInfo.CreateNoWindow = true;
		startInfo.UseShellExecute = false;
		startInfo.WindowStyle = ProcessWindowStyle.Hidden;
		startInfo.RedirectStandardOutput = true;
		startInfo.RedirectStandardError = true;

		outputStringBuilder = new StringBuilder("");
		errorStringBuilder = new StringBuilder("");

		Process process = Process.Start(startInfo);
		process.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedHandler);
		process.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceivedHandler);

		process.BeginOutputReadLine();
		process.BeginErrorReadLine();

		try
		{
			do
			{
				if (waitingProcessToExitCallback != null)
				{
					waitingProcessToExitCallback();
				}
			} while (!process.WaitForExit(100));

			process.WaitForExit();
		}
		catch (Exception e)
		{
			Debug.LogWarningFormat("[OVRADBTool.RunCommand] exception {0}", e.Message);
		}

		exitCode = process.ExitCode;

		process.Close();

		outputString = outputStringBuilder.ToString();
		errorString = errorStringBuilder.ToString();

		outputStringBuilder = null;
		errorStringBuilder = null;

		if (!string.IsNullOrEmpty(errorString))
		{
			if (errorString.Contains("Warning"))
			{
				UnityEngine.Debug.LogWarning("OVRADBTool " + errorString);
			}
			else
			{
				UnityEngine.Debug.LogError("OVRADBTool " + errorString);
			}
		}

		return exitCode;
	}

19 View Source File : RunnerService.cs
License : MIT License
Project Creator : actions

protected override void OnStart(string[] args)
        {
            RunningLoop = Task.Run(
                () =>
                    {
                        try
                        {
                            bool stopping;
                            WriteInfo("Starting Actions Runner Service");
                            TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);

                            lock (ServiceLock)
                            {
                                stopping = Stopping;
                            }

                            while (!stopping)
                            {
                                WriteInfo("Starting Actions Runner listener");
                                lock (ServiceLock)
                                {
                                    RunnerListener = CreateRunnerListener();
                                    RunnerListener.OutputDataReceived += RunnerListener_OutputDataReceived;
                                    RunnerListener.ErrorDataReceived += RunnerListener_ErrorDataReceived;
                                    RunnerListener.Start();
                                    RunnerListener.BeginOutputReadLine();
                                    RunnerListener.BeginErrorReadLine();
                                }

                                RunnerListener.WaitForExit();
                                int exitCode = RunnerListener.ExitCode;

                                // exit code 0 and 1 need stop service
                                // exit code 2 and 3 need restart runner
                                switch (exitCode)
                                {
                                    case 0:
                                        Stopping = true;
                                        WriteInfo(Resource.RunnerExitWithoutError);
                                        break;
                                    case 1:
                                        Stopping = true;
                                        WriteInfo(Resource.RunnerExitWithTerminatedError);
                                        break;
                                    case 2:
                                        WriteInfo(Resource.RunnerExitWithError);
                                        break;
                                    case 3:
                                        WriteInfo(Resource.RunnerUpdateInProcess);
                                        var updateResult = HandleRunnerUpdate();
                                        if (updateResult == RunnerUpdateResult.Succeed)
                                        {
                                            WriteInfo(Resource.RunnerUpdateSucceed);
                                        }
                                        else if (updateResult == RunnerUpdateResult.Failed)
                                        {
                                            WriteInfo(Resource.RunnerUpdateFailed);
                                            Stopping = true;
                                        }
                                        else if (updateResult == RunnerUpdateResult.SucceedNeedRestart)
                                        {
                                            WriteInfo(Resource.RunnerUpdateRestartNeeded);
                                            _restart = true;
                                            ExitCode = int.MaxValue;
                                            Stop();
                                        }
                                        break;
                                    default:
                                        WriteInfo(Resource.RunnerExitWithUndefinedReturnCode);
                                        break;
                                }

                                if (Stopping)
                                {
                                    ExitCode = exitCode;
                                    Stop();
                                }
                                else
                                {
                                    // wait for few seconds before restarting the process
                                    Thread.Sleep(timeBetweenRetries);
                                }

                                lock (ServiceLock)
                                {
                                    RunnerListener.OutputDataReceived -= RunnerListener_OutputDataReceived;
                                    RunnerListener.ErrorDataReceived -= RunnerListener_ErrorDataReceived;
                                    RunnerListener.Dispose();
                                    RunnerListener = null;
                                    stopping = Stopping;
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            WriteException(exception);
                            ExitCode = 99;
                            Stop();
                        }
                    });
        }

19 View Source File : CLangCompiler.cs
License : MIT License
Project Creator : adamant

public int Compile(
            ICompilerOutput output,
            string[] sourceFiles,
            string[] headerSearchPaths,
            string outputPath)
        {
            // used to have: -Wno-incompatible-pointer-types
            var options = "-std=c11 -fsanitize=undefined -fsanitize=integer -fsanitize=nullability -Wall -Wno-unused-label";
            // Next thing is needed for windows
            options += " -Xclang -flto-visibility-public-std";
            if (Path.GetExtension(outputPath) == ".dll") // TODO take this as an argument or something
                options += " --shared";
            var sources = string.Join(' ', sourceFiles);
            var headers = string.Join(' ', headerSearchPaths.Select(h => "--include-directory " + h));
            var arguments = $"{sources} -o {outputPath} {headers} {options}";
            output.WriteLine("clang arguments:");
            output.WriteLine(arguments);
            var startInfo = new ProcessStartInfo("clang", arguments)
            {
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
            };
            var process = new Process() { StartInfo = startInfo };
            // To prevent blocking on a full buffer, we have to process output as it happens
            process.OutputDataReceived += ProcessOutput;
            process.ErrorDataReceived += ProcessOutput;
            output.WriteLine("clang output:");
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            return process.ExitCode;

            void ProcessOutput(object s, DataReceivedEventArgs e)
            {
                output.WriteLine(e.Data);
            }
        }

19 View Source File : LogCatWindow.cs
License : MIT License
Project Creator : adrenak

void OnGUI() {
            GUILayout.BeginHorizontal();

            // Enable pre-filter if process is not started
            GUI.enabled = logCatProcess == null;
            prefilterOnlyUnity = GUILayout.Toggle(prefilterOnlyUnity, "Only Unity", "Button", GUILayout.Width(80));

            // Enable button if process is not started
            GUI.enabled = logCatProcess == null;
            if (GUILayout.Button("Start", GUILayout.Width(60))) {
                // Start `adb logcat -c` to clear the log buffer
                ProcessStartInfo clearProcessInfo = new ProcessStartInfo();
                clearProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
                clearProcessInfo.CreateNoWindow = true;
                clearProcessInfo.UseShellExecute = false;
                clearProcessInfo.FileName = EditorPrefs.GetString("AndroidSdkRoot") + "/platform-tools/adb";
                clearProcessInfo.Arguments = @"logcat -c";
                Process.Start(clearProcessInfo);

                // Start `adb logcat` (with additional optional arguments) process for filtering
                ProcessStartInfo logProcessInfo = new ProcessStartInfo();
                logProcessInfo.CreateNoWindow = true;
                logProcessInfo.UseShellExecute = false;
                logProcessInfo.RedirectStandardOutput = true;
                logProcessInfo.RedirectStandardError = true;
                logProcessInfo.FileName = EditorPrefs.GetString("AndroidSdkRoot") + "/platform-tools/adb";
                logProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;

                // Add additional -s argument for filtering by Unity tag.
                logProcessInfo.Arguments = "logcat" + (prefilterOnlyUnity ? " -s  \"Unity\"" : "");

                logCatProcess = Process.Start(logProcessInfo);

                logCatProcess.ErrorDataReceived += (sender, errorLine) => {
                    if (errorLine.Data != null && errorLine.Data.Length > 2)
                        AddLog(new LogCatLog(errorLine.Data));
                };
                logCatProcess.OutputDataReceived += (sender, outputLine) => {
                    if (outputLine.Data != null && outputLine.Data.Length > 2)
                        AddLog(new LogCatLog(outputLine.Data));
                };
                logCatProcess.BeginErrorReadLine();
                logCatProcess.BeginOutputReadLine();
            }

            // Disable button if process is already started
            GUI.enabled = logCatProcess != null;
            if (GUILayout.Button("Stop", GUILayout.Width(60))) {
                try {
                    logCatProcess.Kill();
                }
                catch (InvalidOperationException ex) {
                    // Just ignore it.
                }
                finally {
                    logCatProcess = null;

                }
            }

            GUI.enabled = true;
            if (GUILayout.Button("Clear", GUILayout.Width(60))) {
                lock (logsList) {
                    logsList.Clear();
                    filteredList.Clear();
                }
            }

            GUILayout.Label(filteredList.Count + " matching logs", GUILayout.Height(20));

            // Create filters
            filterByString = GUILayout.TextField(filterByString, GUILayout.Height(20));
            GUI.color = new Color(0.75f, 0.5f, 0.5f, 1f);
            filterOnlyError = GUILayout.Toggle(filterOnlyError, "Error", "Button", GUILayout.Width(80));
            GUI.color = new Color(0.95f, 0.95f, 0.3f, 1f);
            filterOnlyWarning = GUILayout.Toggle(filterOnlyWarning, "Warning", "Button", GUILayout.Width(80));
            GUI.color = new Color(0.5f, 0.5f, 0.75f, 1f);
            filterOnlyDebug = GUILayout.Toggle(filterOnlyDebug, "Debug", "Button", GUILayout.Width(80));
            GUI.color = new Color(0.5f, 0.75f, 0.5f, 1f);
            filterOnlyInfo = GUILayout.Toggle(filterOnlyInfo, "Info", "Button", GUILayout.Width(80));
            GUI.color = Color.white;
            filterOnlyVerbose = GUILayout.Toggle(filterOnlyVerbose, "Verbose", "Button", GUILayout.Width(80));

            GUILayout.EndHorizontal();

            GUIStyle lineStyle = new GUIStyle();
            lineStyle.normal.background = MakeTexture(600, 1, new Color(1.0f, 1.0f, 1.0f, 0.1f));

            scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(Screen.height - 45));

            // Show only top `showingLimit` log entries
            int fromIndex = filteredList.Count - showLimit;
            if (fromIndex < 0)
                fromIndex = 0;

            for (int i = fromIndex; i < filteredList.Count; i++) {
                LogCatLog log = filteredList[i];
                GUI.backgroundColor = log.GetBgColor();
                GUILayout.BeginHorizontal(lineStyle);
                GUILayout.Label(log.CreationDate + " | " + log.Message);
                GUILayout.EndHorizontal();
            }

            GUILayout.EndScrollView();
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr

public async void carmdrm()
        {
            statuslbl.Content = "Converting File...";

            Extract("OSAC", AppDomain.CurrentDomain.BaseDirectory + "\\res", "res", "ffmpeg.exe");

            string ffdir = AppDomain.CurrentDomain.BaseDirectory + "\\res\\ffmpeg.exe";
            string arg = @"-y -activation_bytes ";
            string arg1 = @" -i ";
            string arg2 = @" -ab ";
            string arg3 = @"k -map_metadata 0 -id3v2_version 3 -vn ";
            string fileout = Path.Combine(outputdisplay.Text, Path.GetFileNameWithoutExtension(inputdisplay.Text) + GetOutExtension());
            string arguments = arg + abytes + arg1 + inputdisplay.Text + arg2 + qlabel.Content + arg3 + fileout;

            Process ffm = new Process();
            ffm.StartInfo.FileName = ffdir;
            ffm.StartInfo.Arguments = arguments;
            ffm.StartInfo.CreateNoWindow = true;
            ffm.StartInfo.RedirectStandardError = true;
            ffm.StartInfo.UseShellExecute = false;
            ffm.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            ffm.EnableRaisingEvents = true;
            Console.SetOut(new TextBoxWriter(txtConsole));
            ffm.ErrorDataReceived += (s, ea) =>
            {
                Console.WriteLine($"{ea.Data}");
            };

            scrolltimer.Tick += new EventHandler(scrolltimer_Tick);
            scrolltimer.Interval = new TimeSpan(0, 0, 1);

            ffm.Start();

            ffm.BeginErrorReadLine();
            scrolltimer.Start();

            await Task.Run(() => ffm.WaitForExit());

            ffm.Close();

            inpbutton.IsEnabled = true;

            convertbutton.IsEnabled = true;

            scrolltimer.Stop();
            scrolltimer.Tick -= new EventHandler(scrolltimer_Tick);

            enrb();
            enbslst();

            statuslbl.Content = "Conversion Complete!";

            stopbar();

            Directory.Delete(resdir, true);
        }

19 View Source File : TestFramework.cs
License : MIT License
Project Creator : adrianoc

public static void Execute(string executable, string args)
        {
            var processInfo = new ProcessStartInfo(executable, args);
            processInfo.CreateNoWindow = true;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;
            processInfo.UseShellExecute = false;

            var process = Process.Start(processInfo);

            var err = new StringBuilder();
            var @out = new StringBuilder();

            process.ErrorDataReceived += (sender, arg) => err.AppendLine(arg.Data);
            process.OutputDataReceived += (sender, arg) => @out.AppendLine(arg.Data);

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.EnableRaisingEvents = true;
            process.WaitForExit();

            if (!string.IsNullOrWhiteSpace(@out.ToString()))
            {
                Console.WriteLine($"{Environment.NewLine}Output: {@out}");
            }
            
            if (!string.IsNullOrWhiteSpace(err.ToString()))
            {
                throw new ApplicationException("Error: " + err + $"{Environment.NewLine}Executable: {executable}");
            }
        }

19 View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6

private Boolean runProcess(string filename, string arguments)
        {
            this.outputText.Text += "\nExecuting " + filename + arguments + "\n";

            ProcessStartInfo sInfo = new ProcessStartInfo();
            sInfo.FileName = filename;
            sInfo.Arguments = arguments;
            sInfo.WorkingDirectory = Path.Combine(nxDir, "import");
            sInfo.RedirectStandardOutput = true;
            sInfo.RedirectStandardError = true;
            sInfo.UseShellExecute = false;
            sInfo.CreateNoWindow = true;

            Process process = new Process();
            process.StartInfo = sInfo;
            processes.Add(process);

            process.OutputDataReceived += new DataReceivedEventHandler((s, e) =>
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    this.outputText.Text += e.Data + "\n";
                }));
            });

            process.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    this.outputText.Text += e.Data + "\n";
                }));
            });

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            while (!process.HasExited)
            {
                Application.DoEvents();
            }

            processes.Remove(process);
            
            if (process.ExitCode > 0)
            {
                return true;
            }

            process.Close();

            return false;
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

private Task<int> RunProcessAsync(Process process, int OwnerTab, string ScriptName)
        {
            var tcs = new TaskCompletionSource<int>();

            // Process Exited
            process.Exited += (s, ea) =>
            {
                RemoveTaskFromTasksList(process.Id, true);
                tcs.SetResult(process.ExitCode);
                AddTextToConsole("<br><span style=\"color:yellow;\">Task finished!</span><br>", OwnerTab);
                AddTextToEventsList("Task " + process.StartInfo.Arguments.Replace("-File ", "") + " finished", true);
                ScrollToBottomListBox(EventsList, true);
            };

            // Process Output data received
            process.OutputDataReceived += (s, ea) => {
                AddTextToConsole(ea.Data, OwnerTab); 
            };

            // Process Error output received
            process.ErrorDataReceived += (s, ea) => {

                if (ea.Data != null)
                {
                    if (ea.Data != "")
                    {
                        AddTextToConsole("<span style=\"color:red;\">Error: " + ea.Data + "</span>", OwnerTab);
                        AddTextToEventsList("Task " + process.StartInfo.Arguments.Replace("-File ", "") + " failed", true);
                    }
                }
            };

            // Start the process
            bool started = process.Start();
            if (!started)
            {
                throw new InvalidOperationException("Could not start process: " + process);
            }

            // Add to tasks list
            AddTaskToTasksList(process.Id, ScriptName.Split("\\")[ScriptName.Split("\\").Length - 1]);

            // Begin to read data from the output
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }

19 View Source File : PowershellStarter.cs
License : MIT License
Project Creator : AlexAsplund

protected override void OnStart(string[] args)
        {

            string ScriptPath = ConfigurationManager.AppSettings["ScriptPath"];
            string ScriptParameters = ConfigurationManager.AppSettings["ScriptParameters"];
            
            // Define process startinfo

            process.CreateNoWindow = true;
            process.UseShellExecute = false;
            process.WorkingDirectory = ConfigurationManager.AppSettings["WorkingDirectory"];
            process.RedirectStandardOutput = true;
            process.RedirectStandardError = true;
            process.FileName = "C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe";
            process.Arguments = "-ExecutionPolicy Unrestricted -File " + ScriptPath + " " + ScriptParameters;

            // Define process error/output event handling and start it.

            
            PSProcess.StartInfo = process;
            PSProcess.EnableRaisingEvents = true;
            PSProcess.Exited += new System.EventHandler(onScriptExited);
            
            PSProcess.OutputDataReceived += (sender, EventArgs) => eventLog1.WriteEntry(EventArgs.Data);
            PSProcess.ErrorDataReceived += (sender, EventArgs) => eventLog1.WriteEntry(EventArgs.Data);
            PSProcess.Start();

            // Begin*ReadLine must be set after process has executed.

            PSProcess.BeginOutputReadLine();
            PSProcess.BeginErrorReadLine();

            eventLog1.WriteEntry("PowershellStarter Started powershell service with scriptpath:" + ScriptPath + " and parameter: " + ScriptParameters);

            


        }

19 View Source File : Guard.cs
License : MIT License
Project Creator : AmazingDM

protected bool StartInstanceAuto(string argument, ProcessPriorityClreplaced priority = ProcessPriorityClreplaced.Normal)
        {
            State = State.Starting;
            try
            {
                // 初始化程序
                InitInstance(argument);
                Instance.EnableRaisingEvents = true;
                if (RedirectStd)
                {
                    // 清理日志
                    _logPath ??= Path.Combine(Global.NetchDir, $"logging\\{Name}.log");
                    if (File.Exists(_logPath))
                        File.Delete(_logPath);

                    Instance.OutputDataReceived += OnOutputDataReceived;
                    Instance.ErrorDataReceived += OnOutputDataReceived;
                }

                Instance.Exited += OnExited;

                // 启动程序
                Instance.Start();
                if (priority != ProcessPriorityClreplaced.Normal)
                    Instance.PriorityClreplaced = priority;
                if (!RedirectStd) return true;
                // 启动日志重定向
                Instance.BeginOutputReadLine();
                Instance.BeginErrorReadLine();
                SaveBufferTimer.Elapsed += SaveBufferTimerEvent;
                SaveBufferTimer.Enabled = true;
                if (StartedKeywords.Count == 0) return true;
                // 等待启动
                for (var i = 0; i < 1000; i++)
                {
                    Thread.Sleep(10);
                    switch (State)
                    {
                        case State.Started:
                            return true;
                        case State.Stopped:
                            Logging.Error($"{Name} 控制器启动失败");
                            Stop();
                            return false;
                    }
                }

                Logging.Error($"{Name} 控制器启动超时");
                Stop();
                return false;
            }
            catch (Exception e)
            {
                Logging.Error($"{Name} 控制器启动失败:\n {e}");
                return false;
            }
        }

19 View Source File : InstantPreviewManager.cs
License : Apache License 2.0
Project Creator : andijakl

private static void RunAdbCommand(string fileName, string arguments, out string output, out string errors)
        {
            using (var process = new System.Diagnostics.Process())
            {
                var startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardError = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;

                var outputBuilder = new StringBuilder();
                var errorBuilder = new StringBuilder();
                process.OutputDataReceived += (sender, ef) => outputBuilder.Append(ef.Data);
                process.ErrorDataReceived += (sender, ef) => errorBuilder.Append(ef.Data);

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.Close();

                // Trims the output strings to make comparison easier.
                output = outputBuilder.ToString().Trim();
                errors = errorBuilder.ToString().Trim();
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : anydream

public static void RunCommand(
			string program,
			string arguments,
			string workDir,
			Action<string> onOutput,
			Action<string> onError,
			bool isWait = true)
		{
			if (program == null)
			{
				program = "cmd";
				arguments = "/c " + arguments;
			}

			if (IsPrintCommand)
			{
				string cmd = string.Format("> {0} {1}", program, arguments);
				Console.WriteLine(cmd);
			}

			var si = new ProcessStartInfo
			{
				WorkingDirectory = workDir,
				FileName = program,
				Arguments = arguments,
				CreateNoWindow = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				UseShellExecute = false
			};
			// 此环境变量会破坏 clang 定位到正确的头文件目录
			si.EnvironmentVariables.Remove("VCInstallDir");

			Process pSpawn = new Process
			{
				StartInfo = si
			};

			if (onOutput != null)
			{
				pSpawn.OutputDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onOutput(args.Data);
				};
			}
			if (onError != null)
			{
				pSpawn.ErrorDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onError(args.Data);
				};
			}

			pSpawn.Start();

			if (onOutput != null)
				pSpawn.BeginOutputReadLine();

			if (onError != null)
				pSpawn.BeginErrorReadLine();

			if (isWait)
				pSpawn.WaitForExit();
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : anydream

private static void RunCommand(
			string program,
			string arguments,
			string workDir,
			Action<string> onOutput,
			Action<string> onError,
			bool isWait = true)
		{
			if (program == null)
			{
				program = "cmd";
				arguments = "/c " + arguments;
			}

			var si = new ProcessStartInfo
			{
				WorkingDirectory = workDir,
				FileName = program,
				Arguments = arguments,
				CreateNoWindow = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				UseShellExecute = false
			};
			// 此环境变量会破坏 clang 定位到正确的头文件目录
			si.EnvironmentVariables.Remove("VCInstallDir");

			Process pSpawn = new Process
			{
				StartInfo = si
			};

			if (onOutput != null)
			{
				pSpawn.OutputDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onOutput(args.Data);
				};
			}
			if (onError != null)
			{
				pSpawn.ErrorDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onError(args.Data);
				};
			}

			pSpawn.Start();

			if (onOutput != null)
				pSpawn.BeginOutputReadLine();

			if (onError != null)
				pSpawn.BeginErrorReadLine();

			if (isWait)
				pSpawn.WaitForExit();
		}

19 View Source File : ShellHelper.cs
License : MIT License
Project Creator : ashishgopalhattimare

public static void RunCommand(string fileName, string arguments, out string output, out string error)
        {
            using (var process = new System.Diagnostics.Process())
            {
                var startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardError = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;

                var outputBuilder = new StringBuilder();
                var errorBuilder = new StringBuilder();
                process.OutputDataReceived += (sender, ef) => outputBuilder.AppendLine(ef.Data);
                process.ErrorDataReceived += (sender, ef) => errorBuilder.AppendLine(ef.Data);

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.Close();

                // Trims the output strings to make comparison easier.
                output = outputBuilder.ToString().Trim();
                error = errorBuilder.ToString().Trim();
            }
        }

19 View Source File : BotProcess.cs
License : GNU General Public License v3.0
Project Creator : asimmon

public void Start()
        {
            try
            {
                this._process.Start();
            }
            catch (Exception ex)
            {
                this._messages.CompleteAdding();
                throw new Exception($"Failed to start the process '{this._command}'", ex);
            }

            this._process.BeginOutputReadLine();
            this._process.BeginErrorReadLine();
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : Asixa

public bool init()
        {
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.RedirectStandardOutput = true;    
            psi.RedirectStandardInput = true;           
            psi.RedirectStandardError = true;
            psi.FileName = "Tools/Steamcmd/builder/steamcmd.exe";               
            psi.UseShellExecute = false;                  
            psi.CreateNoWindow = true;

            cmd = Process.Start(psi);                 
            cmd.OutputDataReceived +=DataReceived;
            cmd.ErrorDataReceived += DataReceived;
            cmd.BeginErrorReadLine();
            cmd.BeginOutputReadLine();

            return true;
        }

19 View Source File : AddInActivatorProcess.cs
License : MIT License
Project Creator : askguanyu

[EnvironmentPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
        public void Start()
        {
            this.CheckDisposed();

            this.DisposeClient();

            string guid = Guid.NewGuid().ToString();
            bool isCreated;

            using (EventWaitHandle serverStartedHandle = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format(AddInActivatorHost.AddInDomainEventNameStringFormat, guid), out isCreated))
            {
                if (!isCreated)
                {
                    throw new Exception(AddInConstants.EventHandleAlreadyExistedException);
                }

                string addInDomainreplacedemblyPath = typeof(AddInActivatorProcess).replacedembly.Location;

                AddInDomainSetup.WriteSetupFile(this._addInDomainSetup, this._addInDomainSetupFile);

                //// args[0] = AddInDomain replacedembly path
                //// args[1] = GUID
                //// args[2] = PID
                //// args[3] = AddInDomainSetup file
                //// args[4] = Redirect output or not

                this._process.StartInfo.Arguments = string.Format("\"{0}\" {1} {2} \"{3}\" {4}", addInDomainreplacedemblyPath, guid, Process.GetCurrentProcess().Id.ToString(), this._addInDomainSetupFile, this._redirectOutput.ToString());
                this.IsRunning = this._process.Start();

                if (!this.IsRunning)
                {
                    Debug.WriteLine(string.Format(AddInConstants.ProcessStartExceptionStringFormat, this._process.StartInfo.FileName));
                    throw new Exception(string.Format(AddInConstants.ProcessStartExceptionStringFormat, this._process.StartInfo.FileName));
                }

                if (!serverStartedHandle.WaitOne(this._addInDomainSetup.ProcessStartTimeout))
                {
                    Debug.WriteLine(AddInConstants.ProcessStartTimeoutException);
                    throw new Exception(AddInConstants.ProcessStartTimeoutException);
                }

                this._process.BeginOutputReadLine();
                this._process.BeginErrorReadLine();
                this._process.PriorityClreplaced = this._addInDomainSetup.ProcessPriority;
                this._addInActivatorClient = new AddInActivatorClient(guid, this._addInDomainSetup);
                this.RaiseEvent(this.Attached);
            }
        }

19 View Source File : TestBase.cs
License : Apache License 2.0
Project Creator : aspnet

private int RunWebServerSystemWeb(string applicationName, string configFileName, bool https)
        {
            var tcs = new TaskCompletionSource<object>();

            int port = GetAvailablePort(https);

            string sourceDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            string targetDirectory = BuildTargetDirectory(
                sourceDirectory,
                configFileName,
                applicationName,
                https ? "https" : "http",
                port);

            Directory.SetCurrentDirectory(targetDirectory);

            string targetHostConfig = Path.Combine(targetDirectory, "ApplicationHost.config");

            string programFile32 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            string iisExpressExe = Path.Combine(programFile32, "IIS Express", "iisexpress.exe");

            var info = new ProcessStartInfo
            {
                WorkingDirectory = targetDirectory,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                ErrorDialog = false,
                CreateNoWindow = false,
                FileName = iisExpressExe,
                Arguments = "/config:\"" + targetHostConfig + "\" /trace:error",
            };

            // Log.Debug("Executing {0}", Definition.Command);
            Process process = Process.Start(info);

            process.OutputDataReceived += OutputDataReceived;
            process.ErrorDataReceived += OutputDataReceived;
            process.Exited += (a, b) => tcs.TrySetResult(null);
            process.EnableRaisingEvents = true;

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            _disposing.Token.Register(() =>
            {
                tcs.Task.Wait(250);
                if (!process.HasExited)
                {
                    process.Kill();
                    tcs.Task.Wait();
                }
                try
                {
                    Directory.Delete(targetDirectory, true);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Cleanup error {0}", ex.Message));
                }
            });

            // Wait for the server to get started.
            Thread.Sleep(1000);

            return port;
        }

19 View Source File : ProcessHost.cs
License : GNU General Public License v3.0
Project Creator : audiamus

protected string runProcess (
      string exePath, string parameters, 
      bool getStdErrorNotOutput = false,
      DataReceivedEventHandler eventHandler = null) 
    {

      if (!File.Exists (exePath))
        return null;

      string result = String.Empty;
      bool async = eventHandler != null;

      using (Process p = new Process ()) {
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.FileName = exePath;
        p.StartInfo.Arguments = parameters;

        if (getStdErrorNotOutput)
          p.StartInfo.RedirectStandardError = true;
        else
          p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardInput = true;

        if (async) {
          if (getStdErrorNotOutput)
            p.ErrorDataReceived += eventHandler;
          else
            p.OutputDataReceived += eventHandler;
        }

        var processOutputStringBuilder = new StringBuilder ();

        p.Start ();
        p.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

        Singleton<ProcessList>.Instance.Add (p);
        Process = p;

        if (async) {
          if (getStdErrorNotOutput)
            p.BeginErrorReadLine ();
          else
            p.BeginOutputReadLine ();
        }
        p.WaitForExit ();

        Singleton<ProcessList>.Instance.Remove (p);
        Process = null;

        if (!async) {
          if (getStdErrorNotOutput)
            result = p.StandardError.ReadToEnd ();
          else
            result = p.StandardOutput.ReadToEnd ();
        } else {
          if (processOutputStringBuilder.Length > 0)
            result = processOutputStringBuilder.ToString ();
        }

      }

      return result;
    }

19 View Source File : ProcessProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

private static void ExecutePostProcessStartActions(bool redirectStandard, bool redirectError, Process process)
        {
            // capturing standard output only starts if you call BeginOutputReadLine
            if (redirectStandard)
            {
                process.BeginOutputReadLine();
            }

            // capturing error output only starts if you call BeginErrorReadLine
            if (redirectError)
            {
                process.BeginErrorReadLine();
            }
        }

19 View Source File : ProcessProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

private void ExecutePostProcessStartActions(bool redirectStandard, bool redirectError, Process process)
        {
            // capturing standard output only starts if you call BeginOutputReadLine
            if (redirectStandard)
            {
                process.BeginOutputReadLine();
            }

            // capturing error output only starts if you call BeginErrorReadLine
            if (redirectError)
            {
                process.BeginErrorReadLine();
            }
        }

19 View Source File : ProcessExecutingGitCommander.cs
License : MIT License
Project Creator : awaescher

protected virtual string Start(Api.Git.Repository repository, string[] command, Action<ProcessStartInfo> initialize)
		{
			var timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;

			var psi = new ProcessStartInfo();

			psi.FileName = "git";
			psi.WorkingDirectory = repository.Path;
			SetArguments(psi, command);
			psi.CreateNoWindow = true;
			psi.UseShellExecute = false;
			psi.EnvironmentVariables["GIT_PAGER"] = "cat";
			RedirectStderr(psi);
			initialize(psi);

			var output = new StringBuilder();
			var error = new StringBuilder();

			using (var outputWaitHandle = new AutoResetEvent(initialState: false))
			using (var errorWaitHandle = new AutoResetEvent(initialState: false))
			using (var process = new Process())
			{
				process.StartInfo = psi;

				process.OutputDataReceived += (sender, e) =>
				{
					if (e.Data == null)
					{
						try
						{
							outputWaitHandle.Set();
						}
						catch (ObjectDisposedException)
						{
							// if the wait handle was disposed,
							// we can ignore the call to .Set()
						}
					}
					else
					{
						output.AppendLine(e.Data);
					}
				};

				process.ErrorDataReceived += (sender, e) =>
				{
					if (e.Data == null)
					{
						try
						{
							errorWaitHandle.Set();
						}
						catch (ObjectDisposedException)
						{
							// if the wait handle was disposed,
							// we can ignore the call to .Set()
						}
					}
					else
					{
						error.AppendLine(e.Data);
					}
				};

				try
				{
					process.Start();
					process.BeginOutputReadLine();
					process.BeginErrorReadLine();

					if (process.WaitForExit(timeout) &&
						outputWaitHandle.WaitOne(timeout) &&
						errorWaitHandle.WaitOne(timeout))
					{
						// Process completed. Check process.ExitCode here.
						return output.ToString();
					}

					// Timed out.
					return error?.ToString() ?? "Unknown error";
				}
				finally
				{
					if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
						throw new GitCommandException("Command did not terminate.");
					if (process.ExitCode != 0)
						throw new GitCommandException(string.Format("Command exited with error code: {0}\n{1}", process.ExitCode, error?.ToString() ?? "Unknown error"));
				}
			}
		}

19 View Source File : AbstractCLIWrapper.cs
License : Apache License 2.0
Project Creator : aws

protected int ExecuteCommand(ProcessStartInfo startInfo, string loggerLabel)
        {


            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                _logger?.WriteLine($"... {loggerLabel}: " + e.Data);
            });

            int exitCode;
            using (var proc = new Process())
            {
                proc.StartInfo = startInfo;
                proc.Start();

                if(startInfo.RedirectStandardOutput)
                {
                    proc.ErrorDataReceived += handler;
                    proc.OutputDataReceived += handler;
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();

                    proc.EnableRaisingEvents = true;
                }

                proc.WaitForExit();

                exitCode = proc.ExitCode;
            }

            return exitCode;
        }

19 View Source File : Utilities.cs
License : Apache License 2.0
Project Creator : aws

private static void BundleWithZipCLI(string zipCLI, string zipArchivePath, string publishLocation, IToolLogger logger)
        {
            var args = new StringBuilder("\"" + zipArchivePath + "\"");

            var allFiles = GetFilesToIncludeInArchive(publishLocation);
            foreach (var kvp in allFiles)
            {
                args.AppendFormat(" \"{0}\"", kvp.Key);
            }

            var psiZip = new ProcessStartInfo
            {
                FileName = zipCLI,
                Arguments = args.ToString(),
                WorkingDirectory = publishLocation,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                logger?.WriteLine("... zipping: " + e.Data);
            });

            using (var proc = new Process())
            {
                proc.StartInfo = psiZip;
                proc.Start();

                proc.ErrorDataReceived += handler;
                proc.OutputDataReceived += handler;
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();

                proc.EnableRaisingEvents = true;
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath));
                }
            }
        }

19 View Source File : Utilities.cs
License : Apache License 2.0
Project Creator : aws

public static ExecuteShellCommandResult ExecuteShellCommand(string workingDirectory, string process, string arguments)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = process,
                Arguments = arguments,
                WorkingDirectory = workingDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };


            StringBuilder capturedOutput = new StringBuilder();
            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                capturedOutput.AppendLine(e.Data);
            });            
            
            using (var proc = new Process())
            {
                proc.StartInfo = startInfo;
                proc.Start();

                if (startInfo.RedirectStandardOutput)
                {
                    proc.ErrorDataReceived += handler;
                    proc.OutputDataReceived += handler;
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();

                    proc.EnableRaisingEvents = true;
                }

                proc.WaitForExit();
                return new ExecuteShellCommandResult(proc.ExitCode, capturedOutput.ToString());
            }            
        }

19 View Source File : LambdaDotNetCLIWrapper.cs
License : Apache License 2.0
Project Creator : aws

public int Publish(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string configuration, string msbuildParameters, string architecture, IList<string> publishManifests)
        {
            if(outputLocation == null)
                throw new ArgumentNullException(nameof(outputLocation));
            
            if (Directory.Exists(outputLocation))
            {
                try
                {
                    Directory.Delete(outputLocation, true);
                    _logger?.WriteLine("Deleted previous publish folder");
                }
                catch (Exception e)
                {
                    _logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}");
                }
            }

            _logger?.WriteLine($"... invoking 'dotnet publish', working folder '{outputLocation}'");

            var dotnetCLI = FindExecutableInPath("dotnet.exe");
            if (dotnetCLI == null)
                dotnetCLI = FindExecutableInPath("dotnet");
            if (string.IsNullOrEmpty(dotnetCLI))
                throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH.");

            var fullProjectLocation = this._workingDirectory;
            if (!string.IsNullOrEmpty(projectLocation))
            {
                fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation);
            }

            StringBuilder arguments = new StringBuilder("publish");
            if (!string.IsNullOrEmpty(projectLocation))
            {
                arguments.Append($" \"{fullProjectLocation}\"");
            }
            if (!string.IsNullOrEmpty(outputLocation))
            {
                arguments.Append($" --output \"{outputLocation}\"");
            }

            if (!string.IsNullOrEmpty(configuration))
            {
                arguments.Append($" --configuration \"{configuration}\"");
            }

            if (!string.IsNullOrEmpty(targetFramework))
            {
                arguments.Append($" --framework \"{targetFramework}\"");
            }

            if (!string.IsNullOrEmpty(msbuildParameters))
            {
                arguments.Append($" {msbuildParameters}");
            }

            if (!string.Equals("netcoreapp1.0", targetFramework, StringComparison.OrdinalIgnoreCase))
            {
                arguments.Append(" /p:GenerateRuntimeConfigurationFiles=true");

                // Define an action to set the runtime and self-contained switches.
                var applyRuntimeSwitchAction = (Action)(() =>
                {
                    if (msbuildParameters == null ||
                        msbuildParameters.IndexOf("--runtime", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        arguments.Append($" --runtime {LambdaUtilities.DetermineRuntimeParameter(targetFramework, architecture)}");
                    }

                    if (msbuildParameters == null ||
                        msbuildParameters.IndexOf("--self-contained", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        arguments.Append(" --self-contained false ");
                    }

                });

                // This is here to not change existing behavior for the 2.0 and 2.1 runtimes. For those runtimes if
                // cshtml files are being used we need to support that cshtml being compiled at runtime. In order to do that we
                // need to not turn PreserveCompilationContext which provides reference replacedemblies to the runtime
                // compilation and not set a runtime.
                //
                // If there are no cshtml then disable PreserveCompilationContext to reduce package size and continue
                // to use the same runtime identifier that we used when those runtimes were launched.
                if (new string[] { "netcoreapp2.0", "netcoreapp2.1" }.Contains(targetFramework))
                {
                    if(Directory.GetFiles(fullProjectLocation, "*.cshtml", SearchOption.AllDirectories).Length == 0)
                    {
                        applyRuntimeSwitchAction();

                        if (string.IsNullOrEmpty(msbuildParameters) ||
                            !msbuildParameters.Contains("PreserveCompilationContext"))
                        {
                            _logger?.WriteLine("... Disabling compilation context to reduce package size. If compilation context is needed preplaced in the \"/p:PreserveCompilationContext=false\" switch.");
                            arguments.Append(" /p:PreserveCompilationContext=false");
                        }
                    }
                }
                else
                {
                    applyRuntimeSwitchAction();
                }

                // If we have a manifest of packages already deploy in target deployment environment then write it to disk and add the 
                // command line switch
                if(publishManifests != null && publishManifests.Count > 0)
                {
                    foreach(var manifest in publishManifests)
                    {
                        arguments.Append($" --manifest \"{manifest}\"");
                    }                    
                }
            }

            // echo the full dotnet command for debug
            _logger?.WriteLine($"... dotnet {arguments}");

            var psi = new ProcessStartInfo
            {
                FileName = dotnetCLI,
                Arguments = arguments.ToString(),
                WorkingDirectory = this._workingDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                _logger?.WriteLine("... publish: " + e.Data);
            });

            int exitCode;
            using (var proc = new Process())
            {
                proc.StartInfo = psi;
                proc.Start();


                proc.ErrorDataReceived += handler;
                proc.OutputDataReceived += handler;
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();

                proc.EnableRaisingEvents = true;

                proc.WaitForExit();

                exitCode = proc.ExitCode;
            }

            if (exitCode == 0)
            {
                ProcessAdditionalFiles(defaults, outputLocation);

                var chmodPath = FindExecutableInPath("chmod");
                if (!string.IsNullOrEmpty(chmodPath) && File.Exists(chmodPath))
                {
                    // as we are not invoking through a shell, which would handle
                    // wildcard expansion for us, we need to invoke per-file
                    var files = Directory.GetFiles(outputLocation, "*", SearchOption.TopDirectoryOnly);
                    foreach (var file in files)
                    {
                        var filename = Path.GetFileName(file);
                        var psiChmod = new ProcessStartInfo
                        {
                            FileName = chmodPath,
                            Arguments = "+rx \"" + filename + "\"",
                            WorkingDirectory = outputLocation,
                            RedirectStandardOutput = true,
                            RedirectStandardError = true,
                            UseShellExecute = false,
                            CreateNoWindow = true
                        };

                        using (var proc = new Process())
                        {
                            proc.StartInfo = psiChmod;
                            proc.Start();

                            proc.ErrorDataReceived += handler;
                            proc.OutputDataReceived += handler;
                            proc.BeginOutputReadLine();
                            proc.BeginErrorReadLine();

                            proc.EnableRaisingEvents = true;
                            proc.WaitForExit();

                            if (proc.ExitCode == 0)
                            {
                                this._logger?.WriteLine($"Changed permissions on published file (chmod +rx {filename}).");
                            }
                        }
                    }
                }
            }

            return exitCode;
        }

19 View Source File : LambdaPackager.cs
License : Apache License 2.0
Project Creator : aws

private static void BundleWithBuildLambdaZip(string zipArchivePath, string rootDirectory, IDictionary<string, string> includedFiles, IToolLogger logger)
        {               
            if (!File.Exists(BuildLambdaZipCliPath))
            {
                throw new LambdaToolsException("Failed to find the \"build-lambda-zip\" utility. This program is required to maintain Linux file permissions in the zip archive.", LambdaToolsException.LambdaErrorCode.FailedToFindZipProgram);
            }
            
            EnsureBootstrapLinuxLineEndings(rootDirectory, includedFiles);
                        
            //Write the files to disk to avoid the command line size limit when we have a large number of files to zip.            
            var inputFilename = zipArchivePath + ".txt";
            using(var writer = new StreamWriter(inputFilename))
            {                            
                foreach (var kvp in includedFiles)
                {
                    writer.WriteLine(kvp.Key);                    
                }
            }

            var args = new StringBuilder($"-o \"{zipArchivePath}\" -i \"{inputFilename}\"");

            var psiZip = new ProcessStartInfo
            {
                FileName = BuildLambdaZipCliPath,
                Arguments = args.ToString(),
                WorkingDirectory = rootDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                logger?.WriteLine("... zipping: " + e.Data);
            });

            try
            {
                using (var proc = new Process())
                {
                    proc.StartInfo = psiZip;
                    proc.Start();

                    proc.ErrorDataReceived += handler;
                    proc.OutputDataReceived += handler;
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();

                    proc.EnableRaisingEvents = true;
                    proc.WaitForExit();

                    if (proc.ExitCode == 0)
                    {
                        logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath));
                    }
                }
            }
            finally
            {
                try
                {
                    File.Delete(inputFilename);
                }
                catch (Exception e)
                {
                    logger?.WriteLine($"Warning: Unable to delete temporary input file, {inputFilename}, after zipping files: {e.Message}");
                }
            }                        
        }

19 View Source File : LambdaPackager.cs
License : Apache License 2.0
Project Creator : aws

private static void BundleWithZipCLI(string zipCLI, string zipArchivePath, string rootDirectory, IDictionary<string, string> includedFiles, IToolLogger logger)
        {
            EnsureBootstrapLinuxLineEndings(rootDirectory, includedFiles);
            
            var args = new StringBuilder("\"" + zipArchivePath + "\"");

            foreach (var kvp in includedFiles)
            {
                args.AppendFormat(" \"{0}\"", kvp.Key);
            }

            var psiZip = new ProcessStartInfo
            {
                FileName = zipCLI,
                Arguments = args.ToString(),
                WorkingDirectory = rootDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                logger?.WriteLine("... zipping: " + e.Data);
            });

            using (var proc = new Process())
            {
                proc.StartInfo = psiZip;
                proc.Start();

                proc.ErrorDataReceived += handler;
                proc.OutputDataReceived += handler;
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();

                proc.EnableRaisingEvents = true;
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath));
                }
            }
        }

19 View Source File : LambdaDotNetCLIWrapper.cs
License : Apache License 2.0
Project Creator : aws

public int Store(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string packageManifest, string architecture, bool enableOptimization)
        {
            if (outputLocation == null)
                throw new ArgumentNullException(nameof(outputLocation));

            if (Directory.Exists(outputLocation))
            {
                try
                {
                    Directory.Delete(outputLocation, true);
                    _logger?.WriteLine("Deleted previous publish folder");
                }
                catch (Exception e)
                {
                    _logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}");
                }
            }


            var dotnetCLI = FindExecutableInPath("dotnet.exe");
            if (dotnetCLI == null)
                dotnetCLI = FindExecutableInPath("dotnet");
            if (string.IsNullOrEmpty(dotnetCLI))
                throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH.");

            var fullProjectLocation = this._workingDirectory;
            if (!string.IsNullOrEmpty(projectLocation))
            {
                fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation);
            }

            var fullPackageManifest = Path.Combine(fullProjectLocation, packageManifest);

            _logger?.WriteLine($"... invoking 'dotnet store' for manifest {fullPackageManifest} into output directory {outputLocation}");


            StringBuilder arguments = new StringBuilder("store");
            if (!string.IsNullOrEmpty(outputLocation))
            {
                arguments.Append($" --output \"{outputLocation}\"");
            }

            if (!string.IsNullOrEmpty(targetFramework))
            {
                arguments.Append($" --framework \"{targetFramework}\"");
            }

            arguments.Append($" --manifest \"{fullPackageManifest}\"");


            arguments.Append($" --runtime {LambdaUtilities.DetermineRuntimeParameter(targetFramework, architecture)}");

            if(!enableOptimization)
            {
                arguments.Append(" --skip-optimization");
            }

            var psi = new ProcessStartInfo
            {
                FileName = dotnetCLI,
                Arguments = arguments.ToString(),
                WorkingDirectory = this._workingDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            var handler = (DataReceivedEventHandler)((o, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                    return;
                
                // Skip outputting this warning message as it adds a lot of noise to the output and is not actionable.
                // Full warning message being skipped: message NETSDK1062:
                // Unable to use package replacedets cache due to I/O error. This can occur when the same project is built
                // more than once in parallel. Performance may be degraded, but the build result will not be impacted.
                if (e.Data.Contains("message NETSDK1062"))
                    return;
                
                _logger?.WriteLine("... store: " + e.Data);
            });

            int exitCode;
            using (var proc = new Process())
            {
                proc.StartInfo = psi;
                proc.Start();


                proc.ErrorDataReceived += handler;
                proc.OutputDataReceived += handler;
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();

                proc.EnableRaisingEvents = true;

                proc.WaitForExit();

                exitCode = proc.ExitCode;
            }

            return exitCode;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : az64

private async Task<bool> GenerateSeed(string filename)
        {
            var seed = await GetSeed();
            var processInfo = new ProcessStartInfo(Path.Combine(_cliPath, @"MMR.CLI.exe"));
            processInfo.WorkingDirectory = _cliPath;
            processInfo.Arguments = $"-output \"output/{filename}.mmr\" -seed {seed} -spoiler -patch";
            processInfo.ErrorDialog = false;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardOutput = true;
            processInfo.RedirectStandardError = true;

            var proc = Process.Start(processInfo);
            proc.ErrorDataReceived += (sender, errorLine) => { if (errorLine.Data != null) Trace.WriteLine(errorLine.Data); };
            proc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) Trace.WriteLine(outputLine.Data); };
            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();

            proc.WaitForExit();
            return proc.ExitCode == 0;
        }

19 View Source File : Executable.cs
License : MIT License
Project Creator : Azure

public async Task<int> RunAsync(Action<string> outputCallback = null, Action<string> errorCallback = null, TimeSpan? timeout = null)
        {
            var processInfo = new ProcessStartInfo
            {
                FileName = _exeName,
                Arguments = _arguments,
                CreateNoWindow = !_visibleProcess,
                UseShellExecute = _shareConsole,
                RedirectStandardError = _streamOutput,
                RedirectStandardInput = _streamOutput,
                RedirectStandardOutput = _streamOutput,
                WorkingDirectory = _workingDirectory ?? Environment.CurrentDirectory
            };

            try
            {
                Process = Process.Start(processInfo);
            }
            catch (Win32Exception ex)
            {
                if (ex.Message == "The system cannot find the file specified")
                {
                    throw new FileNotFoundException(ex.Message, ex);
                }
                throw ex;
            }

            if (_streamOutput)
            {
                Process.OutputDataReceived += (s, e) => outputCallback?.Invoke(e.Data);
                Process.BeginOutputReadLine();
                Process.ErrorDataReceived += (s, e) => errorCallback?.Invoke(e.Data);
                Process.BeginErrorReadLine();
                Process.EnableRaisingEvents = true;
            }

            var exitCodeTask = Process.WaitForExitAsync();

            if (timeout == null)
                return await exitCodeTask;
            else
            {
                await Task.WhenAny(exitCodeTask, Task.Delay(timeout.Value));

                if (exitCodeTask.IsCompleted)
                    return exitCodeTask.Result;
                else
                {
                    Process.Kill();
                    throw new Exception("Process didn't exit within specified timeout");
                }
            }
        }

19 View Source File : FixtureHelpers.cs
License : MIT License
Project Creator : Azure

public static void StartProcessWithLogging(Process funcProcess, ILogger logger)
        {
            funcProcess.ErrorDataReceived += (sender, e) => logger.LogError(e?.Data);
            funcProcess.OutputDataReceived += (sender, e) => logger.LogInformation(e?.Data);

            funcProcess.Start();

            logger.LogInformation($"Started '{funcProcess.StartInfo.FileName}'");

            funcProcess.BeginErrorReadLine();
            funcProcess.BeginOutputReadLine();
        }

19 View Source File : ProcessWrapper.cs
License : MIT License
Project Creator : Azure

public async Task<int?> RunProcess(string fileName, string arguments, string workingDirectory, ITestOutputHelper testOutputHelper = null)
        {
            SemapreplacedSlim processExitSemapreplaced = new SemapreplacedSlim(0, 1);

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                WorkingDirectory = workingDirectory,
                FileName = fileName,
                RedirectStandardError = true,
                RedirectStandardOutput = true
            };

            if (!string.IsNullOrEmpty(arguments))
            {
                startInfo.Arguments = arguments;
            }

            Process testProcess = Process.Start(startInfo);
            testProcess.EnableRaisingEvents = true;
            testProcess.BeginOutputReadLine();
            testProcess.BeginErrorReadLine();
            testProcess.ErrorDataReceived += (s, o) =>
            {
                if (o.Data != null)
                {
                    testOutputHelper.WriteLine($"[{DateTime.UtcNow:O}] Error: {o.Data}");
                }
            };

            testProcess.OutputDataReceived += (s, o) =>
            {
                if (o.Data != null)
                {
                    testOutputHelper.WriteLine($"[{DateTime.UtcNow:O}] {o.Data}");
                }
            };

            testProcess.Exited += (s, e) =>
            {
                processExitSemapreplaced.Release();
            };

            int wait = 3 * 60 * 1000;
            if (!await processExitSemapreplaced.WaitAsync(wait))
            {
                testOutputHelper?.WriteLine($"Process '{testProcess.Id}' did not exit in {wait}ms.");
                testProcess.Kill();
            }

            return testProcess?.ExitCode;
        }

19 View Source File : Shell.cs
License : MIT License
Project Creator : Azure

public int Run(Action<string> outputCallback = null, Action<string> errorCallback = null)
            {
                var processInfo = new ProcessStartInfo
                {
                    FileName = _exeName,
                    Arguments = _arguments,
                    CreateNoWindow = !_visibleProcess,
                    UseShellExecute = _shareConsole,
                    RedirectStandardError = _streamOutput,
                    RedirectStandardInput = _streamOutput,
                    RedirectStandardOutput = _streamOutput,
                    WorkingDirectory = Directory.GetCurrentDirectory()
                };

                Process process = null;

                try
                {
                    process = Process.Start(processInfo);
                }
                catch (Win32Exception ex)
                {
                    if (ex.Message == "The system cannot find the file specified")
                    {
                        throw new FileNotFoundException(ex.Message, ex);
                    }
                    throw ex;
                }

                if (_streamOutput)
                {
                    if (outputCallback != null)
                    {
                        process.OutputDataReceived += (s, e) =>
                        {
                            if (e.Data != null)
                            {
                                outputCallback(e.Data);
                            }
                        };
                        process.BeginOutputReadLine();
                    }

                    if (errorCallback != null)
                    {
                        process.ErrorDataReceived += (s, e) =>
                        {
                            if (!string.IsNullOrWhiteSpace(e.Data))
                            {
                                errorCallback(e.Data);
                            }
                        };
                        process.BeginErrorReadLine();
                    }
                    process.EnableRaisingEvents = true;
                }
                process.WaitForExit();
                return process.ExitCode;
            }

19 View Source File : FixtureHelpers.cs
License : MIT License
Project Creator : Azure

public static void StartProcessWithLogging(Process funcProcess)
        {
            funcProcess.ErrorDataReceived += (sender, e) => Console.WriteLine(e?.Data);
            funcProcess.OutputDataReceived += (sender, e) => Console.WriteLine(e?.Data);

            funcProcess.Start();

            funcProcess.BeginErrorReadLine();
            funcProcess.BeginOutputReadLine();
        }

19 View Source File : IntegrationTestBase.cs
License : MIT License
Project Creator : Azure

protected void StartFunctionHost(string functionName, bool useTestFolder = false)
        {
            var startInfo = new ProcessStartInfo
            {
                // The full path to the Functions CLI is required in the ProcessStartInfo because UseShellExecute is set to false.
                // We cannot both use shell execute and redirect output at the same time: https://docs.microsoft.com//dotnet/api/system.diagnostics.processstartinfo.redirectstandardoutput#remarks
                FileName = GetFunctionsCoreToolsPath(),
                Arguments = $"start --verbose --port {this.Port} --functions {functionName}",
                WorkingDirectory = useTestFolder ? GetPathToBin() : Path.Combine(GetPathToBin(), "SqlExtensionSamples"),
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false
            };
            this.TestOutput.WriteLine($"Starting {startInfo.FileName} {startInfo.Arguments} in {startInfo.WorkingDirectory}");
            this.FunctionHost = new Process
            {
                StartInfo = startInfo
            };
            this.FunctionHost.OutputDataReceived += this.TestOutputHandler;
            this.FunctionHost.ErrorDataReceived += this.TestOutputHandler;

            this.FunctionHost.Start();
            this.FunctionHost.BeginOutputReadLine();
            this.FunctionHost.BeginErrorReadLine();

            Thread.Sleep(10000);     // This is just to give some time to func host to start, maybe there's a better way to do this (check if port's open?)
        }

19 View Source File : E2ETests.cs
License : MIT License
Project Creator : Azure

private void RunDotNet(string command, string workingDir, string solutionFile, string additionalArgs = null)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                WorkingDirectory = workingDir,
                FileName = "dotnet",
                Arguments = $"{command} {solutionFile} {additionalArgs} -nodeReuse:False",
                RedirectStandardError = true,
                RedirectStandardOutput = true
            };

            using (Process process = Process.Start(startInfo))
            {
                StringBuilder stdOut = new StringBuilder(); ;
                StringBuilder stdErr = new StringBuilder();

                process.OutputDataReceived += (s, e) =>
                {
                    if (e.Data != null)
                    {
                        stdOut.AppendLine(e.Data);
                    }
                };

                process.ErrorDataReceived += (s, e) =>
                {
                    if (e.Data != null)
                    {
                        stdErr.AppendLine(e.Data);
                    }
                };

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                process.WaitForExit();

                replacedert.True(process.ExitCode == 0, $"StdOut: {stdOut} | StdErr: {stdErr}");
                replacedert.Empty(stdErr.ToString());
                //replacedert.DoesNotContain(": warning ", stdOut.ToString());
                replacedert.DoesNotContain(": error ", stdOut.ToString());
            }
        }

19 View Source File : ProcessEx.cs
License : MIT License
Project Creator : Azure

public static async Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, Action<string> onStandardOutput, Action<string> onStandardError, CancellationToken cancellationToken)
        {
            var standardOutput = new List<string>();
            var standardError = new List<string>();

            // force some settings in the start info so we can capture the output
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true
            };

            var standardOutputResults = new TaskCompletionSource<string[]>();
            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                    onStandardOutput(args.Data);
                }
                else
                {
                    standardOutputResults.SetResult(standardOutput.ToArray());
                }
            };

            var standardErrorResults = new TaskCompletionSource<string[]>();
            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                    onStandardError(args.Data);
                }
                else
                {
                    standardErrorResults.SetResult(standardError.ToArray());
                }
            };

            var processStartTime = new TaskCompletionSource<DateTime>();

            process.Exited += async (sender, args) =>
            {
                // Since the Exited event can happen asynchronously to the output and error events,
                // we await the task results for stdout/stderr to ensure they both closed.  We must await
                // the stdout/stderr tasks instead of just accessing the Result property due to behavior on MacOS.
                // For more details, see the PR at https://github.com/jamesmanning/RunProcessAsTask/pull/16/
                tcs.TrySetResult(
                    new ProcessResults(
                        process,
                        await processStartTime.Task.ConfigureAwait(false),
                        await standardOutputResults.Task.ConfigureAwait(false),
                        await standardErrorResults.Task.ConfigureAwait(false)));
            };

            using (cancellationToken.Register(
                () =>
                {
                    tcs.TrySetCanceled();
                    try
                    {
                        if (!process.HasExited)
                            process.Kill();
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }))
            {
                cancellationToken.ThrowIfCancellationRequested();

                var startTime = DateTime.Now;
                if (process.Start() == false)
                {
                    tcs.TrySetException(new InvalidOperationException("Failed to start process"));
                }
                else
                {
                    try
                    {
                        startTime = process.StartTime;
                    }
                    catch (Exception)
                    {
                        // best effort to try and get a more accurate start time, but if we fail to access StartTime
                        // (for instance, process has already existed), we still have a valid value to use.
                    }

                    processStartTime.SetResult(startTime);

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                }

                return await tcs.Task.ConfigureAwait(false);
            }
        }

19 View Source File : WorkflowTestHost.cs
License : MIT License
Project Creator : Azure

protected void StartFunctionRuntime(WorkflowTestInput[] inputs, string localSettings, string parameters, string connectionDetails, string host, DirectoryInfo artifactsDirectory)
        {
            try
            {
                var processes = Process.GetProcessesByName("func");
                foreach (var process in processes)
                {
                    process.Kill();
                }

                Directory.CreateDirectory(this.WorkingDirectory);

                if (inputs != null && inputs.Length > 0)
                {
                    foreach (var input in inputs)
                    {
                        if (!string.IsNullOrEmpty(input.FunctionName))
                        {
                            Directory.CreateDirectory(Path.Combine(this.WorkingDirectory, input.FunctionName));
                            File.WriteAllText(Path.Combine(this.WorkingDirectory, input.FunctionName, input.Filename), input.FlowDefinition);
                        }
                    }
                }

                if (artifactsDirectory != null)
                {
                    if (!artifactsDirectory.Exists)
                    {
                        throw new DirectoryNotFoundException(artifactsDirectory.FullName);
                    }

                    var artifactsWorkingDirectory = Path.Combine(this.WorkingDirectory, "Artifacts");
                    Directory.CreateDirectory(artifactsWorkingDirectory);
                    WorkflowTestHost.CopyDirectory(source: artifactsDirectory, destination: new DirectoryInfo(artifactsWorkingDirectory));
                }

                if (!string.IsNullOrEmpty(parameters))
                {
                    File.WriteAllText(Path.Combine(this.WorkingDirectory, "parameters.json"), parameters);
                }

                if (!string.IsNullOrEmpty(connectionDetails))
                {
                    File.WriteAllText(Path.Combine(this.WorkingDirectory, "connections.json"), connectionDetails);
                }

                if (!string.IsNullOrEmpty(localSettings))
                {
                    File.WriteAllText(Path.Combine(this.WorkingDirectory, "local.settings.json"), localSettings);
                }
                else
                {
                    File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\..\\TestFiles\\local.settings.json"), Path.Combine(this.WorkingDirectory, "local.settings.json"));
                }

                if (!string.IsNullOrEmpty(host))
                {
                    File.WriteAllText(Path.Combine(this.WorkingDirectory, "host.json"), host);
                }
                else
                {
                    File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\..\\TestFiles\\host.json"), Path.Combine(this.WorkingDirectory, "host.json"));
                }

                this.Process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        WorkingDirectory = this.WorkingDirectory,
                        FileName = "func.exe",
                        Arguments = "start --verbose",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                    }
                };

                var processStarted = new TaskCompletionSource<bool>();

                this.Process.OutputDataReceived += (sender, args) =>
                {
                    var outputData = args.Data;
                    Console.WriteLine(outputData);
                    if (outputData != null && outputData.Contains("Host started") && !processStarted.Task.IsCompleted)
                    {
                        processStarted.SetResult(true);
                    }

                    lock (this)
                    {
                        this.OutputData.Add(args.Data);
                    }
                };

                var errorData = string.Empty;
                this.Process.ErrorDataReceived += (sender, args) =>
                {
                    errorData = args.Data;
                    Console.Write(errorData);

                    lock (this)
                    {
                        this.ErrorData.Add(args.Data);
                    }
                };

                this.Process.Start();

                this.Process.BeginOutputReadLine();
                this.Process.BeginErrorReadLine();

                var result = Task.WhenAny(processStarted.Task, Task.Delay(TimeSpan.FromMinutes(2))).Result;

                if (result != processStarted.Task)
                {
                    throw new InvalidOperationException("Runtime did not start properly. Please make sure you have the latest Azure Functions Core Tools installed and available on your PATH environment variable, and that Azurite is up and running.");
                }

                if (this.Process.HasExited)
                {
                    throw new InvalidOperationException($"Runtime did not start properly. The error is '{errorData}'. Please make sure you have the latest Azure Functions Core Tools installed and available on your PATH environment variable, and that Azurite is up and running.");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Directory.Delete(this.WorkingDirectory, recursive: true);

                throw;
            }
        }

19 View Source File : PostDeploymentHelper.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

private static void ExecuteScript(string file)
        {
            var fi = new FileInfo(file);
            ProcessStartInfo processInfo;
            if (string.Equals(".ps1", fi.Extension, StringComparison.OrdinalIgnoreCase))
            {
                processInfo = new ProcessStartInfo("PowerShell.exe", string.Format("-ExecutionPolicy RemoteSigned -File \"{0}\"", file));
            }
            else
            {
                processInfo = new ProcessStartInfo(file);
            }

            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardInput = true;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            DataReceivedEventHandler stdoutHandler = (object sender, DataReceivedEventArgs e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.Data))
                {
                    Trace(TraceEventType.Information, "{0}", e.Data);
                }
            };

            DataReceivedEventHandler stderrHandler = (object sender, DataReceivedEventArgs e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.Data))
                {
                    Trace(TraceEventType.Error, "{0}", e.Data);
                }
            };

            Trace(TraceEventType.Information, "Run post-deployment: \"{0}\" {1}", processInfo.FileName, processInfo.Arguments);
            var process = Process.Start(processInfo);
            var processName = process.ProcessName;
            var processId = process.Id;
            Trace(TraceEventType.Information, "Process {0}({1}) started", processName, processId);

            // hook stdout and stderr
            process.OutputDataReceived += stdoutHandler;
            process.BeginOutputReadLine();
            process.ErrorDataReceived += stderrHandler;
            process.BeginErrorReadLine();

            var timeout = (int)GetCommandTimeOut().TotalMilliseconds;
            if (!process.WaitForExit(timeout))
            {
                process.Kill();
                throw new TimeoutException(String.Format("Process {0}({1}) exceeded {2}ms timeout", processName, processId, timeout));
            }

            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new InvalidOperationException(String.Format("Process {0}({1}) exited with {2} exitcode.", processName, processId, process.ExitCode));
            }

            Trace(TraceEventType.Information, "Process {0}({1}) executed successfully.", processName, processId);
        }

19 View Source File : CommandExecutor.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

public void ExecuteCommandAsync(string command, string relativeWorkingDirectory)
        {
            string workingDirectory;
            if (String.IsNullOrEmpty(relativeWorkingDirectory))
            {
                workingDirectory = _rootDirectory;
            }
            else
            {
                workingDirectory = Path.Combine(_rootDirectory, System.Environment.ExpandEnvironmentVariables(relativeWorkingDirectory));
            }

            Executable exe = _externalCommandFactory.BuildExternalCommandExecutable(workingDirectory, _environment.WebRootPath, NullLogger.Instance);
            _executingProcess = exe.CreateProcess(command);

            var commandEvent = CommandEvent;

            _executingProcess.Exited += (sender, e) =>
            {
                if (commandEvent != null)
                {
                    commandEvent(new CommandEvent(CommandEventType.Complete)
                    {
                        ExitCode = _executingProcess.ExitCode
                    });
                }
            };

            _executingProcess.OutputDataReceived += (sender, e) =>
            {
                if (e.Data == null)
                {
                    return;
                }

                if (commandEvent != null)
                {
                    commandEvent(new CommandEvent(CommandEventType.Output, e.Data));
                }
            };

            _executingProcess.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data == null)
                {
                    return;
                }

                if (commandEvent != null)
                {
                    commandEvent(new CommandEvent(CommandEventType.Error, e.Data));
                }
            };

            _executingProcess.EnableRaisingEvents = true;
            _executingProcess.Start();
            _executingProcess.BeginErrorReadLine();
            _executingProcess.BeginOutputReadLine();

            _executingProcess.StandardInput.Close();
        }

19 View Source File : ffmpeg-encoding.cs
License : MIT License
Project Creator : Azure-Samples

[FunctionName("ffmpeg-encoding")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req, ILogger log, ExecutionContext context)
        {
            string output = string.Empty;
            bool isSuccessful = true;
            dynamic ffmpegResult = new JObject();
            string errorText = string.Empty;
            int exitCode = 0;

            log.LogInformation("C# HTTP trigger function processed a request.");

            dynamic data;
            try
            {
                data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd());
            }
            catch (Exception ex)
            {
                return Helpers.Helpers.ReturnErrorException(log, ex);
            }

            var ffmpegArguments = (string)data.ffmpegArguments;

            var sasInputUrl = (string)data.sasInputUrl;
            if (sasInputUrl == null)
                return Helpers.Helpers.ReturnErrorException(log, "Error - please preplaced sasInputUrl in the JSON");

            var sasOutputUrl = (string)data.sasOutputUrl;
            if (sasOutputUrl == null)
                return Helpers.Helpers.ReturnErrorException(log, "Error - please preplaced sasOutputUrl in the JSON");


            log.LogInformation("Arguments : ");
            log.LogInformation(ffmpegArguments);

            try
            {
                var folder = context.FunctionDirectory;
                var tempFolder = Path.GetTempPath();

                string inputFileName = System.IO.Path.GetFileName(new Uri(sasInputUrl).LocalPath);
                string pathLocalInput = System.IO.Path.Combine(tempFolder, inputFileName);

                string outputFileName = System.IO.Path.GetFileName(new Uri(sasOutputUrl).LocalPath);
                string pathLocalOutput = System.IO.Path.Combine(tempFolder, outputFileName);

                foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.IsReady))
                {
                    log.LogInformation($"{drive.Name}: {drive.TotalFreeSpace / 1024 / 1024} MB");
                }

                /* Downloads the original video file from blob to local storage. */
                log.LogInformation("Dowloading source file from blob to local");
                using (FileStream fs = System.IO.File.Create(pathLocalInput))
                {
                    try
                    {
                        var readBlob = new CloudBlob(new Uri(sasInputUrl));
                        await readBlob.DownloadToStreamAsync(fs);
                        log.LogInformation("Downloaded input file from blob");
                    }
                    catch (Exception ex)
                    {
                        log.LogError("There was a problem downloading input file from blob. " + ex.ToString());
                    }
                }

                log.LogInformation("Encoding...");
                var file = System.IO.Path.Combine(folder, "..\\ffmpeg\\ffmpeg.exe");

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = file;

                process.StartInfo.Arguments = (ffmpegArguments ?? " -i {input} {output} -y")
                    .Replace("{input}", "\"" + pathLocalInput + "\"")
                    .Replace("{output}", "\"" + pathLocalOutput + "\"")
                    .Replace("'", "\"");

                log.LogInformation(process.StartInfo.Arguments);

                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.OutputDataReceived += new DataReceivedEventHandler(
                    (s, e) =>
                    {
                        log.LogInformation("O: " + e.Data);
                    }
                );
                process.ErrorDataReceived += new DataReceivedEventHandler(
                    (s, e) =>
                    {
                        log.LogInformation("E: " + e.Data);
                    }
                );
                //start process
                process.Start();
                log.LogInformation("process started");
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();

                exitCode = process.ExitCode;
                ffmpegResult = output;

                log.LogInformation("Video Converted");

                /* Uploads the encoded video file from local to blob. */
                log.LogInformation("Uploading encoded file to blob");
                using (FileStream fs = System.IO.File.OpenRead(pathLocalOutput))
                {
                    try
                    {
                        var writeBlob = new CloudBlockBlob(new Uri(sasOutputUrl));
                        await writeBlob.UploadFromStreamAsync(fs);
                        log.LogInformation("Uploaded encoded file to blob");
                    }
                    catch (Exception ex)
                    {
                        log.LogInformation("There was a problem uploading converted file to blob. " + ex.ToString());
                    }
                }
                System.IO.File.Delete(pathLocalInput);
                System.IO.File.Delete(pathLocalOutput);
            }
            catch (Exception e)
            {
                isSuccessful = false;
                errorText += e.Message;
            }

            if (exitCode != 0)
            {
                isSuccessful = false;
            }

            var response = new JObject
            {
                {"isSuccessful", isSuccessful},
                {"ffmpegResult",  ffmpegResult},
                {"errorText", errorText }

            };

            return new OkObjectResult(
                response
            );
        }

19 View Source File : ProcessService.cs
License : The Unlicense
Project Creator : BAndysc

public async Task<int> Run(CancellationToken token, string path, string arguments, string? workingDirectory, Action<string>? onOutput,
            Action<string>? onError, Action<TextWriter>? onInput,
            params (string, string)[] envVars)
        {
            var startInfo = new ProcessStartInfo(path, arguments);
            startInfo.UseShellExecute = false;
            if (onOutput != null)
                startInfo.RedirectStandardOutput = true;
            if (onError != null)
                startInfo.RedirectStandardError = true;
            if (onInput != null)
                startInfo.RedirectStandardInput = true;
            startInfo.CreateNoWindow = true;
            
            foreach (var envVar in envVars)
                startInfo.Environment.Add(envVar.Item1, envVar.Item2);
    
            if (workingDirectory != null)
                startInfo.WorkingDirectory = workingDirectory;
            
            Process process = new Process();
            process.StartInfo = startInfo;
            process.ErrorDataReceived += (sender, data) =>
            {
                if (data.Data != null)
                {
                    onError?.Invoke(data.Data);
                }
            };
            process.OutputDataReceived += (sender, data) =>
            {
                if (data.Data != null)
                {
                    onOutput?.Invoke(data.Data);
                }
            };
            if (!process.Start())
                throw new Exception("Cannot start " + path);
            
            if (onOutput != null)
                process.BeginOutputReadLine();
            
            if (onError != null)
                process.BeginErrorReadLine();

            //onInput?.Invoke(process.StandardInput);

            try
            {
                await process.WaitForExitAsync(token);
            }
            catch (TaskCanceledException)
            {
                process.Kill();
            }

            return process.HasExited ? process.ExitCode : -1;
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Benjerman

private void startServerButton_Click(object sender, EventArgs e)
        {
            string processFileName = "";


            processFileName = @"bedrock_server.exe";


            minecraftProcess = new System.Diagnostics.Process();

            minecraftProcess.StartInfo.FileName = processFileName;

            AddTextToOutputTextBox("Using this terminal: " + minecraftProcess.StartInfo.FileName);

            minecraftProcess.StartInfo.UseShellExecute = false;
            minecraftProcess.StartInfo.CreateNoWindow = true;
            minecraftProcess.StartInfo.RedirectStandardInput = true;
            minecraftProcess.StartInfo.RedirectStandardOutput = true;
            minecraftProcess.StartInfo.RedirectStandardError = true;

            minecraftProcess.EnableRaisingEvents = true;
            minecraftProcess.Exited += new EventHandler(ProcessExited);
            minecraftProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ConsoleOutputHandler);
            minecraftProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(ConsoleOutputHandler);

            minecraftProcess.Start();

            mcInputStream = minecraftProcess.StandardInput;
            minecraftProcess.BeginOutputReadLine();
            minecraftProcess.BeginErrorReadLine();

            mcInputStream.WriteLine("gamerule");
        }

See More Examples