Exemple #1
0
        static void Main(string[] args)
        {
            try
            {
                if (args == null || args.Length == 0)
                {
                    Console.WriteLine($"Invalid argument!");
                    return;
                }

                var cleaned = args.Select(x => x.Trim()).ToArray();
                var program = cleaned.FirstOrDefault();

                if (string.IsNullOrEmpty(program))
                {
                    Console.WriteLine($"Invalid program!");
                    return;
                }
                var arguments = string.Join(" ", cleaned.Skip(1));


                var sInfo = new System.Diagnostics.ProcessStartInfo
                {
                    UseShellExecute = false,
                    //FileName = @"C:\Program Files\ladybug_tools\python\python.exe",
                    //Arguments = @"-m pip install ladybug-rhino",
                    FileName  = program,
                    Arguments = arguments,
                    //Arguments = @"-m ladybug-rhino change-installed-version [OPTIONS]",
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    //CreateNoWindow = true,
                };

                Console.WriteLine($"{sInfo.FileName} {sInfo.Arguments}");

                var p = new System.Diagnostics.Process();
                p.StartInfo = sInfo;


                p.ErrorDataReceived  += P_ErrorDataReceived;
                p.OutputDataReceived += P_OutputDataReceived;
                p.Start();

                // To avoid deadlocks, use an asynchronous read operation on at least one of the streams.
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();

                p.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("Press any key to close!");
                Console.ReadKey();
            }
        }
Exemple #2
0
        string RunProcess(string file, string args, Stream stdinStream = null)
        {
            var sbOut = new StringBuilder();

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

            p.StartInfo = new System.Diagnostics.ProcessStartInfo(file, args);
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            if (stdinStream != null)
            {
                p.StartInfo.RedirectStandardInput = true;
            }
            p.StartInfo.CreateNoWindow = true;
            p.OutputDataReceived      += (sender, e) =>
            {
                sbOut.Append(e.Data);
            };

            p.Start();
            p.BeginOutputReadLine();

            if (stdinStream != null)
            {
                stdinStream.CopyTo(p.StandardInput.BaseStream);
                p.StandardInput.Close();
            }

            p.WaitForExit();

            return(sbOut.ToString());
        }
        /// <summary>
        /// Pythonの環境設定をする
        /// </summary>
        public static void StartUpPython()
        {
            Process = new System.Diagnostics.Process();
            Process.StartInfo.UseShellExecute        = false;
            Process.StartInfo.RedirectStandardInput  = true;
            Process.StartInfo.RedirectStandardOutput = true;
            Process.StartInfo.RedirectStandardError  = true;
            Process.OutputDataReceived += p_OutputDataReceived;
            Process.ErrorDataReceived  += p_ErrorDataReceived;

            Process.StartInfo.FileName =
                System.Environment.GetEnvironmentVariable("ComSpec");
            Process.StartInfo.CreateNoWindow = true;

            Process.Start();

            Process.BeginOutputReadLine();
            Process.BeginErrorReadLine();
            StreamWriter = Process.StandardInput;
            if (StreamWriter.BaseStream.CanWrite)
            {
                StreamWriter.WriteLine(MySettings.GetInstance().AnacondaPath);
                StreamWriter.WriteLine(@"activate " + MySettings.GetInstance().AnacondaEnv);
            }
        }
Exemple #4
0
        public static void RunCommandTillEnd(string filename, string arguments, List <string> stdout, List <string> stderr, Logger logger)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            process.StartInfo.FileName  = filename;
            process.StartInfo.Arguments = arguments;

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

            process.OutputDataReceived += (sender, eventArgs) => CommandOutputReceived(sender, eventArgs, stdout);
            process.ErrorDataReceived  += (sender, eventArgs) => CommandOutputReceived(sender, eventArgs, stderr);

            logger.Log("Abbout to start: {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            try
            {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
            }
            catch (Exception e)
            {
                logger.Log("Got an exception while starting the process");
                logger.Log(e.ToString());

                return;
            }

            process.WaitForExit();
        }
Exemple #5
0
        public static void Run(string host, int port)
        {
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            client.SendTimeout    = 50000000;
            client.ReceiveTimeout = 50000000;
            client.Connect(host, port);
            System.IO.Stream       stream       = client.GetStream();
            System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
            streamWriter = new System.IO.StreamWriter(stream);

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName               = "cmd.exe";
            p.StartInfo.Arguments              = "";
            p.StartInfo.CreateNoWindow         = true;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.RedirectStandardError  = true;
            p.OutputDataReceived              += new System.Diagnostics.DataReceivedEventHandler(OnOutputDataReceived);
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnErrorDataReceived);
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            while (true)
            {
                p.StandardInput.WriteLine(streamReader.ReadLine());
            }
        }
Exemple #6
0
    static void Main(string[] args)
    {
        // Create the process
        var process = new System.Diagnostics.Process();

        process.EnableRaisingEvents              = true;
        process.StartInfo.UseShellExecute        = false;
        process.StartInfo.FileName               = "php.exe";
        process.StartInfo.Arguments              = "-f path\\test.php mu b 0 0 pgsql://user:[email protected]:5432/nominatim";
        process.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
        process.StartInfo.RedirectStandardOutput = true;

        output = new StringBuilder();
        process.OutputDataReceived += process_OutputDataReceived;

        // Start the process
        process.Start();
        process.BeginOutputReadLine();

        // Wait for the process to finish
        process.WaitForExit();

        Console.WriteLine("test");
        // <-- do something with Program.output here -->

        Console.ReadKey();
    }
Exemple #7
0
        public void Execute(IWin32Window owner, string command, string param)
        {
            Show(owner);
            textBoxLogs.AppendText($"> {command} {param}\r\n\r\n");

            //エントリポイント
            //Processオブジェクトを作成
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            //出力とエラーをストリームに書き込むようにする
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.EnableRaisingEvents = true;
            //OutputDataReceivedとErrorDataReceivedイベントハンドラを追加
            p.OutputDataReceived += p_OutputDataReceived;
            p.ErrorDataReceived  += p_ErrorDataReceived;
            p.Exited             += p_Exited;

            p.StartInfo.FileName = command;
            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.CreateNoWindow        = true;
            p.StartInfo.Arguments             = param;

            //起動
            p.Start();
            _executing = p;

            //非同期で出力とエラーの読み取りを開始
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
        }
Exemple #8
0
        public void Start(string arguments)
        {
            Stop();

            process = new System.Diagnostics.Process();

            process.StartInfo.FileName        = filename;
            process.StartInfo.Arguments       = arguments;
            process.StartInfo.UseShellExecute = false;

            process.StartInfo.CreateNoWindow = true;

            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardOutput = true;

            ClearOutput();

            process.OutputDataReceived += delegate(object sender, System.Diagnostics.DataReceivedEventArgs e) {
                lock (output_lock)
                    output_buffer.Add(e.Data);
            };

            process.Start();
            process.BeginOutputReadLine();
        }
Exemple #9
0
        static string execute_shell(string p_working_directory, string p_file_path, string p_arguments)
        {
            System.Text.StringBuilder process_output_builder = new System.Text.StringBuilder();
            string result = null;


            Action <object, System.Diagnostics.DataReceivedEventArgs> actionWrite = (sender, e) => {
                process_output_builder.AppendLine(e.Data);
            };

            System.Diagnostics.Process proc = new System.Diagnostics.Process();

            proc.StartInfo.WorkingDirectory       = p_working_directory;
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.FileName  = p_file_path;
            proc.StartInfo.Arguments = p_arguments;

            proc.ErrorDataReceived  += (sender, e) => actionWrite(sender, e);
            proc.OutputDataReceived += (sender, e) => actionWrite(sender, e);
            proc.EnableRaisingEvents = true;
            proc.Start();
            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();
            proc.WaitForExit();



            return(result);
        }
Exemple #10
0
        static void runConvertProcess(string input, string output, bool waitExit)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.WorkingDirectory       = Path.ExecutableDirectory;
            proc.StartInfo.CreateNoWindow         = true;
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(ErrorDataReceived);
            proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputDataReceived);
            proc.StartInfo.FileName  = Path.Tools.ReplacerFile;
            proc.StartInfo.Arguments = "\"" + input + "\" \"" + output + "\"";

            proc.Start();

            // waitしないと多分終了コードは取ってる余裕が無いだろうがwaitすると遅いんだよな
            if (waitExit)
            {
                proc.WaitForExit();
#if false
                if (proc.HasExited)
                {
                    System.Console.WriteLine("[ExitCode] " + proc.ExitCode);
                }
#endif
            }
#if false
            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine(); // std::cerr or std::clog 使ったら出力される
#endif
        }
Exemple #11
0
        /// <summary>
        /// Run a shell command.
        /// </summary>
        /// <param name="fileName">File name for the executable.</param>
        /// <param name="arguments">Command line arguments, space delimited.</param>
        /// <param name="output">Filled out with the result as printed to stdout.</param>
        /// <param name="error">Filled out with the result as printed to stderr.</param>
        public static void RunCommand(string fileName, string arguments, out string output, out string error)
        {
            using (var process = new System.Diagnostics.Process())
            {
                var startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
                startInfo.UseShellExecute        = false;
                startInfo.RedirectStandardError  = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow         = true;
                process.StartInfo = startInfo;

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

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

                // Trims the output strings to make comparison easier.
                output = outputBuilder.ToString().Trim();
                error  = errorBuilder.ToString().Trim();
            }
        }
        public override void Handle(TemplateAction action)
        {
            _process.Logger.Info("Running {0}.", action.File);

            var fileInfo = new FileInfo(action.File);

            if (fileInfo.Exists)
            {
                var executable = new System.Diagnostics.Process {
                    StartInfo =
                    {
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        FileName       = fileInfo.FullName,
                        Arguments      = action.Arguments,
                        CreateNoWindow = true
                    }
                };

                executable.OutputDataReceived += (sender, args) => _process.Logger.Info(args.Data);
                executable.Start();
                executable.BeginOutputReadLine();
                executable.WaitForExit();
            }
            else
            {
                _process.Logger.Warn("Couldn't find and execute {0}.", action.File);
            }
        }
        private static void DoIt()
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.ErrorDataReceived  += Proc_ErrorDataReceived;
            proc.OutputDataReceived += Proc_OutputDataReceived;
            proc.Exited             += Proc_Exited;

            proc.StartInfo.FileName               = @"c:\windows\syswow64\psexec_64.exe";
            proc.StartInfo.Arguments              = @"-i -u usr -p pwd \\server -c M:\StackOverflowQuestionsAndAnswers\PSExec_42280413\PSExec_42280413\TheBatFile.bat";
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.RedirectStandardInput  = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute        = false;
            proc.EnableRaisingEvents              = true;
            proc.Start();
            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();

            //if the process runs too quickly, the event don't have time to raise and the application exits.
            //this here takes care of slooowwwwwiiinnnnnggggg things down
            //there are more elegant ways to wait and it does not have to be this long
            Int64 bigone = 200000000;

            while (bigone > 0)
            {
                bigone--;
            }
        }
Exemple #14
0
        /// <summary>
        /// 読み取り開始
        /// </summary>
        public void Read()
        {
            Console.WriteLine("FelicaReader::Read() - start");
            //  プロセスオブジェクトを生成
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            //  実行ファイルを指定
            p.StartInfo.FileName = this.tagtool;
            //  シェルコマンドを無効に
            p.StartInfo.UseShellExecute = false;
            //  入力をリダイレクト
            p.StartInfo.RedirectStandardInput = true;
            //  出力をリダイレクト
            p.StartInfo.RedirectStandardOutput = true;
            //  OutputDataReceivedイベントハンドラを追加
            p.OutputDataReceived += OutputDataReceivedHandler;
            //  プロセスを実行
            p.Start();
            //  非同期で出力の読み取りを開始
            p.BeginOutputReadLine();
            //  入力を行う為のストリームライターとプロセスの標準入力をリンク
            System.IO.StreamWriter myStreamWriter = p.StandardInput;

            myStreamWriter.Close();
            p.WaitForExit();
            p.Close();
            Console.WriteLine("FelicaReader::Read() - end");
        }
Exemple #15
0
        private void getVoicesInEditor()
        {
#if UNITY_STANDALONE || UNITY_EDITOR
            cachedVoices.Clear();

            System.Diagnostics.Process voicesProcess = new System.Diagnostics.Process();

            voicesProcess.StartInfo.FileName  = Util.Config.TTS_LINUX;
            voicesProcess.StartInfo.Arguments = "--voices" + (string.IsNullOrEmpty(Util.Config.TTS_LINUX_DATA) ? string.Empty : " --path=\"" + Util.Config.TTS_LINUX_DATA + '"');

            voicesProcess.StartInfo.CreateNoWindow         = true;
            voicesProcess.StartInfo.RedirectStandardOutput = true;
            voicesProcess.StartInfo.RedirectStandardError  = true;
            voicesProcess.StartInfo.UseShellExecute        = false;
            voicesProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
            voicesProcess.OutputDataReceived += process_OutputDataReceived;

            try
            {
                long time = System.DateTime.Now.Ticks;

                voicesProcess.Start();
                voicesProcess.BeginOutputReadLine();

                do
                {
                    System.Threading.Thread.Sleep(50);
                } while (!voicesProcess.HasExited);

                if (Util.Constants.DEV_DEBUG)
                {
                    Debug.Log("Finished after: " + ((System.DateTime.Now.Ticks - time) / 10000000));
                }

                if (voicesProcess.ExitCode == 0)
                {
                    if (Util.Constants.DEV_DEBUG)
                    {
                        Debug.Log("Voices read: " + cachedVoices.CTDump());
                    }
                }
                else
                {
                    using (System.IO.StreamReader sr = voicesProcess.StandardError)
                    {
                        string errorMessage = "Could not get any voices: " + voicesProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                        Debug.LogError(errorMessage);
                    }
                }
            }
            catch (System.Exception ex)
            {
                string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex;
                Debug.LogError(errorMessage);
            }

            voicesProcess.Dispose();
#endif
            onVoicesReady();
        }
Exemple #16
0
        public bool Do(string iPath)
        {
            try
            {
                var outDir = System.IO.Path.GetDirectoryName(iPath);

                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo
                {
                    UseShellExecute = false,
                    CreateNoWindow  = true,

                    WorkingDirectory = AceUtil.Path,
                    FileName         = "ace.cmd",

                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                };

                var arg = string.Format(" \"{0}\" --force --subdir --outdir \"{1}\"", iPath, outDir);
                psi.Arguments = arg;
                Console.WriteLine(arg);

                using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi))
                {
                    // OutputDataReceivedとErrorDataReceivedイベントハンドラを追加
                    p.OutputDataReceived += this.P_OutputDataReceived;
                    p.ErrorDataReceived  += this.P_ErrorDataReceived;

                    try
                    {
                        // 非同期で出力とエラーの読み取りを開始
                        p.BeginOutputReadLine();
                        p.BeginErrorReadLine();
                    }
                    catch
                    {
                        this.OutputError.Add("結果取得に 失敗 @DoAceFor");
                        Console.WriteLine(@"結果取得に 失敗");
                    }

                    // WaitForExitはReadToEndの後である必要がある (親プロセス、子プロセスでブロック防止のため)
                    p.WaitForExit();
                    this.StatusCode = p.ExitCode;
                }
            }
            catch (Exception ex_psi)
            {
                this.OutputError.Clear();
                this.OutputError.Add("Ace コマンド 失敗 @DoJavaJarFor");

                Console.WriteLine(@"Ace コマンド 失敗");
                Console.WriteLine(ex_psi.ToString());
                return(false);
            }

            Console.WriteLine(string.Join("\r\n", this.OutputError));
            Console.WriteLine(string.Join("\r\n", this.OutputStandard));

            return(true);
        }
        public static bool ExecuteProcess(System.Diagnostics.ProcessStartInfo si)
        {
            si.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
            si.UseShellExecute        = false;
            si.RedirectStandardOutput = true;
            si.RedirectStandardError  = true;
            si.CreateNoWindow         = true;

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

            process.StartInfo = si;

            process.OutputDataReceived += (s, e) => WriteProcessOutput(s as System.Diagnostics.Process, e.Data, false);

            process.ErrorDataReceived += (s, e) => WriteProcessOutput(s as System.Diagnostics.Process, e.Data, true);

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

            if (process.ExitCode != 0)
            {
                Debug.LogErrorFormat("Error when execute process {0} {1}", si.FileName, si.Arguments);
                return(false);
            }
            else
            {
                return(true);
            }
        }
        public string Run(string arguments)
        {
            System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("ffprobe.exe", arguments);
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute        = false;
            processStartInfo.CreateNoWindow         = true;

            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                process.StartInfo = processStartInfo;

                StringBuilder sb = new StringBuilder();
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data))
                                                          {
                                                              sb.AppendLine(e.Data);
                                                          }
                };
                process.ErrorDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data))
                                                         {
                                                             sb.AppendLine(e.Data);
                                                         }
                };

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

                return(sb.ToString());
            }
        }
        //CheckEpubを実施、Output/Errorを表示する
        public void CheckEpub()
        {
            //EPUBチェック実施中パネルを表示する
            var checkingDlg = new EpubCheckingDialog();
            checkingDlg.Show();

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

            //実行ファイル
            p.StartInfo.FileName = javaPath;

            //引数
            var args = "-jar "
                        + "\""+ epubCheckPath + "\" "
                        +" \"" + epubPath + "\"";
            p.StartInfo.Arguments = args;

            //出力とエラーをストリームに書き込むようにする
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            //OutputDataReceivedとErrorDataReceivedイベントハンドラを追加
            p.OutputDataReceived += OutputDataReceived;
            p.ErrorDataReceived += ErrorDataReceived;

            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.CreateNoWindow = true;

            p.Start();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            p.WaitForExit();
            p.Close();

            var resultDlg = new EpubCheckResultDialog();

            //Outputをコピーする
            foreach (var output in outputLines)
            {
                resultDlg.outputTextBox.Text += (output + "\n");
            }

            //Errorをコピーする
            if (errorLines.Count> 1)
            {
                foreach (var error in errorLines)
                {
                    resultDlg.errorTextBox.Text += (error + "\n");
                }
            }
            else
            {
                resultDlg.errorTextBox.Text = "エラーはありませんでした。";
            }
            checkingDlg.Close();
            resultDlg.ShowDialog();
        }
Exemple #20
0
        /// <summary>
        /// Starts the python process to run the script.
        /// </summary>
        /// <param name="sCommand"></param>
        private void StartProcess(string sCommand)
        {
            object oMissing    = "";
            string sPythonPath = "";

            clsStatic.Platform myPlatform = clsStatic.GetPlatform();
            switch (myPlatform)
            {
            case clsStatic.Platform.X64:
                sPythonPath = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\ESRI\\Python10.0", "PythonDir", "");
                break;

            default:
                sPythonPath = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\ESRI\\Python10.0", "PythonDir", "");
                break;
            }

            System.Diagnostics.ProcessStartInfo procStartInfo = new
                                                                System.Diagnostics.ProcessStartInfo("\"" + sPythonPath + "ArcGIS10.0\\python.exe\"");

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute        = false;
            procStartInfo.CreateNoWindow         = true;
            procStartInfo.Arguments = sCommand; //sCommand + " \"" + sSettingPath + sSettingsFile + "\""
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo           = procStartInfo;
            proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
            proc.Start();
            proc.BeginOutputReadLine();
            proc.WaitForExit();
            //m_pProcessOutput.Dispose();
            //m_pProcessOutput = null;
        }
Exemple #21
0
        }     // End Sub ProcessExited

        private void Form1_Load(object sender, EventArgs e)
        {
            spdTerminal = new System.Diagnostics.Process();

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                //spdTerminal.StartInfo.FileName = "/usr/bin/gnome-terminal";
                spdTerminal.StartInfo.FileName = "/bin/bash";
            }
            else
            {
                spdTerminal.StartInfo.FileName = "cmd.exe";
            }

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

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

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

            spdTerminal.Start();

            swInputStream = spdTerminal.StandardInput;
            spdTerminal.BeginOutputReadLine();
            spdTerminal.BeginErrorReadLine();
        } // End Sub Form1_Load
Exemple #22
0
        protected override string RunScript(string vbscmd)
        {
            DataBuffer  = "";
            ErrorBuffer = "";

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.CreateNoWindow         = true;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.StartInfo.FileName         = @"cscript";
            p.OutputDataReceived        += (proc, outLine) => { AddData(outLine.Data); };
            p.ErrorDataReceived         += (proc, outLine) => { AddError(outLine.Data); };
            p.Exited                    += Process_Exited;
            p.StartInfo.WorkingDirectory = mActVBS.ScriptPath;
            try
            {
                p.StartInfo.Arguments = mActVBS.ScriptName + " " + vbscmd;;
            }
            catch (Exception e)
            {
                Reporter.ToLog(eLogLevel.ERROR, e.Message);
            }
            p.Start();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            while (!p.HasExited)
            {
                Thread.Sleep(100);
            }
            return(DataBuffer);
        }
Exemple #23
0
        private static Dictionary <string, SteamData> TryFindSteamData(FileInfo steamCMD, out long[] missingAppIds, params long[] appIds)
        {
            var stringWriter = new StringWriter();

            using (var process = new Process())
            {
                process.StartInfo.FileName               = steamCMD.FullName;
                process.StartInfo.Arguments              = $" +login anonymous {string.Join(" ", appIds.Select(appId => $"+app_info_print {appId}"))} +exit";
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.Start();

                process.OutputDataReceived += (sender, eventArgs) => stringWriter.WriteLine(eventArgs.Data);
                process.BeginOutputReadLine();

                process.WaitForExit();
            }

            var allOutput  = stringWriter.ToString();
            var firstIndex = allOutput.IndexOf("\"");
            var lastIndex  = allOutput.LastIndexOf("}");

            missingAppIds = ExtractMissingAppIds(allOutput);

            if (firstIndex > -1 && lastIndex > -1)
            {
                var appInfoPrintAsJson = TransformAppInfoPrintLangToJson(allOutput.Substring(firstIndex, lastIndex - firstIndex + 1));
                return(JsonSerializer.Deserialize <Dictionary <string, SteamData> >(appInfoPrintAsJson, JsonOptions));
            }
            else
            {
                return(new Dictionary <string, SteamData>());
            }
        }
Exemple #24
0
        public virtual RESULT_PROCESS exec(string[] args)
        {
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.CreateNoWindow         = true;
            startInfo.UseShellExecute        = false;
            startInfo.FileName               = string.Join(@"", new string[] { Util.ExecutableDirectory(), _exe });
            startInfo.Arguments              = args.ToString().Length != -1 ? args.ToString() : string.Empty;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardInput  = true;

            using (System.Diagnostics.Process execute = System.Diagnostics.Process.Start(startInfo))
            {
                try
                {
                    execute.EnableRaisingEvents = true;
                    execute.OutputDataReceived += execute_OutputDataReceived;
                    execute.ErrorDataReceived  += execute_ErrorDataReceived;
                    execute.Exited += execute_Exited;
                    execute.Start();
                    execute.BeginErrorReadLine();
                    execute.BeginOutputReadLine();
                }
                finally {
                    execute.WaitForExit();
                }
                return(result);
            }
        }
Exemple #25
0
        static System.Diagnostics.Process RunCommand(System.Diagnostics.ProcessStartInfo startInfo, bool allowFail = false)
        {
            System.Console.WriteLine($"Running '{startInfo.FileName} {startInfo.Arguments}'");

            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;

            var proc = new System.Diagnostics.Process {
                StartInfo = startInfo,
            };

            proc.OutputDataReceived += (sender, e) => System.Console.WriteLine(e.Data);
            proc.ErrorDataReceived  += (sender, e) => System.Console.WriteLine(e.Data);

            try {
                proc.Start();
            } catch (System.Exception err) {
                System.Console.WriteLine(err.Message);
                WaitAndExit(1);
            }

            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();
            proc.WaitForExit();

            if (!allowFail && proc.ExitCode > 0)
            {
                System.Console.WriteLine($"Command exited with code {proc.ExitCode}");
                WaitAndExit(proc.ExitCode);
            }

            return(proc);
        }
Exemple #26
0
        // Execute the AssembleNET application on the command line
        void RunEngineExternal()
        {
            try
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();

                proc.StartInfo.FileName               = fullAssemblePath;
                proc.StartInfo.Arguments              = mapSrcLocation + " " + mapDstLocation + " " + engineFullPath;
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError  = true;

                proc.OutputDataReceived += OutputHandler;
                proc.ErrorDataReceived  += OutputHandler;
                proc.EnableRaisingEvents = true;

                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
            }
        }
Exemple #27
0
        public void build(string arguments)
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = variables.pathforit + @"\xeBuild\xeBuild.exe";

            if (variables.debugme)
            {
                Console.WriteLine(variables.pathforit);
            }
            if (variables.debugme)
            {
                Console.WriteLine("---" + variables.pathforit + @"\xeBuild\xeBuild.exe");
            }
            if (variables.debugme)
            {
                Console.WriteLine(arguments);
            }
            pProcess.StartInfo.Arguments              = arguments;
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.WorkingDirectory       = variables.pathforit;
            pProcess.StartInfo.RedirectStandardInput  = true;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow         = true;
            pProcess.Exited += new EventHandler(xeExit);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(DataReceived);
            //pProcess.Exited += new EventHandler(xe_Exited);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
            try
            {
                AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
                pProcess.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        Console.WriteLine(e.Data);
                        if (e.Data != null && e.Data.Contains("image built"))
                        {
                            variables.xefinished = true;
                        }
                    }
                };
                pProcess.Start();
                pProcess.BeginOutputReadLine();
                pProcess.StandardInput.WriteLine("enter");
                pProcess.WaitForExit();

                if (pProcess.HasExited)
                {
                    pProcess.CancelOutputRead();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
            }
        }
Exemple #28
0
        public void Convert(string cmd)
        {
            MencoderInstance = new System.Diagnostics.Process();
            MencoderInstance.StartInfo.CreateNoWindow         = true;
            MencoderInstance.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
            MencoderInstance.StartInfo.UseShellExecute        = false;
            MencoderInstance.StartInfo.ErrorDialog            = false;
            MencoderInstance.StartInfo.RedirectStandardOutput = true;
            MencoderInstance.StartInfo.RedirectStandardInput  = true;
            MencoderInstance.StartInfo.RedirectStandardError  = true;



            MencoderInstance.StartInfo.Arguments = cmd;
            MencoderInstance.StartInfo.FileName  = this._backendProgram.MEncoder;

            MencoderInstance.Start();


            MencoderInstance.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(MencoderInstance_OutputDataReceived);
            MencoderInstance.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(MencoderInstance_ErrorDataReceived);
            MencoderInstance.BeginErrorReadLine();
            MencoderInstance.BeginOutputReadLine();
            MencoderInstance.EnableRaisingEvents = true;
            MencoderInstance.Exited += new EventHandler(MencoderInstance_Exited);
        }
        // Start the process
        public void StartProcess()
        {
            if (System.IO.File.Exists(sServiceFilePath) == false)
            {
                bExecutableFailure = true;
                return;
            }

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(sServiceFilePath);
            psi.UseShellExecute        = false;
            psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
            psi.CreateNoWindow         = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput  = true;

            serviceProcess           = new System.Diagnostics.Process();
            serviceProcess.StartInfo = psi;
            serviceProcess.Start();
            serviceProcess.OutputDataReceived += serviceProcess_OutputDataReceived;
            serviceProcess.ErrorDataReceived  += serviceProcess_ErrorDataReceived;
            serviceProcess.BeginErrorReadLine();
            serviceProcess.BeginOutputReadLine();

            swInput = serviceProcess.StandardInput;
        }
        private static void OnChanged(object source, System.IO.FileSystemEventArgs e)
        {
            // TODO, this is so hardcoded it sucks, make it better

            string glslCompiler   = "glslangValidator.exe";
            string glslDir        = RootDir + "\\glslang\\2020.07.28\\bin";
            string sourceFolder   = RootDir + "\\PluginSource\\source\\PixelsForGlory\\Shaders";
            string binariesFolder = RootDir + "\\UnityProject\\Assets\\Plugins\\RayTracing\\x86_64";

            var pathParts = e.Name.Split('\\');
            var nameParts = pathParts[pathParts.Length - 1].Split('.');
            var nameOnly  = nameParts[0];

            var    stageParts = nameOnly.Split('_');
            string stage      = $"r{stageParts[1]}";

            var glslValidator = $"{glslDir}\\{glslCompiler}";
            var glslPath      = $"{sourceFolder}\\{nameOnly}.glsl";

            // What the actual f**k is happening here?
            var binaryPath = $"{binariesFolder}\\{nameOnly}.bin";

            var arguments = $"--target-env vulkan1.2 -V -S {stage} {glslPath} -o {binaryPath}";

            Debug.Log($"Rebuilding shader: {glslValidator} {arguments}");

            var startInfo = new System.Diagnostics.ProcessStartInfo
            {
                CreateNoWindow         = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                WorkingDirectory       = RootDir,
                FileName  = glslValidator,
                Arguments = arguments
            };

            var process = new System.Diagnostics.Process
            {
                StartInfo = startInfo
            };

            process.OutputDataReceived += (sender, args) => { if (args.Data != null)
                                                              {
                                                                  Debug.Log(args.Data);
                                                              }
            };
            process.ErrorDataReceived += (sender, args) => { if (args.Data != null)
                                                             {
                                                                 Debug.LogError(args.Data);
                                                             }
            };

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

            PixelsForGlory.RayTracingPlugin.ResetPipeline();
        }
Exemple #31
0
        public string cmd(string command = "", int timeout = 10000)
        {
            string result = "";

            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardError  = true;
            procStartInfo.UseShellExecute        = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = false;
            procStartInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Normal;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            proc.ErrorDataReceived  += (sender, errorLine) => { };
            proc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null)
                                                                 {
                                                                     result += outputLine.Data;
                                                                 }
            };
            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();
            proc.WaitForExit(timeout);

            return(result);
        }
        static int run_process(string processname, string args)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            //出力とエラーをストリームに書き込むようにする
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
            p.StartInfo.StandardOutputEncoding = Encoding.UTF8;

            p.OutputDataReceived += (Object sender, System.Diagnostics.DataReceivedEventArgs e) =>
            {
                Console.WriteLine(e.Data);
            };
            p.ErrorDataReceived += (Object sender, System.Diagnostics.DataReceivedEventArgs e) =>
            {
                Console.Error.WriteLine(e.Data);
            };
            p.StartInfo.FileName              = processname;
            p.StartInfo.Arguments             = args;
            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.CreateNoWindow        = true;
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
            int return_v = p.ExitCode;

            p.Close();
            return(return_v);
        }
        /// <summary>
        /// Execute a Commad
        /// </summary>
        public List<string> ExecuteCommand(string cmd, string args)
        {
            answer.Clear();
            System.Diagnostics.Process process = null;
            System.Diagnostics.ProcessStartInfo processStartInfo;
            processStartInfo = new System.Diagnostics.ProcessStartInfo();

            processStartInfo.FileName = cmd;
            if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
            {
                processStartInfo.Verb = "runas";
            }

            processStartInfo.Arguments = args;
            processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardInput = true;

            process = new System.Diagnostics.Process();
            process.StartInfo = processStartInfo;
            process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);

            try
            {
                process.Start();

                StreamWriter streamWriter = process.StandardInput;
                process.BeginOutputReadLine();
                streamWriter.Close();
                process.WaitForExit();

                string error = process.StandardError.ReadToEnd();
                if (!error.Equals(""))
                {
                    answer.Add("Errors Found: " + error);
                }
            }
            catch (Exception ex)
            {
                answer.Add("Exception: " + ex.Message);
            }

            if (process != null)
            {
                process.Dispose();
            }

            return answer;
        }
        public static string Exec(String command)
        {
            Console.WriteLine("command : " + command);
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c " + command;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.Start();

            var stdout = new StringBuilder();
            var stderr = new StringBuilder();
            p.OutputDataReceived += (sender, e) => {
                if (e.Data != null) {
                    stdout.AppendLine(e.Data);
                }
            };
            p.ErrorDataReceived += (sendar, e) => {
                if (e.Data != null) {
                    stderr.AppendLine(e.Data);
                }
            };
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            var output = new StringBuilder();
            var isTimeOut = false;
            if (!p.WaitForExit(3000)) {
                isTimeOut = true;
                p.Kill();
            }
            p.CancelOutputRead();
            p.CancelErrorRead();
            output.Append(stdout.ToString());
            output.Append(stderr.ToString());
            if (isTimeOut) {
                output.Append("TIMEOUT.");
            }
            return output.ToString();
        }
		public static string Execute(string executable, string workingdir, string arguments, params object[] vaargs)
		{
			using( System.Diagnostics.Process process = new System.Diagnostics.Process() )
			{
				process.StartInfo.UseShellExecute = false;
				process.StartInfo.FileName = executable;
				process.StartInfo.RedirectStandardOutput = true;
				process.StartInfo.RedirectStandardError = true;
				process.StartInfo.CreateNoWindow = true;
				process.StartInfo.WorkingDirectory = workingdir;
				process.StartInfo.Arguments = string.Format(arguments, vaargs);
				
				if(!process.Start())
				{
					throw new Error("{0}: Failed to start {1}.", executable, process.StartInfo.Arguments);
				}
				
				using( Handler stderr = new Handler(), stdout = new Handler() )
				{
					process.OutputDataReceived += stdout.OnOutput;
					process.BeginOutputReadLine();
					
					process.ErrorDataReceived += stderr.OnOutput;
					process.BeginErrorReadLine();
					
					process.WaitForExit();

					if(0 != process.ExitCode)
					{
						throw new Error("Failed to execute {0} {1}, exit code was {2}", executable, process.StartInfo.Arguments, process.ExitCode);
					}
					
					stderr.sentinel.WaitOne();
					stdout.sentinel.WaitOne();
					
					return stdout.buffer + "\n" + stderr.buffer;
				}
			}
		}
Exemple #36
0
        public GnuShogiPlayer()
        {
            ShogiProc = new System.Diagnostics.Process();
            ShogiProc.StartInfo.FileName = "gnushogi";
            ShogiProc.StartInfo.UseShellExecute = false;
            ShogiProc.StartInfo.RedirectStandardError = true;
            ShogiProc.StartInfo.RedirectStandardInput = true;
            ShogiProc.StartInfo.RedirectStandardOutput = true;

            ShogiProc.EnableRaisingEvents = true;
            ShogiProc.OutputDataReceived += HandleShogiProcOutputDataReceived;

            ShogiProc.Exited += HandleShogiProcExited;
            ShogiProc.Start();
            ShogiProc.BeginOutputReadLine();

            //read welcome message
            ReadFromShogiProc();

            ReadNextMoveThreadWaitHandle = new AutoResetEvent(false);
            ReadNextMoveThread = new Thread(new ThreadStart(ReadNextMoveThreadFunc));
            ReadNextMoveThread.IsBackground = true;
            ReadNextMoveThread.Start();
        }
        public override void Handle(TemplateAction action) {
            _process.Logger.Info("Running {0}.", action.File);

            var fileInfo = new FileInfo(action.File);

            if (fileInfo.Exists) {
                var executable = new System.Diagnostics.Process {
                    StartInfo = {
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        FileName = fileInfo.FullName,
                        Arguments = action.Arguments,
                        CreateNoWindow = true
                    }
                };

                executable.OutputDataReceived += (sender, args) => _process.Logger.Info(args.Data);
                executable.Start();
                executable.BeginOutputReadLine();
                executable.WaitForExit();
            } else {
                _process.Logger.Warn("Couldn't find and execute {0}.", action.File);
            }
        }
		static private bool RunCommand(OutputWindowPane output, string executable, string commandline, string workingdir, int timeout)
		{
			try
			{
				System.Diagnostics.Process process = new System.Diagnostics.Process();
				process.StartInfo.UseShellExecute = false;
				process.StartInfo.FileName = executable;
				if( 0 == timeout )
				{
					// We are not for these processes reading the stdout and thus they could if they wrote more
					// data on the output line hang.
					process.StartInfo.RedirectStandardOutput = false;
					process.StartInfo.RedirectStandardError = false;
				}
				else
				{
					process.StartInfo.RedirectStandardOutput = true;
					process.StartInfo.RedirectStandardError = true;
				}
				process.StartInfo.CreateNoWindow = true;
				process.StartInfo.WorkingDirectory = workingdir;
				process.StartInfo.Arguments = commandline;

				Log.Debug("executableName : " + executable);
				Log.Debug("workingDirectory : " + workingdir);
				Log.Debug("command : " + commandline);

				if(!process.Start())
				{
					Log.Error("{0}: {1} Failed to start. Is Perforce installed and in the path?\n", executable, commandline);
					return false;
				}

                if (0 == timeout)
                {
                    // Fire and forget task.
                    return true;
                }
				
				bool exited = false;
				string alloutput = "";
				using (Process.Handler stderr = new Process.Handler(), stdout = new Process.Handler())
				{
					process.OutputDataReceived += stdout.OnOutput;
					process.BeginOutputReadLine();

					process.ErrorDataReceived += stderr.OnOutput;
					process.BeginErrorReadLine();

					exited = process.WaitForExit(timeout);

					/*
                     * This causes the plugin to unexpectedly crash, since it brings the entire thread down, and thus the entire environment?!?
                     * 
                    
                    if (0 != process.ExitCode)
					{
						throw new Process.Error("Failed to execute {0} {1}, exit code was {2}", executable, process.StartInfo.Arguments, process.ExitCode);
					}*/

					stderr.sentinel.WaitOne();
					stdout.sentinel.WaitOne();
					alloutput = stdout.buffer + "\n" + stderr.buffer;
				}
				
				if(!exited)
				{
					Log.Info("{0}: {1} timed out ({2} ms)", executable, commandline, timeout);
                    process.Kill();
					return false;
				}
				else
				{
					if(null != output)
					{
						output.OutputString(executable + ": " + commandline + "\n");
						output.OutputString(alloutput);
					}

					System.Diagnostics.Debug.WriteLine(commandline + "\n");
					System.Diagnostics.Debug.WriteLine(alloutput);

					if(0 != process.ExitCode)
					{
						Log.Debug("{0}: {1} exit code {2}", executable, commandline, process.ExitCode);
						return false;
					}
				}

				return true;
			}
			catch(System.ComponentModel.Win32Exception e)
			{
				Log.Error("{0}: {1} failed to spawn: {2}", executable, commandline, e.ToString());
				return false;
			}
		}
        public void ExecuteTests(string consolePath, string commandArgs, bool debug)
        {
            string command = string.Format("{0} {1}", consolePath, commandArgs);
            tracer.Trace(command, GetType().Name);

            var pane = outputWindowService.TryGetPane(OutputWindowDefinitions.SpecRunOutputWindowName);
            var displayResult = pane != null;
            var dispatcher = Dispatcher.CurrentDispatcher;

            var process = new System.Diagnostics.Process();
            process.StartInfo.FileName = consolePath;
            process.StartInfo.Arguments = commandArgs;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;

            if (displayResult)
            {
                pane.Clear();
                pane.Activate();
                dte.ToolWindows.OutputWindow.Parent.Activate();
                pane.WriteLine(command);
                process.OutputDataReceived += (sender, args) =>
                                                  {
                                                      if (args.Data != null)
                                                      {
                                                          dispatcher.BeginInvoke(new Action(() => pane.WriteLine(args.Data)), DispatcherPriority.ContextIdle);
                                                      }
                                                  };
            }

            process.Start();

            if (debug)
                AttachToProcess(process.Id);

            if (displayResult)
            {
                process.BeginOutputReadLine();
            }

            // async execution: we do not call 'process.WaitForExit();'
        }
Exemple #40
0
        public static void RunCommandTillEnd(string filename, string arguments, List<string> stdout, List<string> stderr, Logger logger)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            process.StartInfo.FileName = filename;
            process.StartInfo.Arguments = arguments;

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

            process.OutputDataReceived += (sender, eventArgs) => CommandOutputReceived(sender, eventArgs, stdout);
            process.ErrorDataReceived += (sender, eventArgs) => CommandOutputReceived(sender, eventArgs, stderr);

            logger.Log("Abbout to start: {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            try
            {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
            }
            catch (Exception e)
            {
                logger.Log("Got an exception while starting the process");
                logger.Log(e.ToString());

                return;
            }

            process.WaitForExit();
        }
        /// <summary>
        /// Uninstall Specified API
        /// </summary>
        /// <param name="version">version of API to uninstall</param>
        /// <returns>true if successful</returns>
        public bool UninstallAPI(string version, bool isSimulator)
        {
            bool success = false;
            _error = "";
            _isSimulator = isSimulator;

            Status = "Uninstalling API Level";

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(InstallDataReceived);
            p.Exited += new EventHandler(p_Exited);

            /// Get Device PIN
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = string.Format(@"/C " + bbndkPathConst + @"\eclipsec --uninstall {0} {1}", version, isSimulator ? "--simulator" : "");

            try
            {
                IsInstalling = true;
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
                success = false;
            }

            return success;
        }
        public bool Start()
        {
            // if hybris is still running we don't need to start again
            if (this.IsAlive) return true;

            this.Status = AzurePluginStatus.Starting;
            this.StatusMessage = string.Empty;
            try
            {
                // Prepare hybris start
                string hybrisRoot = Path.Combine(BaseDirectory, "hybris");
                string hybrisWorkingDirectory = Path.Combine(hybrisRoot, "bin", "platform");
                string hybrisStartCommandFileName = Path.Combine(hybrisWorkingDirectory, "hybris-start.cmd");

                // Start hybris process
                _HybrisJavaProcess = new System.Diagnostics.Process
                            {
                                StartInfo = new System.Diagnostics.ProcessStartInfo
                                    {
                                        WorkingDirectory = hybrisWorkingDirectory,
                                        FileName = hybrisStartCommandFileName,
                                        Arguments = string.Empty,
                                        UseShellExecute = false,
                                        LoadUserProfile = false,
                                        RedirectStandardOutput = true,
                                        RedirectStandardError = true,
                                        RedirectStandardInput = true,
                                        CreateNoWindow = true,
                                        WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                                    },
                                EnableRaisingEvents = true,
                            };
                _HybrisJavaProcess.OutputDataReceived += (s, a) => { if (!string.IsNullOrWhiteSpace(a.Data)) Trace.TraceVerbose("HybrisPlugin: Hybris process output: " + a.Data); };
                _HybrisJavaProcess.ErrorDataReceived += (s, a) => { if (!string.IsNullOrWhiteSpace(a.Data)) Trace.TraceAndLogError("HybrisPlugin", "Hybris process error: " + a.Data); };
                _HybrisJavaProcess.Exited += delegate(object sender, EventArgs e)
                    {
                        if (!this.ConfigStopHybris)
                        {
                            Trace.TraceAndLogError("HybrisPlugin", "Hybris process exited! ExitCode " + (sender as System.Diagnostics.Process).ExitCode.ToString());
                            this.Status = AzurePluginStatus.Error;
                            this.StatusMessage = "Hybris process exited!";
                        }
                        else
                        {
                            Trace.TraceAndLogWarning("HybrisPlugin", "Hybris process exited due to Additional Configuration change! ExitCode " + (sender as System.Diagnostics.Process).ExitCode.ToString());
                            this.Status = AzurePluginStatus.Warning;
                            this.StatusMessage = "Hybris process exited!";
                        }
                    };
                if (_HybrisJavaProcess.Start())
                {
                    _HybrisJavaProcess.BeginOutputReadLine();
                    _HybrisJavaProcess.BeginErrorReadLine();
                }
                else
                {
                    Trace.TraceAndLogError("HybrisPlugin", "Hybris process could not be started!");
                    this.Status = AzurePluginStatus.ErrorStarting;
                    this.StatusMessage = "Hybris process could not be started!";
                    return false;
                }
                Trace.TraceAndLogInformation("HybrisPlugin", "Hybris process started.");
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error while creating HybrisJavaProcess: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorStarting;
                this.StatusMessage = "Error while creating HybrisJavaProcess.";
                return false;
            }

            this.Status = AzurePluginStatus.Healthy;
            this.StatusMessage = "Process ID: " + _HybrisJavaProcess.Id.ToString();
            return true;
        }
        static void Main(string[] args)
        {
            var outText = new StringBuilder();

              try {
            var asseblyLocation = typeof (Program).Assembly.Location;
            var sdkLocation = Path.GetFullPath(Path.Combine(
              Path.GetDirectoryName(asseblyLocation), @"..\..\..\..\..\..\unityfull"
              ));

            sdkLocation =
              Environment.GetEnvironmentVariable("UNITY_NEW_MONO_SDK") ??
              sdkLocation;

            var mcsLocation = Environment.GetEnvironmentVariable("UNITY_NEW_MONO")
                          ??
                          Environment.ExpandEnvironmentVariables(
                            @"%ProgramFiles%\Mono\lib\mono\4.5\mcs.exe");

            var procStartInfo =
              new System.Diagnostics.ProcessStartInfo(mcsLocation);
            //        new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\Mono\bin\mono.exe");
            //        new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\Mono\bin\mcs.bat");

            procStartInfo.Arguments = $@"""-sdk:{sdkLocation}"" --runtime:v2 " + string.Join(" ", args);

            //      procStartInfo.Arguments = @"""C:\Program Files (x86)\Mono\lib\mono\4.5\mcs.exe"" " + procStartInfo.Arguments;

            procStartInfo.UseShellExecute = false;
            //      procStartInfo.CreateNoWindow = true;
            procStartInfo.RedirectStandardError = true;
            procStartInfo.RedirectStandardOutput = true;

            var proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

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

            proc.OutputDataReceived += (sender, e) => {
              Console.WriteLine(e.Data);
              output.AppendLine(e.Data);
            };

            proc.ErrorDataReceived += (sender, e) => {
              Console.Error.WriteLine(e.Data);
              error.AppendLine(e.Data);
            };

            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();

            proc.WaitForExit();

            outText.AppendLine(procStartInfo.Arguments);

            var corlib_path =
              Path.GetDirectoryName(typeof (object).Assembly.Location);
            string fx_path = corlib_path.Substring(0,
              corlib_path.LastIndexOf(Path.DirectorySeparatorChar));
            outText.AppendLine(fx_path);
            outText.AppendLine(asseblyLocation);
            outText.AppendLine(sdkLocation);

            //      var dict = Environment.GetEnvironmentVariables();
            //      foreach (var k in dict.Keys) {
            //        outText.AppendLine(k + " " + dict[k]);
            //      }
            outText.AppendLine(Environment.CurrentDirectory);

            outText.AppendLine();
            outText.AppendLine("[Output start]");
            outText.AppendLine();
            outText.Append(output);
            outText.AppendLine("[Output end]");

            outText.AppendLine();
            outText.AppendLine("[Error start]");
            outText.AppendLine();
            outText.Append(error);
            outText.AppendLine("[Error end]");
              }
              catch (Exception e) {
            outText.AppendLine();
            outText.AppendLine("[Exception !!!]");
            outText.Append(e);
              }

              System.IO.File.WriteAllText(
              Environment.ExpandEnvironmentVariables(
            @"%TEMP%\UnityMonoUpdatedCompilerOutput.txt"), outText.ToString());
        }
Exemple #44
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            spdTerminal = new System.Diagnostics.Process();

            if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
                //spdTerminal.StartInfo.FileName = "/usr/bin/gnome-terminal";
                // spdTerminal.StartInfo.FileName = "/bin/bash";
                spdTerminal.StartInfo.FileName = "go";
            else
                spdTerminal.StartInfo.FileName = "cmd.exe";

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

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

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

            spdTerminal.Start();

            swInputStream = spdTerminal.StandardInput;
            spdTerminal.BeginOutputReadLine();
            spdTerminal.BeginErrorReadLine();
        }
 void bgworker_DoWork(object sender, DoWorkEventArgs e)
 {
     // setup the process
     UpdateWorkCountUI();
     CheckFileExist(batPath);
     var processInfo = new System.Diagnostics.ProcessStartInfo(batPath, "2>&1");
     processInfo.WorkingDirectory = System.IO.Directory.GetCurrentDirectory();
     processInfo.CreateNoWindow = true;
     processInfo.UseShellExecute = false;
     processInfo.RedirectStandardOutput = true;
     proc = System.Diagnostics.Process.Start(processInfo);
     // attach exit event handler
     proc.EnableRaisingEvents = true;
     proc.Exited += new EventHandler(ProcExit);
     // setup asynchronous reading
     proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler);
     proc.BeginOutputReadLine();
     proc.WaitForExit();
 }
		public SignatureInfo GetSignaturesFromKeystore (string keytool = null, string keystore = null, string alias = null, string storepass = null, string keypass = null)
		{
			if (string.IsNullOrEmpty (keystore))
				keystore = FindDebugKeystore ();

			if (string.IsNullOrEmpty (keytool))
				keytool = FindKeytool ();

			if (string.IsNullOrEmpty (alias))
				alias = "androiddebugkey";
			if (string.IsNullOrEmpty (storepass))
				storepass = "******";
			if (string.IsNullOrEmpty (keypass))
				keypass = "******";

			var sbOut = new StringBuilder ();

			var p = new System.Diagnostics.Process ();
			p.StartInfo = new System.Diagnostics.ProcessStartInfo (keytool, string.Format ("-list -v -keystore \"{0}\" -alias {1} -storepass {2} -keypass {3}", keystore, alias, storepass, keypass));
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
			p.OutputDataReceived += (sender, e) => {
				sbOut.Append (e.Data);
			};

			p.Start ();
			p.BeginOutputReadLine ();
			p.WaitForExit ();

			var sig = GetSignatures (sbOut.ToString ());

			Console.WriteLine (sbOut);

			return sig;
		}
        //CheckEpubを実施、Output/Errorを表示する
        public static bool CheckEpub(string ePubFile)
        {
            var ret = true; //仮にエラーなしとする

            //メッセージ初期化
            outputLines = new List<string>();
            errorLines = new List<string>();

            //EPUBチェック実施中パネルを表示する
            var checkingDlg = new EpubCheckingDialog();
            checkingDlg.Show();

            var javaPath = PostProcess.javaPath;
            var ePubCheckPath = PostProcess.ePubCheckPath;

            //実行ファイル
            var p = new System.Diagnostics.Process();
            p.StartInfo.FileName = javaPath;

            //引数
            var args = "-jar "
                        + "\"" + ePubCheckPath + "\" "
                        + " \"" + ePubFile + "\"";
            p.StartInfo.Arguments = args;

            //出力とエラーをストリームに書き込むようにする
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            //OutputDataReceivedとErrorDataReceivedイベントハンドラを追加
            p.OutputDataReceived += OutputDataReceived;
            p.ErrorDataReceived += ErrorDataReceived;


            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.CreateNoWindow = true;

            //EpubCheckを実行する
            p.Start();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            p.WaitForExit();
            p.Close();

            //結果をダイアログに表示する
            var resultDlg = new EpubCheckResultDialog();

            //Outputをコピーする
            foreach (var output in outputLines)
            {
                resultDlg.outputTextBox.Text += (output + "\n");
            }

            //Errorをコピーする
            if (errorLines.Count > 1)   //エラーがあれば
            {
                foreach (var error in errorLines)
                {
                    resultDlg.errorTextBox.Text += (error + "\n");
                }
                ret = false;    //戻り値をエラーありにする。
            }
            else //エラーなし
            {
                resultDlg.errorTextBox.Text = "エラーはありませんでした。";
            }
            checkingDlg.Close();        //EpubCheck実施中のダイアログを閉じる
            resultDlg.ShowDialog();     //EpubCheck結果を表示する

            return (ret);
        }
        private void deleteFiles()
        {
            var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(_myDir.FullName, "delete_files.cmd"));
            psi.EnvironmentVariables.Add("DATFILES_DIR", _dataDirectory);
            psi.EnvironmentVariables.Add("INSTALL_DIR", _installDirectory);

            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;

            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.ErrorDialog = false;

            var errorWH = new System.Threading.ManualResetEvent(false);
            var outputWH = new System.Threading.ManualResetEvent(false);

            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo = psi;

                p.OutputDataReceived += (s, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWH.Set();
                        }
                        else
                        {
                            _logger.WriteLine(e.Data);
                        }
                    };

                p.ErrorDataReceived += (s, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWH.Set();
                    }
                    else
                    {
                        _logger.WriteLine(e.Data);
                    }
                };

                p.Start();

                p.BeginErrorReadLine();
                p.BeginOutputReadLine();

                p.WaitForExit();

                errorWH.WaitOne();
                outputWH.WaitOne();

                if (p.ExitCode != 0)
                {
                    throw new Exception("Batch file returned with exit code of " + p.ExitCode);
                }
            }
        }
Exemple #49
0
        /// <summary>
        /// Run the blackberry-signer tool with parameters passed in
        /// </summary>
        /// <returns></returns>
        public bool UnRegister()
        {
            bool success = false;

            try
            {

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                startInfo.RedirectStandardError = true;
                startInfo.RedirectStandardOutput = true;
                p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorDataReceived);
                p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputDataReceived);

                //run register tool
                startInfo.FileName = "cmd.exe";
                startInfo.WorkingDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\BlackBerry\\VSPlugin-NDK\\qnxtools\\bin\\";
                startInfo.Arguments = string.Format("/C blackberry-signer.bat -cskdelete");

                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();

                if (p.ExitCode != 0)
                {
                    success = false;
                }
                else
                {
                    /// Remove Files
                    FileInfo fi_p12 = new FileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Research In Motion\author.p12");
                    FileInfo fi_csk = new FileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Research In Motion\bbidtoken.csk");
                    fi_p12.Delete();
                    fi_csk.Delete();
                    /// Set password to blank
                    setPassword("");

                    success = true;
                }
                p.Close();
            }
            catch (Exception e)
            {
                _errors += e.Message + "\n";
                success = false;
            }

            return success;
        }
Exemple #50
0
        /// <summary>
        /// Run the blackberry-signer tool with parameters passed in
        /// </summary>
        /// <returns></returns>
        public bool Register(string authorID, string password)
        {
            bool success = false;
            if (authorID.Trim().ToUpper().Contains("BLACKBERRY"))
            {
                _errors += "BlackBerry is a reserved word and cannot be used in \"author name\".\n";
                return false;
            }
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorDataReceived);
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputDataReceived);

            //run register tool
            startInfo.FileName = "cmd.exe";
            startInfo.WorkingDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\BlackBerry\\VSPlugin-NDK\\qnxtools\\bin\\";
            startInfo.Arguments = string.Format("/C blackberry-keytool -genkeypair -storepass {0} -author {1}", password, "\"" + authorID + "\"");

            try
            {
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                if (p.ExitCode != 0)
                    success = false;
                else
                    success = true;
                p.Close();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
                success = false;
            }

            setPassword(password);

            return success && string.IsNullOrEmpty(_errors);
        }
		public override Task<DebugResult> Launch(dynamic args)
		{
			_attachMode = false;

			// validate argument 'program'
			string programPath = getString(args, "program");
			if (programPath == null) {
				return Task.FromResult(new DebugResult(1001, "launch: property 'program' is missing or empty"));
			}
			programPath = ConvertClientPathToDebugger(programPath);
			if (!File.Exists(programPath) && !Directory.Exists(programPath)) {
				return Task.FromResult(new DebugResult(1002, "launch: program '{path}' does not exist", new { path = programPath }));
			}

			// validate argument 'args'
			string[] arguments = null;
			if (args.args != null) {
				arguments = args.args.ToObject<string[]>();
				if (arguments != null && arguments.Length == 0) {
					arguments = null;
				}
			}

			// validate argument 'cwd'
			var workingDirectory = (string)args.cwd;
			if (workingDirectory != null) {
				workingDirectory = workingDirectory.Trim();
				if (workingDirectory.Length == 0) {
					return Task.FromResult(new DebugResult(1003, "launch: property 'workingDirectory' is empty"));
				}
				workingDirectory = ConvertClientPathToDebugger(workingDirectory);
				if (!Directory.Exists(workingDirectory)) {
					return Task.FromResult(new DebugResult(1004, "launch: workingDirectory '{path}' does not exist", new { path = workingDirectory }));
				}
			}
			workingDirectory = null;	// TODO@AW Why?

			// validate argument 'runtimeExecutable'
			var runtimeExecutable = (string)args.runtimeExecutable;
			if (runtimeExecutable != null) {
				runtimeExecutable = runtimeExecutable.Trim();
				if (runtimeExecutable.Length == 0) {
					return Task.FromResult(new DebugResult(1005, "launch: property 'runtimeExecutable' is empty"));
				}
				runtimeExecutable = ConvertClientPathToDebugger(runtimeExecutable);
				if (!File.Exists(runtimeExecutable)) {
					return Task.FromResult(new DebugResult(1006, "launch: runtimeExecutable '{path}' does not exist", new { path = runtimeExecutable }));
				}
			}

			// validate argument 'runtimeArgs'
			string[] runtimeArguments = null;
			if (args.runtimeArgs != null) {
				runtimeArguments = args.runtimeArgs.ToObject<string[]>();
				if (runtimeArguments != null && runtimeArguments.Length == 0) {
					runtimeArguments = null;
				}
			}

			// validate argument 'env'
			Dictionary<string, string> env = null;
			var environmentVariables = args.env;
			if (environmentVariables != null) {
				env = new Dictionary<string, string>();
				foreach (var entry in environmentVariables) {
					env.Add((string)entry.Name, (string)entry.Value);
				}
				if (env.Count == 0) {
					env = null;
				}
			}

			bool externalConsole = false;
			try {
				externalConsole = (bool)args["externalConsole"];
			}
			catch (RuntimeBinderException) {
				// ignore
			}

			if (Utilities.IsOSX() || Utilities.IsLinux()) {
				const string host = "127.0.0.1";
				int port = Utilities.FindFreePort(55555);

				string mono_path = runtimeExecutable;
				if (mono_path == null) {
					if (!Terminal.IsOnPath(MONO)) {
						return Task.FromResult(new DebugResult(3001, "launch: can't find runtime '{_runtime}' on PATH", new { _runtime = MONO }));
					}
					mono_path = MONO;     // try to find mono through PATH
				}

				var mono_args = new String[runtimeArguments != null ? runtimeArguments.Length + 2 : 2];
				mono_args[0] = "--debug";
				mono_args[1] = String.Format("--debugger-agent=transport=dt_socket,server=y,address={0}:{1}", host, port);
				if (runtimeArguments != null) {
					runtimeArguments.CopyTo(mono_args, 2);
				}

				string program;
				if (workingDirectory == null) {
					// if no working dir given, we use the direct folder of the executable
					workingDirectory = Path.GetDirectoryName(programPath);
					program = Path.GetFileName(programPath);
				}
				else {
					// if working dir is given and if the executable is within that folder, we make the executable path relative to the working dir
					//program = Utilities.MakeRelativePath(workingDirectory, programPath);		// TODO@AW
					program = programPath;
				}

				if (externalConsole) {
					var result = Terminal.LaunchInTerminal(workingDirectory, mono_path, mono_args, program, arguments, env);
					if (!result.Success) {
						return Task.FromResult(new DebugResult(3002, "launch: can't launch terminal ({reason})", new { reason = result.Message }));
					}
				} else {

					_process = new System.Diagnostics.Process();
					_process.StartInfo.CreateNoWindow = true;
					_process.StartInfo.UseShellExecute = false;
					_process.StartInfo.WorkingDirectory = workingDirectory;
					_process.StartInfo.FileName = mono_path;
					_process.StartInfo.Arguments = string.Format("{0} {1} {2}", Terminal.ConcatArgs(mono_args), Terminal.Quote(program), Terminal.ConcatArgs(arguments));

					_stdoutEOF = false;
					_process.StartInfo.RedirectStandardOutput = true;
					_process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
						if (e.Data == null) {
							_stdoutEOF = true;
						}
						SendOutput(OutputEvent.Category.stdout, e.Data);
					};

					_stderrEOF = false;
					_process.StartInfo.RedirectStandardError = true;
					_process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
						if (e.Data == null) {
							_stderrEOF = true;
						}
						SendOutput(OutputEvent.Category.stderr, e.Data);
					};

					_process.EnableRaisingEvents = true;
					_process.Exited += (object sender, EventArgs e) => {
						Terminate("node process exited");
					};

					if (env != null) {
						// we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
						// instead we set the env vars on OpenDebug itself because we know that OpenDebug lives as long as a debug session.
						foreach (var entry in env) {
							System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
						}
					}

					try {
						_process.Start();
						_process.BeginOutputReadLine();
						_process.BeginErrorReadLine();
					}
					catch (Exception e) {
						return Task.FromResult(new DebugResult(3002, "launch: can't launch terminal ({reason})", new { reason = e.Message }));
					}
				}

				Debugger.Connect(IPAddress.Parse(host), port);
			}
			else {	// Generic & Windows
				CommandLine.WaitForSuspend();

				if (workingDirectory == null) {
					// if no working dir given, we use the direct folder of the executable
					workingDirectory = Path.GetDirectoryName(programPath);
				}
				Debugger.WorkingDirectory = workingDirectory;

				if (arguments != null) {
					string pargs = "";
					foreach (var a in arguments) {
						if (args.Length > 0) {
							pargs += ' ';
						}
						pargs += Terminal.Quote(a);
					}
					Debugger.Arguments = pargs;
				}

				if (environmentVariables != null) {
					var dict = Debugger.EnvironmentVariables;
					foreach (var entry in environmentVariables) {
						dict.Add(entry.Key, entry.Value);
					}
				}

				// TODO@AW we should use the runtimeExecutable
				// TODO@AW we should pass runtimeArgs

				var file = new FileInfo(programPath);
				Debugger.Run(file);
				// TODO@AW in case of errors?
			}

			return Task.FromResult(new DebugResult());
		}
Exemple #52
0
        //////////////////////////////////////////////////////////////////////////
        // Lifecycle
        //////////////////////////////////////////////////////////////////////////
        public Process run()
        {
            checkRun();
              try
              {
            // arguments
            string fileName = m_command.get(0) as string;
            StringBuilder args = new StringBuilder();
              for (int i=1; i<m_command.sz(); i++)
              {
            if (i > 1) args.Append(" ");
            args.Append(m_command.get(i) as string);
              }

            // create process
            m_proc = new System.Diagnostics.Process();
            m_proc.StartInfo.UseShellExecute = false;
            m_proc.StartInfo.FileName = fileName;
            m_proc.StartInfo.Arguments = args.ToString();

            // environment
            if (m_env != null)
            {
              IDictionaryEnumerator en = m_env.pairsIterator();
              while (en.MoveNext())
              {
            string key = (string)en.Key;
            string val = (string)en.Value;
            m_proc.StartInfo.EnvironmentVariables[key] = val;
              }
            }

            // working directory
            if (m_dir != null)
              m_proc.StartInfo.WorkingDirectory = ((LocalFile)m_dir).m_file.FullName;

            // streams
            if (m_in != null) m_proc.StartInfo.RedirectStandardInput = true;
            m_proc.StartInfo.RedirectStandardOutput = true;
            m_proc.StartInfo.RedirectStandardError  = true;
            m_proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(outHandler);
            m_proc.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(errHandler);

            // start it
            m_proc.Start();

            // start async read/writes
            if (m_in != null)
            {
              new System.Threading.Thread(
            new System.Threading.ThreadStart(inHandler)).Start();
            }
            m_proc.BeginOutputReadLine();
            m_proc.BeginErrorReadLine();

            return this;
              }
              catch (System.Exception e)
              {
            m_proc = null;
            throw Err.make(e).val;
              }
        }
        public bool Initialize()
        {
            Trace.TraceInformation("HybrisPlugin: Initializing.");
            this.Status = AzurePluginStatus.Initializing;
            this.StatusMessage = string.Empty;

            // 1. create necessary directories for usage by hybris
            #region Directories
            string workBaseDirectory = null;
            try
            {
                workBaseDirectory = RoleEnvironment.GetLocalResource("HybrisOnAzure.WorkBase").RootPath;
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error initializing: Could not retrieve local resource for workBaseDirectory. " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error initializing: Could not retrieve local resource for workBaseDirectory. ";
                return false;
            }

            //    a directory for "working" purposes mapped to a drive letter
            string workDrive = null;
            try
            {
                Trace.TraceInformation("HybrisPlugin: Initializing work-Drive.");
                if (!Directory.Exists(Path.Combine(workBaseDirectory, "work")))
                    Directory.CreateDirectory(Path.Combine(workBaseDirectory, "work"));
                workDrive = DrivePathManager.Map(Path.Combine(workBaseDirectory, "work"), "Work");
                if (!workDrive.EndsWith("\\")) workDrive = workDrive + "\\";
                Trace.TraceInformation("HybrisPlugin: mapped work directory to " + workDrive);
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error initializing: Could not map work drive. " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error initializing: Could not map work drive.";
                return false;
            }

            //    a directory for "temp" purposes mapped to a drive letter
            string tempDrive = null;
            try
            {
                Trace.TraceInformation("HybrisPlugin: Initializing temp-Drive.");
                if (!Directory.Exists(Path.Combine(workBaseDirectory, "temp")))
                    Directory.CreateDirectory(Path.Combine(workBaseDirectory, "temp"));
                tempDrive = DrivePathManager.Map(Path.Combine(workBaseDirectory, "temp"), "Temp");
                if (!tempDrive.EndsWith("\\")) tempDrive = tempDrive + "\\";
                Trace.TraceInformation("HybrisPlugin: mapped temp directory to " + tempDrive);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error initializing: Could not map temp drive. " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error initializing: Could not map temp drive.";
                return false;
            }

            //    a directory for "data" purposes mapped to a drive letter
            string dataDrive = null;
            try
            {
                Trace.TraceInformation("HybrisPlugin: Initializing data-Drive.");
                if (!Directory.Exists(Path.Combine(workBaseDirectory, "data")))
                    Directory.CreateDirectory(Path.Combine(workBaseDirectory, "data"));
                dataDrive = DrivePathManager.Map(Path.Combine(workBaseDirectory, "data"), "Data");
                if (!dataDrive.EndsWith("\\")) dataDrive = dataDrive + "\\";
                Trace.TraceInformation("HybrisPlugin: mapped data directory to " + dataDrive);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error initializing: Could not map data drive. " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error initializing: Could not map data drive.";
                return false;
            }
            #endregion
            #region Subdirectories for direct use by hybris
            Trace.TraceInformation("HybrisPlugin: Initializing subdirectories.");
            string hybrisWorkDirectory = null;
            string hybrisTempDirectory = null;
            string sharedTempDirectory = null;
            string hybrisDataDirectory = null;
            string hybrisLogsDirectory = null;
            try
            {
                // Work Directory = Z:\hybris
                hybrisWorkDirectory = Path.Combine(workDrive, "hybris");
                if (!Directory.Exists(hybrisWorkDirectory))
                    Directory.CreateDirectory(hybrisWorkDirectory);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Could not create directory " + hybrisWorkDirectory + ": " + ex.ToString());
            }
            try
            {
                // Temp Directory = Y:\hybris
                hybrisTempDirectory = Path.Combine(tempDrive, "hybris");
                if (!Directory.Exists(hybrisTempDirectory))
                    Directory.CreateDirectory(hybrisTempDirectory);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Could not create directory " + hybrisTempDirectory + ": " + ex.ToString());
            }
            try
            {
                // Shared Temp Directory = Y:\shared
                sharedTempDirectory = Path.Combine(tempDrive, "shared");
                if (!Directory.Exists(sharedTempDirectory))
                    Directory.CreateDirectory(sharedTempDirectory);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Could not create directory " + sharedTempDirectory + ": " + ex.ToString());
            }
            try
            {
                // Data Directory = S:\hybris on BackOfficeWorker, X:\hybris otherwise
                if (IsBackOfficeWorker)
                {
                    var driveLetter = hybrisDataDirectory = RoleEnvironment.GetConfigurationSettingValue("HybrisOnAzure.BackOfficeShare.DesiredDrive");
                    if (!driveLetter.EndsWith("\\")) driveLetter = driveLetter + "\\";
                    hybrisDataDirectory = Path.Combine(driveLetter, "hybris");
                }

                else
                    hybrisDataDirectory = Path.Combine(dataDrive, "hybris");
                if (!Directory.Exists(hybrisDataDirectory))
                    Directory.CreateDirectory(hybrisDataDirectory);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Could not create directory " + hybrisDataDirectory + ": " + ex.ToString());
            }
            try
            {
                // Logs Directory = X:\Logs\hybris
                hybrisLogsDirectory = Path.Combine(dataDrive, "logs", "hybris");
                if (!Directory.Exists(hybrisLogsDirectory))
                    Directory.CreateDirectory(hybrisLogsDirectory);
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Could not create directory " + hybrisLogsDirectory + ": " + ex.ToString());
            }
            #endregion

            // 2. Build hybris configuration files
            #region Calculates instance numbers
            string role = "";
            string rolenumber = "";
            Trace.TraceInformation("HybrisPlugin: Calculate instance numbers.");
            try
            {
                // This will have values like "BackOfficeWorker_IN_0" or "FrontendWorker_IN_0"
                string instanceName = RoleEnvironment.CurrentRoleInstance.Id;
                if (!string.IsNullOrEmpty(instanceName) && instanceName.Contains('_'))
                {
                    role = instanceName.Split('_').FirstOrDefault();
                    if (!string.IsNullOrEmpty(role))
                    {
                        role = role.ToLower();
                    }
                    try
                    {
                        int _rolenumber = Convert.ToInt32(instanceName.Split('_').LastOrDefault());
                        rolenumber = _rolenumber.ToString(CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                        // do nothing
                    }
                    catch (OverflowException)
                    {
                        // do nothing
                    }
                }
                if (string.IsNullOrEmpty(role))
                {
                    role = "unknown";
                }
                if (string.IsNullOrEmpty(rolenumber))
                {
                    rolenumber = "0";
                }
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error calculating role numbers: " + ex.Message);
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error calculating role numbers";
                return false;
            }
            #endregion

            #region local.properties file
            // Build hybris configuration user.properties file
            Trace.TraceInformation("HybrisPlugin: Updating local.properties file.");
            string hybrisRoot = Path.Combine(BaseDirectory, "hybris");
            string hybrisWorkingDirectory = Path.Combine(hybrisRoot, "bin", "platform");
            try
            {
                string userPropertiesFile = Path.Combine(hybrisRoot, "config", "local.properties");
                string userPropertiesFileContent = System.IO.File.Exists(userPropertiesFile) ? System.IO.File.ReadAllText(userPropertiesFile) : string.Empty;

                // Set the tomcat TCP port and binding information
                IPEndPoint tomcatHttpIPEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TomcatHttp"].IPEndpoint;
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "tomcat.http.listenaddress", tomcatHttpIPEndpoint.Address.ToString());
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "tomcat.http.port", tomcatHttpIPEndpoint.Port.ToString(CultureInfo.InvariantCulture));
                IPEndPoint tomcatHttpsIPEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TomcatHttps"].IPEndpoint;
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "tomcat.https.listenaddress", tomcatHttpsIPEndpoint.Address.ToString());
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "tomcat.https.port", tomcatHttpsIPEndpoint.Port.ToString(CultureInfo.InvariantCulture));

                // Set the JGroups TCP port and binding information
                IPEndPoint invalidationIPEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["InvalidateJGroup"].IPEndpoint;
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "cluster.broadcast.method.jgroups.tcp.bind_addr", invalidationIPEndpoint.Address.ToString());
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "cluster.broadcast.method.jgroups.tcp.bind_port", invalidationIPEndpoint.Port.ToString(CultureInfo.InvariantCulture));

                // Set the cluster id and node id
                // For a FrontendWorker, the cluster ID is calculated based on its IP Address (whilst the BackOfficeWorker has the ClusterId 0)
                //       See FrontendHybrisPlugin.cs Line 111
                IPAddress managementEndpointAddress = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Management"].IPEndpoint.Address;
                byte[] addressBytes = managementEndpointAddress.GetAddressBytes();
                int clusterId = IsBackOfficeWorker ? 0 : addressBytes[addressBytes.Length - 1];

                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "cluster.maxid", "256");
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "cluster.id", clusterId.ToString(CultureInfo.InvariantCulture));
                userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "node.id", clusterId.ToString(CultureInfo.InvariantCulture));

                // Change media.default.url.strategy when being on backoffice worker
                if (RoleEnvironment.CurrentRoleInstance.Role.Name.ToLower().Contains("backoffice"))
                {
                    //userPropertiesFileContent = PatchProperty(userPropertiesFileContent, "media.default.url.strategy", "windowsAzureBlobURLStrategy");
                }

                // Update work path settings
                userPropertiesFileContent = userPropertiesFileContent.Replace(@"{instanceworkdir}", hybrisWorkDirectory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); // INFO: Was instanceWorkDirectory
                userPropertiesFileContent = userPropertiesFileContent.Replace(@"{workdir}", hybrisWorkDirectory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                userPropertiesFileContent = userPropertiesFileContent.Replace(@"{logsdir}", hybrisLogsDirectory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                userPropertiesFileContent = userPropertiesFileContent.Replace(@"{datadir}", hybrisDataDirectory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                userPropertiesFileContent = userPropertiesFileContent.Replace(@"{tempdir}", hybrisTempDirectory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

                // Update the user.properties file
                File.WriteAllText(userPropertiesFile, userPropertiesFileContent);
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error creating user.properties file: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error creating user.properties file";
                return false;
            }
            #endregion

            // 3. Create hybris commands
            #region build command
            // Read the standard PATH environment variable
            string searchPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine);

            string hybrisBuildCommandFileName = Path.Combine(hybrisWorkingDirectory, "hybris-build.cmd");
            try
            {
                Trace.TraceInformation("HybrisPlugin: Create hybris build command.");

                // Build hybris build command
                var hybrisBuildCommandBuilder = new StringBuilder();
                hybrisBuildCommandBuilder.AppendLine(@"@echo off");
                hybrisBuildCommandBuilder.AppendLine(@"set path=" + Path.Combine(JavaHomeDirectory, @"bin") + ";" + searchPath);
                hybrisBuildCommandBuilder.AppendLine(@"set java_home=" + JavaHomeDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set temp=" + sharedTempDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set tmp=" + sharedTempDirectory);
                hybrisBuildCommandBuilder.AppendLine();
                hybrisBuildCommandBuilder.AppendLine(@"set HYBRIS_DATA_DIR=" + hybrisDataDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set HYBRIS_TEMP_DIR=" + hybrisTempDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set HYBRIS_WORK_DIR=" + hybrisWorkDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set HYBRIS_LOG_DIR=" + hybrisLogsDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"set HYBRIS_LOGS_DIR=" + hybrisLogsDirectory);
                hybrisBuildCommandBuilder.AppendLine();
                hybrisBuildCommandBuilder.AppendLine(@"cd " + hybrisWorkingDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"call setantenv.bat");
                hybrisBuildCommandBuilder.AppendLine();
                //hybrisBuildCommandBuilder.AppendLine(@"cd " + Path.Combine(hybrisWorkingDirectory, @"..\..\build"));
                //hybrisBuildCommandBuilder.AppendLine(@"call ant config -Denv=" + DeploymentName + " -Drole=" + RoleName + " -Drolenumber=" + rolenumber);
                //hybrisBuildCommandBuilder.AppendLine();
                //hybrisBuildCommandBuilder.AppendLine(@"cd " + hybrisWorkingDirectory);
                hybrisBuildCommandBuilder.AppendLine(@"call ant");
                File.WriteAllText(hybrisBuildCommandFileName, hybrisBuildCommandBuilder.ToString());
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error creating hybris build command: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error creating hybris build command";
                return false;
            }
            #endregion

            #region start command
            // Build hybris start command
            string hybrisStartCommandFileName = Path.Combine(hybrisWorkingDirectory, "hybris-start.cmd");
            try
            {
                Trace.TraceInformation("HybrisPlugin: Generate hybris start command");
                var hybrisStartCommandBuilder = new StringBuilder();
                hybrisStartCommandBuilder.AppendLine(@"@echo off");
                hybrisStartCommandBuilder.AppendLine(@"set path=" + Path.Combine(JavaHomeDirectory, @"bin") + ";" + searchPath);
                hybrisStartCommandBuilder.AppendLine(@"set java_home=" + JavaHomeDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set temp=" + sharedTempDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set tmp=" + sharedTempDirectory);
                hybrisStartCommandBuilder.AppendLine();
                hybrisStartCommandBuilder.AppendLine(@"set HYBRIS_DATA_DIR=" + hybrisDataDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set HYBRIS_TEMP_DIR=" + hybrisTempDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set HYBRIS_WORK_DIR=" + hybrisWorkDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set HYBRIS_LOG_DIR=" + hybrisLogsDirectory);
                hybrisStartCommandBuilder.AppendLine(@"set HYBRIS_LOGS_DIR=" + hybrisLogsDirectory);
                hybrisStartCommandBuilder.AppendLine();
                hybrisStartCommandBuilder.AppendLine(@"cd " + hybrisWorkingDirectory);
                hybrisStartCommandBuilder.AppendLine(@"call setantenv.bat");
                hybrisStartCommandBuilder.AppendLine(@"call hybrisserver.bat");
                File.WriteAllText(hybrisStartCommandFileName, hybrisStartCommandBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error creating hybris start command: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error creating hybris start command";
                return false;
            }
            #endregion

            #region stop command
            // Build hybris stop command
            string hybrisStopCommandFileName = Path.Combine(hybrisWorkingDirectory, "hybris-stop.cmd");

            try
            {
                Trace.TraceInformation("HybrisPlugin: Generating hybris stop command");

                var hybrisStopCommandBuilder = new StringBuilder();
                hybrisStopCommandBuilder.AppendLine(@"@echo off");
                hybrisStopCommandBuilder.AppendLine(@"set path=" + Path.Combine(JavaHomeDirectory, @"bin") + ";" + searchPath);
                hybrisStopCommandBuilder.AppendLine(@"set java_home=" + JavaHomeDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set temp=" + sharedTempDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set tmp=" + sharedTempDirectory);
                hybrisStopCommandBuilder.AppendLine();
                hybrisStopCommandBuilder.AppendLine(@"set HYBRIS_DATA_DIR=" + hybrisDataDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set HYBRIS_TEMP_DIR=" + hybrisTempDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set HYBRIS_WORK_DIR=" + hybrisWorkDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set HYBRIS_LOG_DIR=" + hybrisLogsDirectory);
                hybrisStopCommandBuilder.AppendLine(@"set HYBRIS_LOGS_DIR=" + hybrisLogsDirectory);
                hybrisStopCommandBuilder.AppendLine();
                hybrisStopCommandBuilder.AppendLine(@"cd " + hybrisWorkingDirectory);
                hybrisStopCommandBuilder.AppendLine(@"java -jar StopTanukiWrapper.jar");
                File.WriteAllText(hybrisStopCommandFileName, hybrisStopCommandBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error creating hybris stop command: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error creating hybris stop command";
                return false;
            }
            #endregion

            // 4. TanukiWrapper
            #region Tanuki wrapper
            Trace.TraceInformation("HybrisPlugin: Installing StopTanukiWrapper.jar");
            try
            {
                // Save the required StopTanukiWrapper.jar file in the platform directory
                string stopTanukiWrapperFileName = Path.Combine(hybrisWorkingDirectory, "StopTanukiWrapper.jar");
                File.WriteAllBytes(stopTanukiWrapperFileName, hybrisOnAzure.Common.Properties.Resources.StopTanukiWrapper);
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error installing StopTanukiWrapper.jar: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error installing StopTanukiWrapper.jar";
                return false;
            }
            #endregion

            // 5. actually build the hybris platform
            #region Build hybris
            // Build hybris platform
            Trace.TraceInformation("HybrisPlugin: Building hybris platform.");
            try
            {
                var buildOutput = new StringBuilder();
                var buildError = new StringBuilder();
                using (var buildProcess = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        WorkingDirectory = hybrisWorkingDirectory,
                        FileName = hybrisBuildCommandFileName,
                        Arguments = string.Empty,
                        UseShellExecute = false,
                        LoadUserProfile = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        RedirectStandardInput = true,
                        CreateNoWindow = true,
                        WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                    },
                    EnableRaisingEvents = true,
                })
                {
                    buildProcess.OutputDataReceived += (s, a) => Trace.TraceVerbose("HybrisPlugin: Building hybris ouput line" + a.Data);
                    buildProcess.ErrorDataReceived += (s, a) => Trace.TraceAndLogError("HybrisPlugin", "Building hybris error line" + a.Data);

                    if (buildProcess.Start())
                    {
                        buildProcess.BeginOutputReadLine();
                        buildProcess.BeginErrorReadLine();
                        buildProcess.WaitForExit();
                    }

                    if (buildProcess.ExitCode == 0)
                        Trace.TraceAndLogInformation("HybrisPlugin", "Successfully built hybris platform.");
                    else
                        Trace.TraceAndLogError("HybrisPlugin", "Error executing build hybris platform command.");
                }
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("Hybris", "Error building hybris platform. " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error building hybris platform.";
                return false;
            }
            #endregion

            // 6. Get from additional settings if we may start the hybris process
            #region Additional configuration
            AdditionalConfigurationManager.Instance.AdditionalConfigurationChanged += Instance_AdditionalConfigurationChanged;
            try
            {
                Trace.TraceInformation("HybrisPlugin: Processing initial additional configuration.");
                AdditionalConfigurationManager.Instance.ProcessConfiguration();
                Trace.TraceInformation("HybrisPlugin: Successfully processed initial additional configuration.");
            }
            catch(Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error processing initial additional configuration: " + ex.ToString());
            }
            try
            {
                Trace.TraceInformation("HybrisPlugin", "Determining if Hybris was stopped before a reboot.");
                var stopHybris = AdditionalConfigurationManager.Instance.GetCurrentConfigurationValue("StopHybris");
                if (stopHybris == null)
                    Trace.TraceAndLogWarning("HybrisPlugin", "Determining if Hybris was stopped before a reboot resulted in a NULL value. Hybris will be started.");
                else
                {
                    Trace.TraceInformation("HybrisPlugin: Determining if Hybris was stopped before a reboot resulted in: " + stopHybris);
                    this.ConfigStopHybris = bool.Parse(stopHybris);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceAndLogError("HybrisPlugin", "Error getting from Additional configuration if processes are to be started: " + ex.ToString());
                this.Status = AzurePluginStatus.ErrorInitializing;
                this.StatusMessage = "Error getting Additional configuration";
                return false;
            }
            #endregion

            Trace.TraceInformation("HybrisPlugin: Initialization done.");
            this.Status = AzurePluginStatus.NotStarted;
            this.StatusMessage = string.Empty;
            return true;
        }
Exemple #54
0
        public void Start()
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = Command;
            pProcess.StartInfo.Arguments = Params;

            pProcess.StartInfo.UseShellExecute = UseShellExecute;
            pProcess.StartInfo.RedirectStandardOutput = RedirectStandardOutput;
            pProcess.StartInfo.RedirectStandardError = RedirectStandardError;
            pProcess.StartInfo.CreateNoWindow = CreateNoWindow;
            pProcess.StartInfo.WindowStyle = WindowStyle;

            if (RedirectStandardOutput)
            {
                pProcess.OutputDataReceived += (sender, args) =>
                {
                    if (OnNewLine != null)
                        OnNewLine(args.Data);
                };
                pProcess.ErrorDataReceived += (sender, args) =>
                {
                    if (OnNewLine != null)
                        OnNewLine(args.Data);
                };
            }

            pProcess.Start();
            if (RedirectStandardOutput)
            {
                pProcess.BeginOutputReadLine();
                pProcess.BeginErrorReadLine();
            }
            SetProcessStatusInvoke(ProcessStatus.Running);

            if(Async)
            {
                new Thread(() =>
                {
                    pProcess.WaitForExit();
                    SetProcessStatusInvoke(ProcessStatus.Stop);
                }).Start();
            }
            else
            {
                pProcess.WaitForExit();
                SetProcessStatusInvoke(ProcessStatus.Stop);
            }
        }
Exemple #55
0
        public static void Execute(
            Bam.Core.ExecutionContext context,
            string executablePath,
            Bam.Core.StringArray commandLineArguments,
            string workingDirectory = null,
            Bam.Core.StringArray inheritedEnvironmentVariables = null,
            System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> addedEnvironmentVariables = null,
            string useResponseFileOption = null)
        {
            var processStartInfo = new System.Diagnostics.ProcessStartInfo();
            processStartInfo.FileName = executablePath;
            processStartInfo.ErrorDialog = true;
            if (null != workingDirectory)
            {
                processStartInfo.WorkingDirectory = workingDirectory;
            }

            var cachedEnvVars = new System.Collections.Generic.Dictionary<string, string>();
            // first get the inherited environment variables from the system environment
            if (null != inheritedEnvironmentVariables)
            {
                int envVarCount;
                if (inheritedEnvironmentVariables.Count == 1 &&
                    inheritedEnvironmentVariables[0] == "*")
                {
                    foreach (System.Collections.DictionaryEntry envVar in processStartInfo.EnvironmentVariables)
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                    }
                }
                else if (inheritedEnvironmentVariables.Count == 1 &&
                         System.Int32.TryParse(inheritedEnvironmentVariables[0], out envVarCount) &&
                         envVarCount < 0)
                {
                    envVarCount += processStartInfo.EnvironmentVariables.Count;
                    foreach (var envVar in processStartInfo.EnvironmentVariables.Cast<System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                        --envVarCount;
                        if (0 == envVarCount)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var envVar in inheritedEnvironmentVariables)
                    {
                        if (!processStartInfo.EnvironmentVariables.ContainsKey(envVar))
                        {
                            Bam.Core.Log.Info("Environment variable '{0}' does not exist", envVar);
                            continue;
                        }
                        cachedEnvVars.Add(envVar, processStartInfo.EnvironmentVariables[envVar]);
                    }
                }
            }
            processStartInfo.EnvironmentVariables.Clear();
            if (null != inheritedEnvironmentVariables)
            {
                foreach (var envVar in cachedEnvVars)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
                }
            }
            if (null != addedEnvironmentVariables)
            {
                foreach (var envVar in addedEnvironmentVariables)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value.ToString(System.IO.Path.PathSeparator);
                }
            }

            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardInput = true;

            var arguments = commandLineArguments.ToString(' ');
            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                //TODO: should this include the length of the executable path too?
                if (arguments.Length >= 32767)
                {
                    if (null == useResponseFileOption)
                    {
                        throw new Bam.Core.Exception("Command line is {0} characters long, but response files are not supported by the tool {1}", arguments.Length, executablePath);
                    }

                    var responseFilePath = System.IO.Path.GetTempFileName();
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(responseFilePath))
                    {
                        Bam.Core.Log.DebugMessage("Written response file {0} containing:\n{1}", responseFilePath, arguments);
                        // escape any back slashes
                        writer.WriteLine(arguments.Replace(@"\", @"\\"));
                    }

                    arguments = System.String.Format("{0}{1}", useResponseFileOption, responseFilePath);
                }
            }
            processStartInfo.Arguments = arguments;

            Bam.Core.Log.Detail("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments);

            // useful debugging of the command line processor
            Bam.Core.Log.DebugMessage("Working directory: '{0}'", processStartInfo.WorkingDirectory);
            if (processStartInfo.EnvironmentVariables.Count > 0)
            {
                Bam.Core.Log.DebugMessage("Environment variables:");
                foreach (var envVar in processStartInfo.EnvironmentVariables.Cast<System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                {
                    Bam.Core.Log.DebugMessage("\t{0} = {1}", envVar.Key, envVar.Value);
                }
            }

            System.Diagnostics.Process process = null;
            int exitCode = -1;
            try
            {
                process = new System.Diagnostics.Process();
                process.StartInfo = processStartInfo;
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.OutputDataReceived);
                process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.ErrorDataReceived);
                process.Start();
                process.StandardInput.Close();
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
            }
            if (null != process)
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                // TODO: need to poll for an external cancel op?
                // poll for the process to exit, as some processes seem to get stuck (hdiutil attach, for example)
                while (!process.HasExited)
                {
                    process.WaitForExit(2000);
                }
                // this additional WaitForExit appears to be needed in order to finish reading the output and error streams asynchronously
                // without it, output is missing from a Native build when executed in many threads
                process.WaitForExit();

                exitCode = process.ExitCode;
                //Bam.Core.Log.DebugMessage("Tool exit code: {0}", exitCode);
                process.Close();
            }

            if (exitCode != 0)
            {
                var message = new System.Text.StringBuilder();
                message.AppendFormat("Command failed: {0} {1}", processStartInfo.FileName, processStartInfo.Arguments);
                message.AppendLine();
                message.AppendFormat("Command exit code: {0}", exitCode);
                message.AppendLine();
                throw new Bam.Core.Exception(message.ToString());
            }
        }
Exemple #56
0
        /// <summary>
        /// Upload Token to connected device
        /// </summary>
        /// <returns>True if successful</returns>
        private bool uploadDebugToken()
        {
            bool success = false;

            if (string.IsNullOrEmpty(DeviceIP))
            {
                return success;
            }
            else if (!File.Exists(LocalFolder + "DebugToken.bar"))
            {
                return success;
            }

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived);

            /// Request Debug Token
            startInfo.FileName = "cmd.exe";
            startInfo.WorkingDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\BlackBerry\\VSPlugin-NDK\\qnxtools\\bin\\";
            startInfo.Arguments = string.Format(@"/C blackberry-deploy.bat -installDebugToken ""{0}"" -device {1} -password {2}", LocalFolder + "DebugToken.bar", DeviceIP, DevicePassword);

            try
            {
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    success = false;
                }
                else
                {
                    success = true;
                }
                p.Close();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
                success = false;
            }

            return success;
        }
Exemple #57
0
        /// <summary>
        /// Execute Awk 
        /// </summary>
        public void ExecScript(Dictionary<Type, IFrontEndConfig> referencesConfig)
        {
            #region write temp files
            string sNppAwkPluginDataPath = Path.Combine(TempDirectory, this.Script.Title+".Data{0}.txt");
            string sNppAwkPluginScriptPath = Path.Combine(TempDirectory, this.Script.Title+".awk");

            if (!Directory.Exists(TempDirectory))
            {
                Directory.CreateDirectory(TempDirectory);
            }

            for (int i=0 ; i<this.Data.Count ; i++)
            {
                string sData = this.Data[i];
                string sFichPath = string.Format(sNppAwkPluginDataPath, i == 0 ? string.Empty : (i + 1).ToString());
                using (StreamWriter oStreamData = new StreamWriter(sFichPath, false, Encoding.Default))
                {
                    oStreamData.Write(sData);
                    oStreamData.Flush();
                }
            }

            string finalScript = this.Script.GenerateFinalScript(mConfig);
            using (StreamWriter oStreamScript = new StreamWriter(sNppAwkPluginScriptPath, false, Encoding.Default))
            {
                oStreamScript.Write(finalScript);
                oStreamScript.Flush();
            }

            foreach (string reference in ScriptHelper.ParseReferences(finalScript))
            {
                //copy all references in the temp directory
                string[] tab = reference.Split('|');
                string referenceType = "FILE";
                string referenceValue = reference;
                if (tab.Length == 2)
                {
                    referenceType = tab[0].ToUpper();
                    referenceValue = tab[1];
                }

                switch (referenceType)
                {
                    case "FILE":
                        {
                            if (File.Exists(referenceValue))
                            {
                                File.Copy(referenceValue, Path.Combine(TempDirectory, Path.GetFileName(referenceValue)));
                            }
                        }
                        break;
                    case "SCRIPT":
                        {
                            IScript s = mConfig.GetScript(referenceValue);
                            if (s == null)
                            {
                                foreach (IFrontEndConfig c in referencesConfig.Values)
                                {
                                    s = c.GetScript(referenceValue);
                                    if (s != null)
                                    {
                                        break;
                                    }
                                }
                            }

                            if (s != null)
                            {
                                using (StreamWriter writer = new StreamWriter(Path.Combine(TempDirectory, s.Title + "." + s.Type.ToString().ToLower()),false))
                                {
                                    writer.Write(s.GenerateFinalScript(mConfig));
                                    writer.Flush();
                                }
                            }
                        }
                        break;
                    default :
                        throw new NotImplementedException("Unknown reference type");
                }
            }
            #endregion

            #region execute Awk process
            moResult = new StringBuilder();
            moError = new StringBuilder();

            //format Awk arguments
            StringBuilder oArgs = new StringBuilder();
            foreach (string sElt in Args)
            {
                oArgs.Append(sElt);
                oArgs.Append(" ");
            }

            StringBuilder oScriptPath = new StringBuilder(260);
            Win32Helper.GetShortPathName(sNppAwkPluginScriptPath, oScriptPath, oScriptPath.Capacity);

            StringBuilder oDataPaths = new StringBuilder();
            for (int i = 0; i < this.Data.Count; i++)
            {
                StringBuilder oDataPath = new StringBuilder(260);
                Win32Helper.GetShortPathName(string.Format(sNppAwkPluginDataPath, i == 0 ? string.Empty : (i + 1).ToString()), oDataPath, oDataPath.Capacity);
                oDataPaths.Append(oDataPath.ToString());
                if (i < this.Data.Count - 1)
                {
                    oDataPaths.Append(" ");
                }
            }

            System.Diagnostics.ProcessStartInfo oInfo = new System.Diagnostics.ProcessStartInfo(ExePath, string.Format("--posix {0} -f {1} {2}", oArgs.ToString(), oScriptPath.ToString(), oDataPaths.ToString()));
            oInfo.UseShellExecute = false;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;
            oInfo.CreateNoWindow = true;
            oInfo.WorkingDirectory = TempDirectory;

            System.Diagnostics.Process oProcess = new System.Diagnostics.Process();
            oProcess.StartInfo = oInfo;
            oProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(oProcess_OutputDataReceived);
            oProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(oProcess_ErrorDataReceived);

            oProcess.Start();
            try
            {
                oProcess.BeginOutputReadLine();
                oProcess.BeginErrorReadLine();
                oProcess.WaitForExit();
            }
            finally
            {
                oProcess.Close();
            }
            #endregion
        }
Exemple #58
0
        /// <summary>
        /// Read the author information from the debug token and update the appropriate boxes.
        /// </summary>
        public void setAuthorInfo()
        {
            if (!File.Exists(_localRIMFolder + "DebugToken.bar"))
            {
                // Create the dialog instance without Help support.
                var DebugTokenDialog = new DebugToken.DebugTokenDialog();
                // Show the dialog.
                if (!DebugTokenDialog.IsClosing)
                    DebugTokenDialog.ShowDialog();
            }

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived);

            /// Get Device PIN
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = string.Format(@"/C blackberry-airpackager.bat -listManifest ""{0}""", _localRIMFolder + "DebugToken.bar");

            try
            {
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                p.Close();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// Get the device Info of the connected device
        /// </summary>
        /// <returns>True if successful</returns>
        public bool getDeviceInfo()
        {
            bool success = false;

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(DeviceInfoDataReceived);

            /// Get Device PIN
            startInfo.FileName = "cmd.exe";
            startInfo.WorkingDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\BlackBerry\\VSPlugin-NDK\\qnxtools\\bin\\";
            startInfo.Arguments = string.Format("/C blackberry-deploy.bat -listDeviceInfo {0} {1}", DeviceIP, DevicePassword == "" ? "" : "-password " + DevicePassword);

            try
            {
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    success = false;
                }
                else
                {
                    success = true;
                }

                p.Close();
                if (_errors != "")
                {
                    int begin = _errors.IndexOf("java.io.IOException: ");
                    if (begin != -1)
                    {
                        begin += 20;
                        int end = _errors.IndexOf("\n", begin);
                        MessageBox.Show(_errors.Substring(begin, end - begin) + "\n\nSee the Debug Output window for details.", "Could not get the device Info of the connected device.", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                        MessageBox.Show(_errors + "See the Debug Output window for details.", "Could not get the device Info of the connected device.", MessageBoxButton.OK, MessageBoxImage.Error);

                    _errors = "";
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
                success = false;
                if (_errors != "")
                {
                    int begin = _errors.IndexOf("java.io.IOException: ");
                    if (begin != -1)
                    {
                        begin += 20;
                        int end = _errors.IndexOf("\n", begin);
                        MessageBox.Show(_errors.Substring(begin, end - begin) + "\n\nSee the Debug Output window for details.", "Could not get the device Info of the connected device.", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                        MessageBox.Show(_errors + "See the Debug Output window for details.", "Could not get the device Info of the connected device.", MessageBoxButton.OK, MessageBoxImage.Error);

                    _errors = "";
                }
            }

            return success;
        }
        /// <summary>
        /// Install Specified API
        /// </summary>
        /// <param name="version">version of API to install</param>
        /// <returns>true if successful</returns>
        public bool InstallAPI(string version, bool isRuntime, bool isSimulator)
        {
            bool success = false;
            _isRuntime = isRuntime;
            _isSimulator = isSimulator;
            _error = "";

            installVersion = version;

            Status = "Installing API Level";

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = p.StartInfo;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;
            p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);
            p.EnableRaisingEvents = true;
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(InstallDataReceived);
            p.Exited += new EventHandler(p_Exited);

            /// Get Device PIN
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = string.Format(@"/C " + bbndkPathConst + @"\eclipsec --install {0} {1} {2}", version, isRuntime ? "--runtime" : "", isSimulator ? "--simulator" : "");

            try
            {
                IsInstalling = true;
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                int parentProcessID = p.Id;
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ParentProcessId=" + parentProcessID);
                ManagementObjectCollection collection = searcher.Get();
                foreach (ManagementObject item in collection)
                {
                    try
                    {
                        installProcessID.Add(Convert.ToInt32(item["ProcessId"].ToString()));
                    }
                    catch (Exception e)
                    {
                    }
                }

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
                System.Diagnostics.Debug.WriteLine(e.Message);
                success = false;
            }

            return success;
        }