System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo)

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

4229 Examples 7

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

private void generateGames()
        {
            try
            {               
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "botgamelist " + SteamBotController.getSteamUserID() + " " + username));
            }
            catch (Exception) { }           
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(gameListFile));
        }

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

private void openSteamDesktopAuthAsync()
        {            
            if (!SteamTwoProperties.jsonSetting.SDALinkSetting.Equals(""))
            {
                string exepath = SteamTwoProperties.jsonSetting.SDALinkSetting;
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = exepath;
                psi.WorkingDirectory = Path.GetDirectoryName(exepath);
                Process.Start(psi);
            }           
        }

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

private void generateGames()
        {
            try
            {
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "gamelist"));
            }
            catch (Exception) { }
            Hide();
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(GAME_LIST_FILE));
            Show();
        }

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

private void achievements1_Click(object sender, RoutedEventArgs e)
        {
            if (listView1.SelectedItem != null)
            {
                ListViewItem item = new ListViewItem();
                item = (ListViewItem)listView1.SelectedItem;
                Process.Start(new ProcessStartInfo(SAM_GAME, item.Tag.ToString()));
            }
        }

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

private async void startIdler(bool delayed)
        {
            foreach (ListViewItem item in listView1.SelectedItems)
            {
                if (delayed)
                    await Task.Delay(4000);
                runningProc.Add(Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, item.Tag.ToString()) { WindowStyle = ProcessWindowStyle.Hidden }));
            }
        }

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

private static void luanchSteamTwo()
        {
            string exepath = AppDomain.CurrentDomain.BaseDirectory + "\\Steam Two.exe";
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = exepath;           
            psi.WorkingDirectory = Path.GetDirectoryName(exepath);
            psi.Arguments = "startup";
            Process.Start(psi);          
        }

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

static void CheckAdminRights()
        {
            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent());

            if (!wp.IsInRole(WindowsBuiltInRole.Administrator))
            {
                
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    Verb = "runas",
                    FileName = appExePath,
                    WorkingDirectory = appWorkDir
                };

                Process.Start(psi);
                Environment.Exit(0);
            }

        }

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

private bool RestartProcessWithExistedInfo(string extraArgs)
        {
            Log.Info("Restaring process {0} with extra args {1}", procType, extraArgs == null ? "None" : extraArgs);

            string newArgList = RebuildArgList(this.processArgs, extraArgs);

            ProcessStartInfo psi = new ProcessStartInfo(this.processPath, newArgList);
            psi.UseShellExecute = true;

            try
            {
                this.process = Process.Start(psi);
            }
            catch (Exception e)
            {
                Log.Critical("the process could not be recovered." + e.Message);
                return false;
            }


            this.process.Exited += Process_Exited;
            this.process.EnableRaisingEvents = true;
            this.processArgs = this.process.StartInfo.Arguments;
            this.pid = this.process.Id;

            Log.Info("New process created successfuly Pid: {0}", pid);

            return true;
        }

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

static bool Run(string process, string args)
        {

            if (!File.Exists(process))
            {
                Console.WriteLine("{0} not found. Process creation failed.", process);
                return false;
            }

            ProcessStartInfo psi = new ProcessStartInfo(process, args)
            {
                UseShellExecute = true
            };

            return Process.Start(psi) != null;
        }

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

static void Init()
        {
            bool watchdog = !System.Diagnostics.Debugger.IsAttached;
            Log.Warning("Initializing backend. (watchdog? = {0})",watchdog);

            RequestDispatcher.CreateDispatchers(4);
            RequestBridge.CreatePipeServers(4);

            Edi.StartEdi();
            
            //start health monitor.
            System.Diagnostics.Process.Start(
                Config.Get().SbmonPath, 
                string.Format("-backend {0} -memcached {1} -mport {2} -watchdog {3}", 
                System.Diagnostics.Process.GetCurrentProcess().Id,
                DataCacheInstance.ProcessId,Config.Get().MemcachedPort,watchdog));

            LogService.Start();
            Talk = new InternalTalk(true);
            Talk.OnTalk += Talk_OnTalk;
            
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : X86Assembly.cs
with MIT License
from 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY

private void button3_Click(object sender, EventArgs e)
        {
            //Crypt
            string result = Properties.Resources.stub;
            result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
            result = result.Replace("%native%", native.Checked.ToString().ToLower());
            result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
            result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
            result = result.Replace("%key%", key.Text);
            result = result.Replace("%asm%", GenerateKey());
            var providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            CompilerResults results;
            using (var provider = new CSharpCodeProvider(providerOptions))
            {
                var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
                if (ico !=  null)
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
                else
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";

                Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
                Params.Referencedreplacedemblies.Add("System.dll");
                Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
                Params.Referencedreplacedemblies.Add("System.Security.Dll");
                Params.Referencedreplacedemblies.Add("System.Management.dll");

                string fname = "";
                if (punp.Checked)
                {
                    fname = Pump();
                    Params.EmbeddedResources.Add(fname); 
                }
                
                string tmp = "payload";
                File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
                Params.EmbeddedResources.Add(tmp);
                results = provider.CompilereplacedemblyFromSource(Params, result);
                try
                {
                    File.Delete(tmp);
                    File.Delete(fname);
                }
                catch(Exception)
                {

                } 
            }
            if (results.Errors.Count == 0)
            {
                String temp = Environment.GetEnvironmentVariable("temp");
                if (obf.Checked)
                {
                   
                    File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
                    File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
                    File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
                    File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
                    File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
                    File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
                    File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);

                    String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
                    crproj = crproj.Replace("%base%", temp);
                    crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
                    File.WriteAllText(temp + "\\def.crproj", crproj);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    startInfo.FileName = "cmd.exe";
                    Thread pr = new Thread(() => Process.Start(startInfo));
                    pr.Start();
                    pr.Join();
                }
                else
                {
                    String file = Environment.CurrentDirectory + "\\Crypted.exe";
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception)
                    {

                    }
                    File.Move(temp + "\\Crypted.exe", file);
                }
                    

                MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            foreach (CompilerError compilerError in results.Errors)
            {
                MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
            }
            
            
                
        }

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

private void visitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (projects.SelectedItems.Count > 0)
            {
                try
                {
                    ListViewItem item = projects.SelectedItems[0];
                    NginxMonitorUrl pro = (NginxMonitorUrl)item.Tag;
                    Process.Start(pro.url);
                }
                catch { }                
            }
        }

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

private void visit2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (projects.SelectedItems.Count > 0)
            {
                try
                {
                    ListViewItem item = projects.SelectedItems[0];
                    NginxMonitorUrl pro = (NginxMonitorUrl)item.Tag;
                    Process.Start(pro.host);
                }
                catch { }
            }
        }

19 Source : Form1.cs
with MIT License
from 2401dem

private void button4_Click(object sender, EventArgs e)
        {
            if (IsFolder)
                if (textBox2.Text != "" && Directory.Exists(textBox2.Text))
                    System.Diagnostics.Process.Start(textBox2.Text);
                else
                    MessageBox.Show("Output folder does not exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                if (textBox2.Text.LastIndexOf('\\') != -1 && Directory.Exists(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf('\\'))))
                System.Diagnostics.Process.Start(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf('\\')));
            else
                MessageBox.Show("Output folder does not exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

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

private void tsbAbout_Click(object sender, EventArgs e)
        {
            Process.Start(Global.AboutUrl);
        }

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

private void tsbV2rayWebsite_Click(object sender, EventArgs e)
        {
            Process.Start(Global.v2rayWebsiteUrl);
        }

19 Source : FrmSettings.cs
with GNU General Public License v3.0
from 9vult

private void BtnViewFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", txtDirectory.Text);
        }

19 Source : FrmUpdate.cs
with GNU General Public License v3.0
from 9vult

private void BtnContinue_Click(object sender, EventArgs e)
        {
            if (rbWait.Checked)
            {
                this.Close();
            }
            else // Download Update
            {
                System.Diagnostics.Process.Start(info.Download_url);
                Application.Exit();
            }
        }

19 Source : ShellManager.cs
with GNU General Public License v3.0
from a4004

public static bool CheckCommand(string process, string arguments = null)
        {
            ProcessStartInfo cmdSi = new ProcessStartInfo()
            {
                FileName = process,
                Arguments = $"{(arguments == null ? "" : arguments)}",
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden
            };

            Program.Debug("shellmgr", $"Running command \"{process}{(arguments == null ? "" : " " + arguments)}\"");

            try
            {
                Process cmd = Process.Start(cmdSi);
                Program.Debug("shellmgr", "The system reports no errors at the moment. Attempting to close the process.");

                return ExitProcess(cmd) == 0;
            }
            catch (Exception ex)
            {
                Program.Debug("shellmgr", $"An error was encountered. {ex.Message}", Event.Critical);
                return false;
            }
        }

19 Source : ShellManager.cs
with GNU General Public License v3.0
from a4004

public static bool RunCommand(out string output, string process, string arguments = null)
        {
            ProcessStartInfo cmdSi = new ProcessStartInfo()
            {
                FileName = process,
                Arguments = $"{(arguments == null ? "" : arguments)}",
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            Program.Debug("shellmgr", $"Running command \"{process}{(arguments == null ? "" : " " + arguments)}\"");

            try
            {
                Process cmd = Process.Start(cmdSi);

                try
                {
                    Program.Debug("shellmgr", "The system reports no errors at the moment.");
                    Program.Debug("shellmgr", $"[INFO] The process (pid {cmd.Id}) is running as a task " +
                        $"and is limited to a runtime of 1800 seconds.", Event.Warning);
                }
                catch
                {
                    output = "The pid was invalid.";
                    return false;
                }

                cmd.WaitForExit(1800);

                output = cmd.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "");
                string error = cmd.StandardError.ReadToEnd().Replace("\r", "").Replace("\n", "");

                Program.Debug("shellmgr", $"{process} stderr: {error}", Event.Critical);

                if (!cmd.HasExited)
                    return ExitProcess(cmd) == 0;
                else
                    return cmd.ExitCode == 0;
            }
            catch (Exception ex)
            {
                Program.Debug("shellmgr", $"An error was encountered. {ex.Message}", Event.Critical);
                output = ex.Message;
                return false;
            }
        }

19 Source : HistoryViewer.cs
with MIT License
from aabiryukov

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
		private void ExecViewHistory(Uri tfsCollectionUri, string sourceControlFolder)
        {
            // gource start arguments
            string arguments;
            string replacedle;
			string avatarsDirectory = null;

            if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
            {
                replacedle = "History of " + sourceControlFolder;
				var logFile = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.txt");
	            
	            if (m_settigs.ViewAvatars)
	            {
		            avatarsDirectory = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.Avatars");
					if (!Directory.Exists(avatarsDirectory))
		            {
			            Directory.CreateDirectory(avatarsDirectory);
		            }
	            }

				bool historyFound;
				bool hasLines;

                using (var waitMessage = new WaitMessage("Connecting to Team Foundation Server...", OnCancelByUser))
                {
                    var progress = waitMessage.CreateProgress("Loading history ({0}% done) ...");

                    hasLines =
                        TfsLogWriter.CreateGourceLogFile(
                            logFile,
							avatarsDirectory,
                            tfsCollectionUri,
                            sourceControlFolder,
                            m_settigs,
                            ref m_canceled,
                            progress.SetValue
                            );

	                historyFound = progress.LastValue > 0;
                    progress.Done();
                }

                if (m_canceled)
					return;

                if (!hasLines)
                {
	                MessageBox.Show(
		                historyFound
			                ? "No items found.\nCheck your filters: 'User name' and 'File type'."
							: "No items found.\nTry to change period of the history (From/To dates).",
		                "TFS History Visualization");
	                return;
                }

	            arguments = string.Format(CultureInfo.InvariantCulture, " \"{0}\" ", logFile);

                // Setting other history settings

                arguments += " --seconds-per-day " + m_settigs.SecondsPerDay.ToString(CultureInfo.InvariantCulture);

                if (m_settigs.TimeScale != VisualizationSettings.TimeScaleOption.None)
                {
                    var optionValue = ConvertToString(m_settigs.TimeScale);
                    if (optionValue != null)
                        arguments += " --time-scale " + optionValue;
                }

                if (m_settigs.LoopPlayback)
                {
                    arguments += " --loop";
                }

				arguments += " --file-idle-time 60"; // 60 is default in gource 0.40 and older. Since 0.41 default 0.
            }
            else
            {
                // PlayMode: Live
                replacedle = "Live changes of " + sourceControlFolder;

                arguments = " --realtime --log-format custom -";
                arguments += " --file-idle-time 28800"; // 8 hours (work day)
            }

            var baseDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location) ??
                                "unknown";


            if (baseDirectory.Contains("Test"))
            {
                baseDirectory += @"\..\..\..\VSExtension";
            }

#if DEBUG
			// baseDirectory = @"C:\Temp\aaaa\уи³пс\";
#endif
            var gourcePath = Path.Combine(baseDirectory, @"Gource\Gource.exe");
            var dataPath = Path.Combine(baseDirectory, @"Data");

            // ******************************************************
            // Configuring Gource command line
            // ******************************************************

            arguments +=
                string.Format(CultureInfo.InvariantCulture, " --highlight-users --replacedle \"{0}\"", replacedle);

			if (m_settigs.ViewLogo != CheckState.Unchecked)
			{
				var logoFile = m_settigs.ViewLogo == CheckState.Indeterminate
					? Path.Combine(dataPath, "Logo.png")
					: m_settigs.LogoFileName;

				// fix gource unicode path problems
				logoFile = FileUtils.GetShortPath(logoFile);

				arguments += string.Format(CultureInfo.InvariantCulture, " --logo \"{0}\"", logoFile);
			}

            if (m_settigs.FullScreen)
            {
                arguments += " --fullscreen";

				// By default gource not using full area of screen width ( It's a bug. Must be fixed in gource 0.41).
				// Fixing fullscreen resolution to real full screen.
				if (!m_settigs.SetResolution)
				{
					var screenBounds = Screen.PrimaryScreen.Bounds;
					arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}", screenBounds.Width,
											   screenBounds.Height);
				}
			}

            if (m_settigs.SetResolution)
            {
                arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}",
                                           m_settigs.ResolutionWidth, m_settigs.ResolutionHeight);
            }

            if (m_settigs.ViewFilesExtentionMap)
            {
                arguments += " --key";
            }

			if (!string.IsNullOrEmpty(avatarsDirectory))
			{
				arguments += string.Format(CultureInfo.InvariantCulture, " --user-image-dir \"{0}\"", avatarsDirectory);
			}

            // Process "--hide" option
            {
                var hideItems = string.Empty;
                if (!m_settigs.ViewDirNames)
                {
                    hideItems = "dirnames";
                }
                if (!m_settigs.ViewFileNames)
                {
                    if (hideItems.Length > 0) hideItems += ",";
                    hideItems += "filenames";
                }
                if (!m_settigs.ViewUserNames)
                {
                    if (hideItems.Length > 0) hideItems += ",";
                    hideItems += "usernames";
                }

                if (hideItems.Length > 0)
                    arguments += " --hide " + hideItems;
            }

            arguments += " --max-files " + m_settigs.MaxFiles.ToString(CultureInfo.InvariantCulture);

			if (SystemInformation.TerminalServerSession)
			{
				arguments += " --disable-bloom";
			}

			if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
            {
                var si = new ProcessStartInfo(gourcePath, arguments)
                    {
                        WindowStyle = ProcessWindowStyle.Maximized,
 //                       UseShellExecute = true
					};

                Process.Start(si);
            }
            else
            {
                var logReader = new VersionControlLogReader(tfsCollectionUri, sourceControlFolder, m_settigs.UsersFilter,
                                                     m_settigs.FilesFilter);
                using (new WaitMessage("Connecting to Team Foundation Server..."))
                {
                    logReader.Connect();
                }

                System.Threading.Tasks.Task.Factory.StartNew(() => RunLiveChangesMonitor(logReader, gourcePath, arguments));
            }
        }

19 Source : HistoryViewer.cs
with MIT License
from aabiryukov

private static void RunLiveChangesMonitor(VersionControlLogReader reader, string gourcePath, string arguments)
	    {
			var gourceStartInfo = new ProcessStartInfo(gourcePath, arguments)
			{
				WindowStyle = ProcessWindowStyle.Maximized,
				RedirectStandardInput = true,
				UseShellExecute = false
			};

            var process = Process.Start(gourceStartInfo);

			if (process == null)
				throw new InvalidDataException("Failed to start process: " + gourceStartInfo.FileName);

	        using (var gourceWriter = new StreamWriter(process.StandardInput.BaseStream, Encoding.UTF8))
	        {
		        gourceWriter.AutoFlush = process.StandardInput.AutoFlush;
		        gourceWriter.NewLine = process.StandardInput.NewLine;

		        while (!process.HasExited)
		        {
			        var line = reader.ReadLine();
			        Debug.WriteLine("LOG: " + (line ?? "<NULL>"));
			        if (line == null)
			        {
				        // Waiting for second to avoid frequent server calls 
				        System.Threading.Thread.Sleep(1000);
			        }
			        else
			        {
						gourceWriter.WriteLine(line);
				        // System.Threading.Thread.Sleep(100);
			        }
		        }
	        }
        }

19 Source : Program.cs
with MIT License
from abanu-org

private static ProcessResult ExecAsync(CommandArgs args, bool redirect, Action<string, Process> onNewLine = null, TimeSpan? timeout = null)
        {
            if (!args.IsSet())
                return null;

            var fileName = args[0].GetEnv();
            var arguments = args.Pop(1).ToString().GetEnv();

            var start = new ProcessStartInfo(fileName);

            if (arguments.Length > 0)
                start.Arguments = arguments;

            if (redirect)
            {
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                start.RedirectStandardError = true;
                start.UseShellExecute = false;
            }

            Console.WriteLine(fileName + " " + arguments);

            var proc = Process.Start(start);
            var result = new ProcessResult(proc, timeout);

            if (redirect)
            {

                var th = new Thread(() =>
                {
                    var buf = new char[1];
                    var sb = new StringBuilder();
                    while (true)
                    {
                        var count = proc.StandardOutput.Read(buf, 0, 1);
                        if (count == 0)
                            break;
                        Console.Write(buf[0]);
                        if (buf[0] == '\n')
                        {
                            var line = sb.ToString();
                            onNewLine?.Invoke(line, proc);
                            sb.Clear();
                        }
                        else
                        {
                            if (buf[0] != '\r')
                                sb.Append(buf[0]);
                        }
                    }
                });
                th.Start();

                //var data = proc.StandardOutput.ReadToEnd();
                var error = proc.StandardError.ReadToEnd();
                //Console.WriteLine(data);
                Console.WriteLine(error);
            }

            return result;
        }

19 Source : SettingView.xaml.cs
with MIT License
from Abdesol

private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
            e.Handled = true;
        }

19 Source : VisualLineLinkText.cs
with MIT License
from Abdesol

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
														 Justification = "I've seen Process.Start throw undoreplacedented exceptions when the mail client / web browser is installed incorrectly")]
		protected internal override void OnMouseDown(MouseButtonEventArgs e)
		{
			if (e.ChangedButton == MouseButton.Left && !e.Handled && LinkIsClickable()) {
				RequestNavigateEventArgs args = new RequestNavigateEventArgs(this.NavigateUri, this.TargetName);
				args.RoutedEvent = Hyperlink.RequestNavigateEvent;
				FrameworkElement element = e.Source as FrameworkElement;
				if (element != null) {
					// allow user code to handle the navigation request
					element.RaiseEvent(args);
				}
				if (!args.Handled) {
					try {
						Process.Start(new ProcessStartInfo { FileName = this.NavigateUri.ToString(), UseShellExecute = true });
					} catch {
						// ignore all kinds of errors during web browser start
					}
				}
				e.Handled = true;
			}
		}

19 Source : OVRADBTool.cs
with MIT License
from absurd-joy

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

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

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

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

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

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

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

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

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

		exitCode = process.ExitCode;

		process.Close();

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

		outputStringBuilder = null;
		errorStringBuilder = null;

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

		return exitCode;
	}

19 Source : OVRADBTool.cs
with MIT License
from absurd-joy

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

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

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

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

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

		return process;
	}

19 Source : SourceTipsView.xaml.cs
with MIT License
from ABTSoftware

private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            Process.Start("explorer.exe", Urls.GithubRootUrl);
        }

19 Source : Splash.xaml.cs
with MIT License
from ABTSoftware

private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            Process.Start("explorer.exe", Urls.ReleaseArticle);
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public void ExportActual(WriteableBitmap actualBitmap, string fileName)
        {
            if (!Directory.Exists(ExportActualPath))
            {
                Directory.CreateDirectory(ExportActualPath);
            }

            var pathString = Path.Combine(ExportActualPath, fileName);

            if (Path.GetExtension(fileName).ToUpper() == ".BMP")
            {
                SaveToBmp(pathString, actualBitmap);
            }
            else
            {
                SaveToPng(pathString, actualBitmap);
            }

            ProcessStartInfo startInfo = new ProcessStartInfo(pathString);
            Process.Start(startInfo);
        }

19 Source : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
with MIT License
from ABTSoftware

private void RunExportExampleTest(ExampleStartTestCase testCase)
        {
            return;

            // Useful UIAutomation Ids

            // ExportExampleView
            // ExportExampleView.ExportPathTextBox
            // ExportExampleView.ExportButton
            // ExportExampleView.CloseButton
            // ExampleView.Export

            // Toggle the export button, this shows ExportExampleView
            var exportButton = _mainWindow.FindFirstDescendant("ExampleView.Export").AsToggleButton();
            exportButton?.Toggle();

            string exportPath = base.GetTemporaryDirectory();
            try
            {
                var exampleExportView = WaitForElement(() => _mainWindow.FindFirstDescendant("ExportExampleView"));
                var exampleExportTextBox = exampleExportView.FindFirstDescendant("ExportExampleView.ExportPathTextBox")
                    .AsTextBox();
                var exampleExportButton =
                    exampleExportView.FindFirstDescendant("ExportExampleView.ExportButton").AsButton();
                var exampleExportCloseButton =
                    exampleExportView.FindFirstDescendant("ExportExampleView.CloseButton").AsButton();

                // Set output path and export 
                exampleExportTextBox.Text = exportPath;
                exampleExportButton.Invoke();

                // Get the messagebox, close it 
                var msg = WaitForElement(() => _mainWindow.ModalWindows.FirstOrDefault().AsWindow());
                var yesButton = msg.FindFirstChild(cf => cf.ByName("OK")).AsButton();
                yesButton.Invoke();

                // Close example export view
                exampleExportCloseButton?.Invoke();

                // Now check the example
                var subDir = Directory.GetDirectories(exportPath).First();
                var projectFile = Directory.GetFiles(subDir, "*.sln").FirstOrDefault();

                // MSBuild
                //fs.WriteLine("@echo Building " + projectName);
                //fs.WriteLine(@"call ""C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe"" /ToolsVersion:12.0 /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
                string msBuildPath = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe";
                var msBuildProcess = Process.Start(new ProcessStartInfo(msBuildPath,
                    $"/ToolsVersion:Current /p:Configuration=\"Debug\" \"{projectFile}\" /t:Restore;Build /p:WarningLevel=0"));
                msBuildProcess.WaitForExit(10000);
                replacedert.That(msBuildProcess.ExitCode, Is.EqualTo(0), $"Failed to build example {testCase.Category}/{testCase.Group}/{testCase.Example}");
            }
            finally
            {
                Directory.Delete(exportPath, true);
            }
        }

19 Source : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
with MIT License
from ABTSoftware

private void RunScreenshotTest(ExampleStartTestCase testCase)
        {
            var exampleView = WaitForElement(() => _mainWindow.FindFirstDescendant("ExampleView.TransitioningFrame"));
            if (exampleView == null)
            {
                replacedert.Fail("Unable to get ExampleView");
            }
            var userControlNotFrame = exampleView.FindFirstByXPath($"Custom");

            // Capture a screenshot & compare
            using (var capture = Capture.Element(userControlNotFrame))
            {
                var actualBitmap = new WriteableBitmap(capture.BitmapImage);

                //#if DEBUG
                // When true, we export the image and open in Paint for test purposes. 
                // Save this image in resources, as embedded resource, then set flag exportActualForTest=false for the actual test
                if (testCase.ExportActual)
                {
                    var pathString = Path.Combine(ExportActualPath, testCase.ResourceName);
                    base.SaveToPng(pathString, actualBitmap);

                    // Export the actual 
                    ProcessStartInfo startInfo = new ProcessStartInfo(pathString);
                    Process.Start(startInfo);
                }
                //#endif

                WriteableBitmap expectedBitmap = null;
                try
                {
                    expectedBitmap = this.LoadResource(testCase.ResourceName);
                }
                catch (Exception caught)
                {
                    throw new Exception("Unable to load image from resource " + testCase.ResourceName, caught);
                }
                replacedert.True(CompareBitmaps(testCase.ResourceName, actualBitmap, expectedBitmap, testCase.Tolerance));
            }
        }

19 Source : ExceptionHandler.cs
with MIT License
from Accelerider

private void Log(Exception exception)
        {
            Logger.Fatal("An uncaught exception occurred", exception);

            if (_isShowed) return;

            _isShowed = true;
            switch (exception)
            {
                case NotImplementedException _:
                    MessageBox.Show(
                        "Sorry! The feature has NOT been IMPLEMENTED. Please wait for the next version. ",
                        "Fatal",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                    break;
                case NotSupportedException _:
                    MessageBox.Show(
                        "Sorry! The feature has NOT been SUPPORTED. Please wait for the next version. ",
                        "Fatal",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                    break;
                default:
                    var result = MessageBox.Show(
                        $"Sorry! An uncaught EXCEPTION occurred. {Environment.NewLine}" +
                        $"You can pack and send log files in %AppData%\\Accelerider\\Logs to the developer. Thank you! {Environment.NewLine}{Environment.NewLine}" +
                        $"Do you want to open the Logs folder? ",
                        "Fatal",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Error);

                    if (result == MessageBoxResult.Yes)
                    {
                        Process.Start(AcceleriderFolders.Logs);
                    }

                    break;
            }

            ProcessController.Restart(-1);
        }

19 Source : TippingManager.cs
with MIT License
from acid-chicken

public static async Task<string> InvokeMethodAsync(params object[] args)
        {
            using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }))
            using (var reader = process.StandardOutput)
            {
                var output = await reader.ReadToEndAsync().ConfigureAwait(false);
                process.WaitForExit();
                process.Close();
                return output.Trim();
            }
        }

19 Source : AboutViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static void NavigateTo(System.Uri url)
        {
            Process.Start(new ProcessStartInfo(url.AbsoluteUri));
        }

19 Source : UpgradeViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static void OpenChangeLog()
        {
            System.Diagnostics.Process.Start(Constants.ChangelogLink);
        }

19 Source : ConsoleUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

[SecurityCritical]
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        internal static void StartHiddenConsoleProg(string exePath, string args, int waitTime)
        {
            var startInfo = new ProcessStartInfo();
            startInfo.FileName = exePath;

            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            if (!string.IsNullOrEmpty(args))
            {
                startInfo.Arguments = args;
            }
            Process p = Process.Start(startInfo);
            p.WaitForExit(waitTime);
            p.Dispose();
        }

19 Source : FileUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

[SecurityCritical]
        internal static void EditConfigFile(Doreplacedent doc)
        {
            var config = Manager.GetConfigFileName(doc);
            if (File.Exists(config)) {
                var process = Process.Start(Settings1.Default.TextEditor, config);
                process.Dispose();
            } else {
                SCaddinsApp.WindowManager.ShowMessageBox("SCexport", "config file does not exist");
            }
        }

19 Source : FileUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

[SecurityCritical]
        internal static void EditConfigFileModal(Doreplacedent doc)
        {
            var config = Manager.GetConfigFileName(doc);
            if (File.Exists(config))
            {
                var process = Process.Start(Settings1.Default.TextEditor, config);
                process.WaitForExit();
                process.Dispose();
            }
            else
            {
                SCaddinsApp.WindowManager.ShowMessageBox("SCexport", "config file does not exist");
            }
        }

19 Source : ProcessExtensionL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task SuccessReadProcessEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                string envName = Guid.NewGuid().ToString();
                string envValue = Guid.NewGuid().ToString();

                Process sleep = null;
                try
                {
#if OS_WINDOWS
                    string node = Path.Combine(TestUtil.GetSrcPath(), @"..\_layout\externals\node12\bin\node");
#else
                    string node = Path.Combine(TestUtil.GetSrcPath(), @"../_layout/externals/node12/bin/node");
                    hc.EnqueueInstance<IProcessInvoker>(new ProcessInvokerWrapper());
#endif
                    var startInfo = new ProcessStartInfo(node, "-e \"setTimeout(function(){{}}, 15 * 1000);\"");
                    startInfo.Environment[envName] = envValue;
                    sleep = Process.Start(startInfo);

                    var timeout = Process.GetProcessById(sleep.Id);
                    while (timeout == null)
                    {
                        await Task.Delay(500);
                        timeout = Process.GetProcessById(sleep.Id);
                    }

                    try
                    {
                        trace.Info($"Read env from {timeout.Id}");
                        var value = timeout.GetEnvironmentVariable(hc, envName);
                        if (string.Equals(value, envValue, StringComparison.OrdinalIgnoreCase))
                        {
                            trace.Info($"Find the env.");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        trace.Error(ex);
                    }

                    replacedert.True(false, "Fail to retrive process environment variable.");
                }
                finally
                {
                    sleep?.Kill();
                }
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1]+@")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {
            var psi = new ProcessStartInfo();
            psi.FileName = args[0];
            var script = args[1];
            var imageLocations = args[2].Split('|');

            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            var errors = "";
            var results = "";

            foreach (var location in imageLocations)
            {
                psi.Arguments = $"\"{script}\",\"{location}\"";

                using (var process = Process.Start(psi))
                {
                    errors = process.StandardError.ReadToEnd();
                    results = process.StandardOutput.ReadToEnd();
                }

                Console.WriteLine("ERRORS:");
                Console.WriteLine(errors);
                Console.WriteLine();
                Console.WriteLine("Results:");
                Console.WriteLine(results);
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {

            var psi = new ProcessStartInfo();
            psi.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
            var script = @"C:\Users\rajiyer\Doreplacedents\Projects\AI\Base\src\ActuarialIntelligence.Infrastructure.PythonScripts\Recommendation.py";
            psi.Arguments = $"\"{script}\"";
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            var errors = "";
            var results = "";
            using (var process = Process.Start(psi))
            {
                errors = process.StandardError.ReadToEnd();
                results = process.StandardOutput.ReadToEnd();
            }

            // 5) Display output
            Console.WriteLine("ERRORS:");
            Console.WriteLine(errors);
            Console.WriteLine();
            Console.WriteLine("Results:");
            Console.WriteLine(results);


        }

19 Source : ValuesController.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

[HttpPost("TestRunPython")]
        public ActionResult<string> TestRunPython()
        {
            var psi = new ProcessStartInfo();
            psi.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
            var script = @"C:\Users\rajiyer\Doreplacedents\Projects\AI\Base\src\ActuarialIntelligence.Infrastructure.PythonScripts\LogisticRegression.py";
            psi.Arguments = $"\"{script}\"";
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            var errors = "";
            var results = "";
            using (var process = Process.Start(psi))
            {
                errors = process.StandardError.ReadToEnd();
                results = process.StandardOutput.ReadToEnd();
            }
            return results;
        }

19 Source : MainWindow.cs
with MIT License
from adainrivers

private void UpdateNotification_Click(object sender, EventArgs e)
        {
            var link = UpdateNotification.Tag.ToString();
            if (link != null && link.StartsWith("https://"))
            {
                var psInfo = new ProcessStartInfo
                {
                    FileName = link,
                    UseShellExecute = true
                };
                Process.Start(psInfo);
            }
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

private static Process Execute(string executable)
        {
            var startInfo = new ProcessStartInfo(executable)
            {
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
            };

            return Process.Start(startInfo);
        }

See More Examples