System.Diagnostics.Process.BeginOutputReadLine()

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

644 Examples 7

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

private void V2rayStart()
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.PriorityClreplaced = ProcessPriorityClreplaced.High;
                p.BeginOutputReadLine();
                //processId = p.Id;
                _process = p;

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(true, msg);
            }
        }

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

private int V2rayStartNew(string configStr)
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return -1;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        Arguments = "-config stdin:",
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.BeginOutputReadLine();

                p.StandardInput.Write(configStr);
                p.StandardInput.Close();

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
                return p.Id;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(false, msg);
                return -1;
            }
        }

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 : OVRPlatformTool.cs
License : MIT License
Project Creator : absurd-joy

static void CheckForUpdate(string dataPath)
		{
			string platformUtilPath = CheckForPlatformUtil(dataPath);
			InitializePlatformUtilProcess(platformUtilPath, "self-update");

			OVRPlatformTool.log += "Checking for update...\n";

			ovrPlatUtilProcess.Exited += new EventHandler(
				(s, e) =>
				{
					if (File.Exists(dataPath + ".ovr-platform-util.exe"))
					{
						OVRPlatformTool.log += "Cleaning up...\n";
						while (File.Exists(dataPath + ".ovr-platform-util.exe")) { }
						OVRPlatformTool.log += "Finished updating platform utility.\n";
					}
					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";
					}
				}
			);

			try
			{
				ovrPlatUtilProcess.Start();
				ovrPlatUtilProcess.BeginOutputReadLine();
			}
			catch
			{
				if (ThrowPlatformUtilStartupError(platformUtilPath))
				{
					CheckForUpdate(dataPath);
				}
			}
		}

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

static void LoadRedistPackages(string dataPath)
		{
			// Check / Download the platform util and call list-redists on it
			activeProcess = true;
			string platformUtilPath = CheckForPlatformUtil(dataPath);
			InitializePlatformUtilProcess(platformUtilPath, "list-redists");

			OVRPlatformTool.log += "Loading redistributable packages...\n";

			List<RedistPackage> redistPacks = new List<RedistPackage>();

			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") && !e.Data.Contains("ID"))
					{
						// Get the name / ID pair from the CLI and create a redist package instance
						string[] terms = e.Data.Split('|');
						if (terms.Length == 2)
						{
							RedistPackage redistPack = new RedistPackage(terms[1], terms[0]);
							redistPacks.Add(redistPack);
						}
					}
				}
			);

			try
			{
				ovrPlatUtilProcess.Start();
				ovrPlatUtilProcess.BeginOutputReadLine();

				ovrPlatUtilProcess.WaitForExit();

				if (redistPacks.Count != OVRPlatformToolSettings.RiftRedistPackages.Count)
				{
					OVRPlatformTool.log += "Successfully updated redistributable packages.\n";
					OVRPlatformToolSettings.RiftRedistPackages = redistPacks;
				}
				else
				{
					OVRPlatformTool.log += "Redistributable packages up to date.\n";
				}
			}
			catch
			{
				if (ThrowPlatformUtilStartupError(platformUtilPath))
				{
					LoadRedistPackages(dataPath);
				}
			}
		}

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 : 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 : VideoAnalyzer.cs
License : MIT License
Project Creator : AlturosDestinations

private async Task<replacedyzeResult> GetVideoInfoAsync(MediaInput mediaInput, CancellationToken cancellationToken = default)
        {
            if (!File.Exists(this._ffprobePath))
            {
                return new replacedyzeResult { Successful = false, ErrorMessage = $"ffprobe could not be found {this._ffprobePath}" };
            }

            var startInfo = new ProcessStartInfo
            {
                FileName = this._ffprobePath,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            if (mediaInput.FileContent != null)
            {
                startInfo.RedirectStandardInput = true;
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams -";
            }
            else
            {
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams \"{mediaInput.FilePath}\"";
            }

            using (var outputWaitHandle = new AutoResetEvent(false))
            {
                var json = new StringBuilder();

                var dataReceived = new DataReceivedEventHandler((sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                        return;
                    }

                    json.AppendLine(e.Data);
                });

                this._process = new Process();

                try
                {
                    this._process.StartInfo = startInfo;
                    this._process.OutputDataReceived += dataReceived;

                    if (!this._process.Start())
                    {
                        return new replacedyzeResult { ErrorMessage = "Cannot start ffprobe" };
                    }

                    this._process.BeginOutputReadLine();

                    if (mediaInput.FileContent != null)
                    {
                        using (var ffprobeIn = this._process.StandardInput.BaseStream)
                        {
                            var packageSize = 100000;
                            for (var i = 0; i < mediaInput.FileContent.Length; i += packageSize)
                            {
                                var package = mediaInput.FileContent.Skip(i).Take(packageSize).ToArray();
                                await ffprobeIn.WriteAsync(package, 0, package.Length, cancellationToken);
                            }
                            await ffprobeIn.FlushAsync(cancellationToken);
                            ffprobeIn.Close();
                        }
                    }

                    if (!this._process.WaitForExit(this._timeout) || !outputWaitHandle.WaitOne(this._timeout))
                    {
                        return new replacedyzeResult { ErrorMessage = $"Timeout reached {this._timeout} (ms)" };
                    }

                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (IOException)
                {
                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe (IOException)" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (Exception exception)
                {
                    return new replacedyzeResult { Successful = false, ErrorMessage = exception.ToString() };
                }
                finally
                {
                    this._process.OutputDataReceived -= dataReceived;
                    this._process?.Dispose();
                }
            }
        }

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 : PortHelper.cs
License : MIT License
Project Creator : AmazingDM

private static void GetReservedPortRange(PortType portType, ref List<Range> targetList)
        {
            var lines = new List<string>();
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "netsh",
                    Arguments = $" int ipv4 show excludedportrange {portType}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            process.OutputDataReceived += (s, e) =>
            {
                if (e.Data != null) lines.Add(e.Data);
            };
            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit();

            var splitLine = false;
            foreach (var line in lines)
                if (!splitLine)
                {
                    if (line.StartsWith("-"))
                        splitLine = true;
                }
                else
                {
                    if (line == string.Empty)
                        break;

                    var value = line.Trim().Split(' ').Where(s => s != string.Empty).ToArray();

                    targetList.Add(new Range(ushort.Parse(value[0]), ushort.Parse(value[1])));
                }
        }

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 : Solution.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public bool BuildSolution(IOutput output, Configuration configuration, bool rebuild, string msbuildPath = null)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            if (!UpdateExternals(output, configuration, false, msbuildPath))
            {
                return false;
            }
            BuildResult buildResult = new BuildResult();
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(GetMsbuildPath(msbuildPath));
            string targetAction = rebuild ? "Rebuild" : "Build";
            process.StartInfo.Arguments = string.Format("{0} /t:{1} /p:Configuration={2} /m", SolutionFullName, targetAction, configuration);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            DataReceivedEventHandler eventHandler = (s, e) => { output.WriteLine(e.Data); buildResult.ProcessMessage(e.Data); };
            try
            {
                process.OutputDataReceived += eventHandler;
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();
            }
            finally
            {
                process.OutputDataReceived -= eventHandler;
                buildResult.SetTime(stopwatch.Elapsed);
                BuildResult = buildResult;
            }
            return process.ExitCode == 0;
        }

19 View Source File : GraphicsUtils.cs
License : MIT License
Project Creator : AntonyCorbett

private static bool ExecuteFFMpeg(string ffmpegFolder, string arguments)
        {
            Log.Logger.Debug($"Executing ffmpeg with args = {arguments}");

            var ffmpegPath = Path.Combine(ffmpegFolder, "ffmpeg.exe");

            var p = new Process
            {
                StartInfo =
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    FileName = ffmpegPath,
                    Arguments = arguments,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                },
            };

            using (p)
            {
                p.Start();

                p.BeginOutputReadLine();
                p.StandardError.ReadToEnd();

                var rv = p.WaitForExit(5000);
                if (!p.HasExited)
                {
                    p.Kill();
                }

                Log.Logger.Debug($"Ffmpeg return code = {rv}");

                return rv;
            }
        }

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 : MLTools.cs
License : MIT License
Project Creator : aornelas

void ExecuteMLDBCommand(string command, string args)
    {
        // display command to user
        hasExited = false;
        p = new System.Diagnostics.Process();
        p.StartInfo.WorkingDirectory = sdkPath + "/tools/mldb/";
        p.StartInfo.FileName = "mldb.exe";
        // make sure user can't initiate an infinite log, and reset output whenever log is called so we can show the whole 100 lines
        if (command == "log")
        {
            terminalOutput = "";
            if (args == "")
            {
                args = "-d -t 100";
                terminalOutput += "No support for continuous logging yet. Default log gives 100 lines.";
            }
        }
        p.StartInfo.Arguments = command + " " + args;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        p.StartInfo.RedirectStandardOutput = true;
        p.Exited += new System.EventHandler(handleExit);
        p.EnableRaisingEvents = true;
        p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(
           (s, e) =>
           {
               string output = e.Data;
               prevMessage = output;
               switch (command)
               {
                   case "log":
                       terminalOutput += output;
                       terminalOutput += "\n";
                       log += output + "\n";
                       break;
                   default:
                       terminalOutput += output;
                       terminalOutput += "\n";
                       break;
               }
               // set scrollbar position to bottom when new data is received
               scroll.y = 10000;

               // if terminal output is too long, empty it 
               if (terminalOutput.Length >= 16382)
               {
                   terminalOutput = "";
               }
           }
       );
        // handle long commands like log and install individually, do not wait for exit here (thus not blocking the main threa
        terminalOutput += "mldb " + command + " " + args + "\n";
        p.Start();

        p.BeginOutputReadLine();
    }

19 View Source File : UnityDebugViewerADB.cs
License : Apache License 2.0
Project Creator : AsanCai

public bool StartLogcatProcess(DataReceivedEventHandler processDataHandler, string filter, string adbPath)
        {
            /// stop first
            StopLogcatProcess();

            if (CheckDevice(adbPath))
            {
                string commands = string.IsNullOrEmpty(filter) ? UnityDebugViewerADBUtility.LOGCAT_ARGUMENTS : string.Format(UnityDebugViewerADBUtility.LOGCAT_ARGUMENTS_WITH_FILTER, filter);

                ProcessStartInfo logProcessInfo = CreateProcessStartInfo(commands, adbPath);
                if (logProcessInfo != null)
                {
                    /// 执行adb进程
                    logCatProcess = Process.Start(logProcessInfo);
                    logCatProcess.OutputDataReceived += processDataHandler;
                    logCatProcess.BeginOutputReadLine();
                    return true;
                }
            }

            return false;
        }

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

private static void SendNetshCommand(string command)
        {
            ProcessStartInfo psi = new ProcessStartInfo("netsh")
            {
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
            };

            TL.LogMessage("SendNetshCommand", "Creating netsh process");
            Process process = new Process
            {
                StartInfo = psi
            };
            process.OutputDataReceived += (sender, args) => TL.LogMessage("SetAcl", string.Format("NetSh output: {0}", args.Data));

            TL.LogMessage("SendNetshCommand", "Starting process");
            process.Start();
            process.BeginOutputReadLine();
            TL.LogMessage("SendNetshCommand", "Process started");

            TL.LogMessage("SendNetshCommand", string.Format("Sending netsh command: {0}", command));
            process.StandardInput.WriteLine(command);
            TL.LogMessage("SendNetshCommand", string.Format("Sent netsh command: {0}", command));

            TL.LogMessage("SendNetshCommand", string.Format("Sending netsh command: exit"));
            process.StandardInput.WriteLine("exit");
            TL.LogMessage("SendNetshCommand", string.Format("Sent netsh command: exit"));

            process.WaitForExit();
            TL.LogMessage("SendNetshCommand", "Process ended");

        }

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 : DotnetCoreBuildTools.cs
License : MIT License
Project Creator : axlj45

public static string GetCoreBasePath(string projectPath)
        {
            // Ensure that we set the DOTNET_CLI_UI_LANGUAGE environment variable to "en-US" before
            // running 'dotnet --info'. Otherwise, we may get localized results.

            string originalCliLanguage = Environment.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE");
            Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en-US");

            try
            {
                // Create the process info
                ProcessStartInfo startInfo = new ProcessStartInfo("dotnet", "--info")
                {
                    // global.json may change the version, so need to set working directory
                    WorkingDirectory = Path.GetDirectoryName(projectPath),
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                // Execute the process
                using (Process process = Process.Start(startInfo))
                {
                    List<string> lines = new List<string>();
                    process.OutputDataReceived += (_, e) =>
                    {
                        if (!string.IsNullOrWhiteSpace(e.Data))
                        {
                            lines.Add(e.Data);
                        }
                    };
                    process.BeginOutputReadLine();
                    process.WaitForExit();
                    return ParseCoreBasePath(lines);
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", originalCliLanguage);
            }
        }

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 : ProcessRunner.cs
License : MIT License
Project Creator : azist

public int Run(int timeoutMs = 0)
        {
          m_BufferedOutput = new StringBuilder();
          m_ExitCode = 0;
          var watch = new Stopwatch();
          using (Process p = new Process())
          {
            p.StartInfo.FileName = ProcessCmd;
            p.StartInfo.Arguments = Arguments;
            p.StartInfo.UseShellExecute = false;//so we can redir IO gotta be false
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            p.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    m_BufferedOutput.AppendLine(e.Data);
                }
            };


            p.Start();
            watch.Start();

            p.BeginOutputReadLine();

            if (timeoutMs>0)
                p.WaitForExit(timeoutMs);
            else
                p.WaitForExit();


            m_ExecutionTimeMs = (int)watch.ElapsedMilliseconds;

            if (!p.HasExited)
            {
                m_TimedOutAndKilled = true;
                p.Kill();
            }
            else
                m_ExitCode = p.ExitCode;


          }//using

          return m_ExitCode;
        }

19 View Source File : BundledMongoDb.cs
License : MIT License
Project Creator : azist

protected override void DoStart()
    {
      base.DoStart();

      if (!System.IO.Directory.Exists(m_MongoBinPath.NonBlank(nameof(MongoBinPath))))
       throw new MongoDbConnectorException("The MongoDb bin path `{0}` does not exist".Args(m_MongoBinPath));

      var p = m_ServerProcess = new Process();

      p.StartInfo.FileName = System.IO.Path.Combine(m_MongoBinPath, PROCESS_CMD);

      //see:  https://docs.mongodb.com/manual/reference/program/mongod/
      var args = "--noauth --port {0}".Args(m_Mongo_port);

      if (m_Mongo_bind_ip.IsNotNullOrWhiteSpace())
        args += " --bind_ip \"{0}\"".Args(m_Mongo_bind_ip);

      if (m_Mongo_dbpath.IsNotNullOrWhiteSpace())
      {
        //20201205 DKh #378
        IOUtils.EnsureAccessibleDirectory(m_Mongo_dbpath);

        args += " --dbpath \"{0}\"".Args(m_Mongo_dbpath);
      }

      if (m_Mongo_quiet) args += " --quiet";

      if (m_Mongo_directoryperdb) args += " --directoryperdb";

      p.StartInfo.Arguments = args;
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.CreateNoWindow = true;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

      var logrel = Guid.NewGuid();
      p.OutputDataReceived += (sender, e) =>
      {
        var ll = this.MongoLogMinLevel;
        if (!ll.HasValue) return;//logging disabled

        if (e.Data != null && e.Data.IsNotNullOrWhiteSpace())
        {
          //https://docs.mongodb.com/manual/reference/log-messages/#json-log-output-format
          //With MongoDB 4.4, all log output is now in JSON format. This includes log output sent to the file, syslog, and
          //stdout(standard out) log destinations, as well as the output of the getLog command.
          try
          {
            //Re: #495
            var map = e.Data.JsonToDataObject() as JsonDataMap;
            var t = Log.MessageType.TraceD;

            var ts = map["s"].replacedtring();
            if (ts.EqualsOrdIgnoreCase("F")) t = Log.MessageType.CatastrophicError;
            else if (ts.EqualsOrdIgnoreCase("E")) t = Log.MessageType.Error;
            else if (ts.EqualsOrdIgnoreCase("W")) t = Log.MessageType.Warning;

            if (t >= ll.Value)
            {
              WriteLog(t, PROCESS_CMD, map["msg"].replacedtring(), pars: e.Data, related: logrel);
            }
          }
          catch //older versions of mongo
          {
            if (ll.Value <= Log.MessageType.TraceD)
            {
              WriteLog(Log.MessageType.TraceD, PROCESS_CMD, e.Data, related: logrel);
            }
          }

        }
      };

      p.Start();//<===========
      p.BeginOutputReadLine();

      var sw = Stopwatch.StartNew();
      while(App.Active)
      {
        System.Threading.Thread.Sleep(1000);//give process ramp-up time

        if (m_ServerProcess.HasExited)
        {
          ensureProcessTermination("start", m_StartupTimeoutMs);
          AbortStart();
          throw new MongoDbConnectorException("Mongo Db process crashed on start. Inspect logs for details (to enable logging, set this.ComponentLogLevel = Azos.Log.MessageType.Debug)");
        }

        if (sw.ElapsedMilliseconds > m_StartupTimeoutMs)
        {
          ensureProcessTermination("start", m_StartupTimeoutMs);
          AbortStart();
          throw new MongoDbConnectorException("Mongo Db process did not return success in the alloted time of {0}".Args(m_StartupTimeoutMs));
        }

        try
        {
           var db = GetDatabaseUnsafe(MongoConsts.ADMIN_DB);
           db.Ping();//ensure the successful connection
           break;//success
        }
        catch(Exception error)
        {
           WriteLog(Log.MessageType.TraceD, nameof(DoStart), "Error trying to db.Ping() on start: " + error.ToMessageWithType(), error);
        }
      }
    }

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");
                }
            }
        }

See More Examples