Exemple #1
0
        private void DataSourceWizard_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_CurrentConfig is ConfigCoachCRMAccess)
            {
                System.Diagnostics.Process DownloadProgram = (_CurrentConfig as ConfigCoachCRMAccess).DownloadListProgram;

                if (DownloadProgram != null && !DownloadProgram.HasExited)
                {
                    DownloadProgram.Kill();

                    DownloadProgram.Dispose();

                    DownloadProgram = null;
                }

                DownloadProgram = (_CurrentConfig as ConfigCoachCRMAccess).DownloadDataProgram;

                if (DownloadProgram != null && !DownloadProgram.HasExited)
                {
                    DownloadProgram.Kill();

                    DownloadProgram.Dispose();

                    DownloadProgram = null;
                }
            }
        }
Exemple #2
0
 public static void shutDown()
 {
     if (serverProces != null)
     {
         serverProces.Kill();
     }
 }
Exemple #3
0
        /// <summary>
        /// Sends a close message to the process. Immediately stops the process if it has not closed after maxExitWaitTime.
        /// </summary>
        /// <param name="maxExitWaitTime">The maximum exit wait time.</param>
        /// <exception cref="System.InvalidOperationException">Cannot Terminate Non-Running Process.</exception>
        /// <exception cref="System.ObjectDisposedException">Object Has Been Disposed</exception>
        public void Stop(int maxExitWaitTime)
        {
            this.ThrowIfDisposed();
            this.ThrowIfCannotTerminate();

            process.CloseMainWindow();
            if (!process.WaitForExit(maxExitWaitTime))
            {
                process.Kill();
            }
        }
Exemple #4
0
 private void buttonCancel_Click(object sender, RoutedEventArgs e)
 {
     if (proc != null)
     {
         if (!proc.HasExited)
         {
             proc.Kill();
         }
     }
     this.Close();
 }
Exemple #5
0
 void StopDDD()
 {
     m_ddd.Disconnect();
     m_ddd = null;
     if (Properties.Settings.Default.RunDDDServer)
     {
         if (m_dddProcess != null)
         {
             m_dddProcess.Kill();
         }
         m_dddProcess = null;
     }
 }
Exemple #6
0
        public static int CleanProcess(bool isQuit, string processName)
        {
            int count = 0;

            if (string.IsNullOrEmpty(processName))
            {
                return(count);
            }
            System.Diagnostics.Process[] lcProcessList = System.Diagnostics.Process.GetProcessesByName(processName);

            for (int k = 0; k < lcProcessList.Length; k++)
            {
                count++;
                if (!isQuit)
                {
                    continue;
                }
                System.Diagnostics.Process lcProcess = lcProcessList[k];
                if (lcProcess.MainWindowHandle != IntPtr.Zero)
                {
                    lcProcess.Kill();
                }
                else
                {
                    List <IntPtr> hWndList = new List <IntPtr>();
                    EnumWindows(
                        delegate(IntPtr hWnd, int lParam)
                    {
                        uint procId = 0;
                        uint result = GetWindowThreadProcessId(hWnd, ref procId);
                        if (procId == lcProcess.Id)
                        {
                            hWndList.Add(hWnd);
                        }
                        return(1);
                    }
                        , IntPtr.Zero
                        );
                    foreach (IntPtr hWnd in hWndList)
                    {
                        int style   = GetWindowLong(hWnd, GWL_STYLE);
                        int styleEx = GetWindowLong(hWnd, GWL_EXSTYLE);
                        if (style > 0)
                        {
                            lcProcess.Kill();
                        }
                    }
                }
            }
            return(count);
        }
Exemple #7
0
        public override void Disconnect(Response response, dynamic args)
        {
            try {
                if (!(iOSDebuggerProcess?.HasExited ?? true))
                {
                    iOSDebuggerProcess?.StandardInput?.WriteLine("\r\n");
                    iOSDebuggerProcess?.Kill();
                    iOSDebuggerProcess = null;
                }
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
            IDEManager.Shared.StopMonitoring();
            if (_attachMode)
            {
                lock (_lock) {
                    if (_session != null)
                    {
                        _debuggeeExecuting = true;
                        _breakpoints.Clear();
                        _session.Breakpoints.Clear();
                        _session.Continue();
                        _session = null;
                    }
                }
            }
            else
            {
                // Let's not leave dead Mono processes behind...
                if (_process != null)
                {
                    _process.Kill();
                    _process = null;
                }
                else
                {
                    PauseDebugger();
                    DebuggerKill();

                    while (!_debuggeeKilled)
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                }
            }

            SendResponse(response);
        }
        public bool WaitForExit(int milliseconds)
        {
            if (_process.WaitForExit(milliseconds))
            {
                return(true);
            }

            _process.Refresh();
            if (!_process.HasExited)
            {
                _process.Kill();
            }

            return(false);
        }
 public void CancelExecution()
 {
     try
     {
         ExecutionCancelled = true;
         if (this.IsPackagePerformanceVisualization)
         {
             if (process != null && !process.HasExited)
             {
                 process.Kill();
                 process.WaitForExit();
             }
         }
         else
         {
             if (pipelineBreakdownTestDirector != null)
             {
                 pipelineBreakdownTestDirector.CancelExecution();
             }
         }
         timer1_Tick(null, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Problem stopping execution of package:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
     }
 }
Exemple #10
0
        static void Main(string[] args)
        {
            System.IO.StreamReader sErr;
            System.IO.StreamReader sOut;
            String tempErr, tempOut;

            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo.FileName               = @"NET";
            myProcess.StartInfo.Arguments              = @"USE Y:\192.168.0.150\SFTP sftp2018 /user:\SFTP\"; //password is 123456, username is Administrator
            myProcess.StartInfo.CreateNoWindow         = true;
            myProcess.StartInfo.UseShellExecute        = false;
            myProcess.StartInfo.RedirectStandardError  = true;
            myProcess.StartInfo.RedirectStandardOutput = true; // 導出 StandardOutput
            try
            {
                myProcess.Start();
                myProcess.WaitForExit(10000);

                if (!myProcess.HasExited)
                {
                    myProcess.Kill();
                    Console.Write("執行失敗!!");
                }
                else
                {
                    sErr    = myProcess.StandardError;
                    tempErr = sErr.ReadToEnd();
                    sErr.Close();

                    sOut    = myProcess.StandardOutput;
                    tempOut = sOut.ReadToEnd();
                    sOut.Close();

                    if (myProcess.ExitCode == 0) //連線磁碟機建立成功
                    {
                        ////Response.Write("執行成功" + "<BR>" + tempOut.ToString()); // 把執行結果也印出來
                        //System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
                    }
                    else if (myProcess.ExitCode == 2) // 忽略連線磁碟機已存在
                    {
                        var savePath = Directory.GetFiles(@"");
                        //System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
                    }
                    else
                    {
                        Console.Write(tempErr);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                myProcess.Close();
            }
            finally
            {
                myProcess.Close();
                Console.ReadLine();
            }
        }
Exemple #11
0
 internal static bool runShellCommand(string command)
 {
     System.Diagnostics.Process p = new System.Diagnostics.Process {
         StartInfo = new System.Diagnostics.ProcessStartInfo {
             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
             FileName    = "cmd.exe",
             Arguments   = (@"CMD /C " + command)
         }
     };
     p.Start();
     p.WaitForExit(5000);
     if (p.HasExited == false)    //Check to see if the process is still running.
     {
         if (p.Responding)        //Test to see if the process is hung up.
         {
             p.CloseMainWindow(); //Process was responding; close the main window.
             return(false);
         }
         else
         {
             p.Kill(); //Process was not responding; force the process to close.
             return(false);
         }
     }
     return(true);
 }
Exemple #12
0
        private static List <string> PLCsList(out int iTimeOut, out int iThreadSleep, out int iLoopCount)
        {
            List <string> Address = new List <string>();

            iTimeOut     = 1;
            iThreadSleep = 1;
            iLoopCount   = 1;

            try
            {
                string SciezkaDoPlikuZapisu = @"PLCList.json";
                string Data       = System.IO.File.ReadAllText(SciezkaDoPlikuZapisu);
                var    PLCAdresIP = JsonConvert.DeserializeObject <List <PLCAdresIP> >(Data);
                Address      = PLCAdresIP[0].AdresIP;
                iThreadSleep = Int32.Parse(PLCAdresIP[0].ThreadSleep);
                iLoopCount   = Int32.Parse(PLCAdresIP[0].LoopCount);
                iTimeOut     = Int32.Parse(PLCAdresIP[0].TimeOut);
            }
            catch (Exception ex)
            {
                MessageBox.Show("A handled exception just occurred: \n" + ex.Message, "Exception number 0x0002", MessageBoxButton.OK, MessageBoxImage.Error);
                System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
                process.Kill();
            }
            return(Address);
        }
Exemple #13
0
        /// <summary>
        /// Runs a commandline program and returns stdout as a string.
        /// </summary>
        /// <returns>The stdout value.</returns>
        /// <param name="cmd">The command to run.</param>
        /// <param name="args">The commandline arguments.</param>
        private static string RunProgramAndReadOutput(string cmd, string args)
        {
            System.Diagnostics.Process pi = null;
            try
            {
                var psi = new System.Diagnostics.ProcessStartInfo(cmd, args)
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true, // Suppress error messages
                    RedirectStandardInput  = false,
                    UseShellExecute        = false
                };

                pi = System.Diagnostics.Process.Start(psi);
                pi.WaitForExit(5000);
                if (pi.HasExited)
                {
                    return(pi.StandardOutput.ReadToEnd().Trim());
                }
            }
            catch
            {
            }
            finally
            {
                if (pi != null && !pi.HasExited)
                {
                    try { pi.Kill(); }
                    catch { }
                }
            }

            return(null);
        }
Exemple #14
0
 public static void PrintExcelFile(string filePath, ref string szErr)
 {
     Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
     try
     {
         xlApp.Visible = true;
         object oMissing = System.Reflection.Missing.Value;
         Microsoft.Office.Interop.Excel.Workbook  xlWorkbook  = xlApp.Workbooks.Open(filePath, 0, true, 5, oMissing, oMissing, true, 1, oMissing, false, false, oMissing, false, oMissing, oMissing);
         Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets[1];
         //xlWorksheet.PrintPreview(null);
         //xlWorksheet.PrintPreview(true);
         //xlApp.Visible = false;
         //xlWorksheet = null;
         xlWorksheet.PrintOut(1, 1, 2, true);//.PrintOutEx()
     }
     catch (Exception ex)
     {
         szErr = ex.ToString();
     }
     finally
     {
         IntPtr t = new IntPtr(xlApp.Hwnd);
         xlApp = null;
         GC.Collect();
         int k = 0;
         GetWindowThreadProcessId(t, out k);                                          //得到本进程唯一标志k
         System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
         p.Kill();                                                                    //关闭进程k
     }
 }
Exemple #15
0
        private static double PingTimeAverage(string host, int echoNum, int iTimeOut)
        {
            long totalTime  = 0;
            Ping pingSender = new Ping();

            try
            {
                for (int i = 0; i < echoNum; i++)
                {
                    PingReply reply = pingSender.Send(host, iTimeOut);
                    if (reply.Status == IPStatus.Success)
                    {
                        totalTime += reply.RoundtripTime;
                    }
                    if (reply.Status == IPStatus.TimedOut)
                    {
                        totalTime = 9999 * echoNum;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("A handled exception just occurred: \n" + ex.Message, "Exception number 0x0004", MessageBoxButton.OK, MessageBoxImage.Error);
                System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
                process.Kill();
            }
            return(totalTime / echoNum);
        }
 public void OnStop(StopReason reason)
 {
     if (process != null)
     {
         pipePackets.Enqueue(null);
         try {
             if (!Task.WaitAll(new [] { stdInTask, stdOutTask, stdErrorTask }, 333))
             {
                 processCancellationToken.Cancel();
                 Task.WaitAll(new [] { stdInTask, stdOutTask, stdErrorTask }, 333);
             }
         }
         catch (AggregateException) {
         }
         try {
             if (!process.HasExited)
             {
                 if (!process.CloseMainWindow() ||
                     !process.WaitForExit(1000))
                 {
                     process.Kill();
                 }
             }
         }
         catch (System.ComponentModel.Win32Exception) {
         }
         catch (InvalidOperationException) {
         }
         process.Close();
         process = null;
         processCancellationToken = null;
     }
     Sink.OnStop(reason);
 }
Exemple #17
0
        public static int Exec(string executable, string arguments, int timeoutInMilliseconds = 20 * 1000)
        {
            var psi = new System.Diagnostics.ProcessStartInfo();

            psi.UseShellExecute = false;
            psi.FileName        = executable;
            psi.Arguments       = arguments;
            //psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            using (var p = new System.Diagnostics.Process()
            {
                StartInfo = psi,
            })
            {
                p.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
                p.ErrorDataReceived  += (s, e) => Console.Error.WriteLine(e.Data);

                p.Start();
                var exitedBeforeTimeout = p.WaitForExit(timeoutInMilliseconds);
                if (!exitedBeforeTimeout)
                {
                    p.Kill();
                    return(Int32.MaxValue);
                }
                return(p.ExitCode);
            }
        }
Exemple #18
0
        protected void ReleaseExcel(ref MSOffice.Application excelApp, ref MSOffice.Workbook excelBook, ref MSOffice.Worksheet excelSheet)
        {
            try
            {
                excelBook.Close(false, null, null);
                excelApp.Quit();
                GC.Collect();

                IntPtr ptr = new IntPtr(excelApp.Hwnd);
                int    pid = 0;
                GetWindowThreadProcessId(ptr, out pid);
                System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(pid);

                System.Runtime.InteropServices.Marshal.ReleaseComObject((object)excelApp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject((object)excelBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject((object)excelSheet);
                excelApp   = null;
                excelBook  = null;
                excelSheet = null;

                //最后尝试结束进程,出错表示已销毁
                try
                { proc.Kill(); }
                catch (Exception) { }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #19
0
 public static void MseStop()
 {
     try{
         mseProcess.Kill();
         mseProcess.Close();
     }catch {}
 }
Exemple #20
0
 /// <summary>
 /// Kill a process and all of its children
 /// </summary>
 /// <param name="pid">Process ID.</param>
 private static void KillProcess(int pid)
 {
     System.Diagnostics.Process process = null;
     // Cannot close 'system idle process'.
     if (pid == 0)
     {
         return;
     }
     try
     {
         process = System.Diagnostics.Process.GetProcessById(pid);
         if (process == null)
         {
             Log($"Process with id {pid} is null");
         }
         else
         {
             process.Kill();
         }
     }
     catch (Exception ex)
     {
         Log($"Process with Id {pid} threw exception: {ex.Message}");
     }
 }
        ReadLine(int timeout, string @default)
        {
            using (var process = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    FileName               = "ReadLine.exe",
                    RedirectStandardOutput = true,
                    UseShellExecute        = false
                }
            })
            {
                process.Start();
                var rli = new ReadLineInvoker(process.StandardOutput.ReadLine);
                var iar = rli.BeginInvoke(null, null);

                if (!iar.AsyncWaitHandle.WaitOne(new System.TimeSpan(0, 0, timeout)))
                {
                    process.Kill();
                    return(@default);
                }

                return(rli.EndInvoke(iar));
            }
        }
Exemple #22
0
        public bool CreateReport()
        {
            bool rtn = false;

            try
            {
                if (File.Exists(sourceFile))
                {
                    File.Delete(sourceFile);
                }
                File.Copy(testFile, sourceFile);
                copyTemp();
                Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                excel.Visible = false;
                excel.Workbooks.Open(reportFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                IntPtr t = new IntPtr(excel.Hwnd);
                int    k = 0;
                GetWindowThreadProcessId(t, out k);
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
                p.Kill();
                rtn = true;
                File.Delete(sourceFile);
            }
            catch (Exception ex)
            {
                File.Delete(sourceFile);
                //WriteLog(sourceFileName + "-Excel权限问题或没有安装,数据没有上传!");
                //MessageBox.Show("Excel问题导致上传失败,请重试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                rtn = false;
            }

            return(rtn);
        }
Exemple #23
0
 /// <summary>
 /// 启动外部程序,等待指定时间后退出
 /// </summary>
 /// <param name="appFileName">外部程序文件名(包括路径)</param>
 /// <param name="milliSeconds">等待时长(毫秒)(0-无限期等待)</param>
 /// <returns>
 /// 0-外部程序正常退出
 /// 1-外部程序被强制终止
 /// 2-外部程序没有正常运行
 /// </returns>
 public int RunProcessForWait(string appFileName, int milliSeconds = 0)
 {
     try
     {
         System.Diagnostics.Process proc = System.Diagnostics.Process.Start(appFileName);
         if (proc != null)
         {
             if (milliSeconds == 0)
             {
                 proc.WaitForExit();
                 return(0);
             }
             else
             {
                 proc.WaitForExit(milliSeconds);
                 if (proc.HasExited)
                 {
                     return(0);
                 }
                 else
                 {
                     proc.Kill();
                     return(1);
                 }
             }
         }
         return(2);
     }
     catch (ArgumentException error)
     {
         throw new Exception(error.Message);
     }
 }
Exemple #24
0
        public static void AutoUpdate(string location, string user, string password)
        {
            System.Diagnostics.Process pr = new System.Diagnostics.Process();

            System.Diagnostics.ProcessStartInfo prStart = new System.Diagnostics.ProcessStartInfo();

            prStart.FileName = "AutoUpdate.exe";

            prStart.Arguments = location + " " + AppDomain.CurrentDomain.FriendlyName;

            pr.StartInfo = prStart;

            System.Diagnostics.Process prAgent = ApplicationRun.RunningInstance(MesAgent);

            //System.Diagnostics.Process prDCT = ApplicationRun.RunningInstance(DCTServer);

            pr.Start();

            if (prAgent != null)
            {
                prAgent.Kill();
            }

            // Marked By Hi1/Venus.Feng on 20080908 for Hisense Version : not need to kill DCT in CS
            // The Updater will Kill it
            //if( prDCT != null)
            //{
            //    prDCT.Kill();
            //}
            // End Marked
            Application.Exit();
        }
Exemple #25
0
        private void InitializeProgram()
        {
            try
            {
                // File .exe.config
                Process tempsProcess = Process.GetCurrentProcess();
                if (!Others.ExistFile(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config"))
                {
                    var sw = new StreamWriter(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe.config");
                    sw.WriteLine("<?xml version=\"1.0\"?>");
                    sw.WriteLine("<configuration>");
                    sw.WriteLine("<startup>");
                    sw.WriteLine("<supportedRuntime version=\"v4.0\"/>");
                    sw.WriteLine("</startup>");
                    sw.WriteLine("<runtime>");
                    sw.WriteLine("<loadFromRemoteSources enabled=\"true\"/>");
                    sw.WriteLine("</runtime>");
                    sw.WriteLine("</configuration>");
                    sw.Close();

                    Process.Start(Application.StartupPath + "\\" + tempsProcess.ProcessName + ".exe");
                    tempsProcess.Kill();
                }

                LangSelection.DropDownStyle = ComboBoxStyle.DropDownList;
                Others.GetVisualStudioRedistribuable2013();
            }
            catch (Exception ex)
            {
                Logging.WriteError("Login > InitializeProgram(): " + ex);
            }
        }
Exemple #26
0
        public override void Disconnect(Response response, dynamic args)
        {
            if (_attachMode)
            {
                Debugger.Disconnect();
            }
            else
            {
                // Let's not leave dead Mono processes behind...
                if (_process != null)
                {
                    _process.Kill();
                    _process = null;
                }
                else
                {
                    Debugger.Pause();
                    Debugger.Kill();

                    while (!Debugger.DebuggeeKilled)
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                }
            }

            SendResponse(response);
        }
 private void OnApplicationQuit()
 {
     if (process != null && !process.HasExited)
     {
         process.Kill();
     }
 }
        /// <summary>
        /// METODO para Cerrar la conexion con la Aplicacion de Excel y Matar Proceso
        /// </summary>
        void fu_cer_rar_xls()
        {
            libro_xls.Close(false);
            app_xls.Quit();

            uint ID_proceso = 0;

            //Obtiene el ID del proceso de Excel a cerrar Despues
            GetWindowThreadProcessId((IntPtr)app_xls.Hwnd, out ID_proceso);

            try
            {
                //Mata el proceso de Excel que se obtuvo por ID
                System.Diagnostics.Process proceso_xls = System.Diagnostics.Process.GetProcessById((int)ID_proceso);
                proceso_xls.Kill();
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message);
            }

            //Limpiando las variables de Excel
            app_xls   = null;
            libro_xls = null;
            hoja_xls  = null;
            rango_xls = null;
        }
Exemple #29
0
        public static void RestartProgram(bool updateProgram)
        {
            String huginPOSPath = IOUtil.ProgramDirectory + IOUtil.AssemblyName;

            System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();

            System.Diagnostics.ProcessStartInfo psi;
            if (!File.Exists(huginPOSPath))
            {
                psi = new System.Diagnostics.ProcessStartInfo("ShutDown", "/t 1 /r");
                DisplayAdapter.Cashier.Show(PosMessage.RESTART_COMPUTER);
            }
            else
            {
                if (updateProgram)
                {
                    CreateBatchFile();
                    huginPOSPath = IOUtil.ProgramDirectory + "upgrade.bat";
                }

                psi = new System.Diagnostics.ProcessStartInfo(huginPOSPath, "");
                DisplayAdapter.Cashier.Show(PosMessage.RESTART_PROGRAM);
            }

            System.Diagnostics.Process processStarting = new System.Diagnostics.Process();
            processStarting.StartInfo = psi;

            processStarting.Start();
            currentProcess.Kill();
        }
        /// <summary>
        /// Kill all emulation tasks and sub-processes
        /// </summary>
        public static void KillEmulator()
        {
            if (VMConnected)
            {
                ClientManager.Close();
            }

            StopUpdatingStatus();

            VMConnected              = false;
            frcUserProgramPresent    = false;
            isTryingToRunRobotCode   = false;
            isRunningRobotCode       = false;
            isRunningRobotCodeRunner = false;

            if (IsVMRunning())
            {
                qemuNativeProcess.Kill();
                qemuNativeProcess = null;
                qemuJavaProcess.Kill();
                qemuJavaProcess = null;
                grpcBridgeProcess.Kill();
                grpcBridgeProcess = null;
            }
        }
        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();
        }
Exemple #32
0
		public void CreateRepl(Process replProcess)
		{
			var tabItem = new ReplTab();
			var replEntity = new Entity<ReplState> { CurrentState = new ReplState() };

			WireUpTheTextBoxInputToTheReplProcess(tabItem.InteractiveText, replProcess, replEntity);
			WireUpTheOutputOfTheReplProcessToTheTextBox(tabItem.InteractiveText, replProcess, replEntity);
			WireUpTheReplEditorCommandsToTheEditor(tabItem.InteractiveText, replProcess, replEntity, tabItem);

			tabItem.CloseButton.Click +=
			(o, e) =>
			{
				replProcess.Kill();
				ReplManager.Items.Remove(tabItem);
			};

			ReplManager.Items.Add(tabItem);
			ReplManager.SelectedItem = tabItem;
		  ReplToolWindow.Show();
		}
Exemple #33
0
 internal static bool runShellCommand(string command) {
     System.Diagnostics.Process p = new System.Diagnostics.Process {
         StartInfo = new System.Diagnostics.ProcessStartInfo {
             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
             FileName = "cmd.exe",
             Arguments = (@"CMD /C " + command)
         }
     };
     p.Start();
     p.WaitForExit(5000);
     if (p.HasExited == false) { //Check to see if the process is still running.
         if (p.Responding) {//Test to see if the process is hung up.
             p.CloseMainWindow();//Process was responding; close the main window.
             return false;
         } else {
             p.Kill(); //Process was not responding; force the process to close.
             return false;
         }
     }
     return true;
 }
Exemple #34
0
 static void Main(string[] args)
 {
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     
     process.Kill();
     //InternetExplorer ie = new InternetExplorer();
     //object Empty = 0;
     
     //ie.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(ie_BeforeNavigate2);
     //ie.Visible = true;
     //ie.Navigate("http://www.google.com", ref Empty, ref Empty, ref Empty, ref Empty);
     //for (int i = 0; i < 10; i++)
     //{
     //    Thread.Sleep(500);
     //    SendKeys.Send("{Tab}");
     //}
     //Thread.Sleep(10000);
     //ie.Quit();
    
     //CallBack call = new CallBack(EnumeratorWindow);
     //EnumWindows(call, 0);
 }
Exemple #35
0
        public static void PrintPDF(string path)
        {
            string printerPath = "";
            PrintDialog pd = new PrintDialog();
            var result = pd.ShowDialog();
            if (result == DialogResult.OK)
            {
                printerPath = pd.PrinterSettings.PrinterName;
            }

            //string printer = GetDefaultPrinter();
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = path;
            process.StartInfo.Verb = "printto";
            process.StartInfo.Arguments = "\"" + printerPath + "\"";

            process.Start();

            // I have to use this in case of Adobe Reader to close the window
            process.WaitForInputIdle();
            process.Kill();
        }
Exemple #36
0
        static string Execute(string cmd, string arguments)
        {
            string result = "";
            using (System.Diagnostics.Process shell = new System.Diagnostics.Process())
            {
                shell.StartInfo.UseShellExecute = false;

                shell.StartInfo.FileName = cmd;
                shell.StartInfo.Arguments = arguments;
                shell.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                shell.StartInfo.RedirectStandardOutput = true;
                shell.Start();
                if (shell.WaitForExit(3 * 60 * 1000))
                {
                    result = shell.StandardOutput.ReadToEnd();
                    shell.Close();
                }
                else
                {
                    shell.Kill();
                    Kill(System.IO.Path.GetFileName(cmd), System.IO.Path.GetDirectoryName(cmd));
                    Kill("DW20.exe", System.IO.Path.GetDirectoryName(cmd));
                }
                return result;
            }
        }
Exemple #37
0
        private static void Main()
        {
            Controller controller;
            System.Diagnostics.Process runProgram;
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            int time;

            {
                string
                    controllerString = "-1",
                    buttonsString = "",
                    execString = "",
                    paramsString = "",
                    timeString = "0",
                    clString = Environment.CommandLine;

                string[] stringElements = clString.Split(new string[] { "--" }, StringSplitOptions.RemoveEmptyEntries);
                int buttonCombo = 0, controllerNum = -1;

                foreach (var s in stringElements)
                {
                    if (s.Contains("="))
                    {
                        var lSide = s.Split('=')[0];
                        var rSide = s.Split('=')[1];

                        if (lSide == "buttons" || lSide == "b")
                            buttonsString = rSide;
                        else if (lSide == "exec" || lSide == "e")
                            execString = rSide;
                        else if (lSide == "params" || lSide == "p")
                            paramsString = rSide;
                        else if (lSide == "time" || lSide == "t")
                            timeString = rSide;
                        else if (lSide == "contoller" || lSide == "c")
                            controllerString = rSide;
                    }
                }

                {
                    bool error = false;
                    int oVal = 0;

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    foreach (var b in buttonsString.Split('+')) //Find Button Combo that is required
                    {
                        if (int.TryParse(b, out oVal))
                            buttonCombo += (int)Math.Pow(2, oVal);
                        else
                        {
                            if (buttonsString == string.Empty)
                                Console.WriteLine("A button combination is not specififed.");
                            else
                                Console.WriteLine("The button argument is not used properly.");
                            error = true;
                            break;
                        }
                    }
                    if (!System.IO.File.Exists(execString))
                    {
                        if (execString == string.Empty)
                            Console.WriteLine("An executable is not specififed.");
                        else
                            Console.WriteLine("The executable does not exist, it's possibly an invalid path.");
                        error = true;
                    }
                    if (!int.TryParse(timeString, out time))
                    {
                        Console.WriteLine("The time argument not used properly.");
                        error = true;
                    }
                    if (!int.TryParse(controllerString, out controllerNum))
                    {
                        Console.WriteLine("The controller argument not used properly.");
                        error = true;
                    }
                    if(error)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Command      Alt   Purpose");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("--buttons    --b   Button combination to close the program" + Environment.NewLine +
                                          "                       --b=0+8+6" + Environment.NewLine +
                                          "--exec       --e   Full path to the executable" + Environment.NewLine +
                                          "                       --e=C:\\Emulators\\nestopia.exe" + Environment.NewLine +
                                          "--controller --c   ID of specific controller to use           [Optional]" + Environment.NewLine +
                                          "                       --c=0" + Environment.NewLine +
                                          "--time       --t   Milliseconds to hold down the combination  [Optional]" + Environment.NewLine +
                                          "                       --t=2500" + Environment.NewLine +
                                          "--params     --p   Parameters when launching the program      [Optional]" + Environment.NewLine +
                                          "                       --p=C:\\roms\\NES\\Super Mario Bros..nes");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        return;
                    }
                    else
                        Console.ForegroundColor = ConsoleColor.Gray;
                }

                controller = new Controller(controllerNum, buttonCombo); //Controller class that handles button presses when checked

                runProgram = new System.Diagnostics.Process(); //Start up the program
                runProgram.StartInfo.FileName = execString;
                runProgram.StartInfo.Arguments = paramsString;
                runProgram.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(execString);
                runProgram.Start();
            }

            while(true)
            {
                if (!controller.comboPressed())
                {
                    timer.Restart();
                }
                else if(timer.ElapsedMilliseconds >= time)
                {
                    try
                    {
                        runProgram.Kill();
                    }
                    catch { }
                    return;
                }

                System.Threading.Thread.Sleep(35);
            }
        }
Exemple #38
0
        /// <summary>
        /// Runs the ffmpeg command
        /// </summary>
        public void RunFfmpegCmd()
        {
            // can we run it?
            if (worker != null) {
                Debug.LogError ("Please command is still running. Wait it to complete or kill it first");
                return;
            }

            if(File.Exists(FinalOutfile)) {
                if (!EditorUtility.DisplayDialog ("Overwrite?", FinalOutfile + " exists. Overwrite?", "Yes", "No")) {
                    Debug.Log ("Output file '" + FinalOutfile + "' exists, didn't overwrite");
                    return;
                }
            }

            string ffmpegArgs = BuildFfmpegArgs ();
            Debug.Log ("Running: " + ffmpegPath + " " + ffmpegArgs);

            // start ffmpeg process inside a background worker so that it won't block the UI
            worker = new BackgroundWorker ();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += delegate(object sender, DoWorkEventArgs e) {
                // start the process.
                // currently we're doing it the easy way and not capturing standard input and output
                // for creating better UX.
                var process = new System.Diagnostics.Process ();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo (ffmpegPath, ffmpegArgs);
                process.StartInfo.CreateNoWindow = false;
                process.StartInfo.UseShellExecute = true;
                process.Start ();
                do {
                    process.WaitForExit (200);
                    if (worker.CancellationPending) {
                        process.Kill ();
                    }
                } while(!process.HasExited);
                ffmpegExitCode = process.ExitCode;
            };
            worker.RunWorkerAsync ();
        }
Exemple #39
0
 private void print_Click(object sender, EventArgs e)
 {
     openFileDialog1.ShowDialog();
     System.Diagnostics.Process command = new System.Diagnostics.Process();
     command.StartInfo.FileName = @"C:\Program Files\Adobe\Reader 11.0\Reader\acrord32.exe";
     command.StartInfo.Arguments = "/h /p " + openFileDialog1.FileName;
     command.StartInfo.UseShellExecute = false;
     command.StartInfo.CreateNoWindow = true;
     command.Start();
     command.WaitForExit(31000);
     if (!command.HasExited)
         command.Kill();
     else command.Close();
 }
        // Case1572: 1.1.06.11_Import Context_Normal_contains an archived image
        public void Run_Import_ContextWithArchiveImage_Case1572()
        {
            int runCount = 0;
            foreach (InputDataSet ids in this.Input.DataSets)
            {
                string patientdir = string.Empty;
                runCount++;
                Round r = this.NewRound(runCount.ToString(), "Acquisition");
                CheckPoint pImportAnalysis = new CheckPoint("Import Context", "Import Context using conversiontool");
                r.CheckPoints.Add(pImportAnalysis);

                PatientService pa = new PatientService();
                XMLParameter query = new XMLParameter("filter");
                //XMLParameter psa = new XMLParameter("presentationstate");

                //XMLParameterCollection psaCollection = new XMLParameterCollection();

                for (int i = 0; i < ids.InputParameters.Count; i++)
                {
                    if (ids.InputParameters.GetParameter(i).Step == "patient")
                    {
                        if (ids.InputParameters.GetParameter(i).Key == "patientdir")
                            patientdir = ids.InputParameters.GetParameter(i).Value;
                        else
                            query.AddParameter(ids.InputParameters.GetParameter(i).Key, ids.InputParameters.GetParameter(i).Value);
                    }
                }
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + "\\ConversionTool version 1.0.4.0\\conversiontool.exe";
                p.StartInfo.Arguments = "-P\"" + patientdir + "\"";
                p.Start();
                System.Threading.Thread.Sleep(20000);
                p.Kill();

                XMLResult rslQuery = pa.queryPatients(query);
                string puid = null;

                if (rslQuery.IsErrorOccured)
                {
                    pImportAnalysis.Result = TestResult.Fail;
                    pImportAnalysis.Outputs.AddParameter("archiveFMS Import", "Query Fail:", rslQuery.Message);
                    goto CLEANUP;
                }
                else
                {
                    puid = rslQuery.SingleResult;
                }

                NewPatientService nps = new NewPatientService();
                PatientListObjectsRequestType request = new PatientListObjectsRequestType();
                request.type = PatientListObjectsType.all;
                request.currentSpecified = true;
                request.current = true;
                request.patientInternalId = puid;

                nps.listObjects(request);

                System.Threading.Thread.Sleep(10000);
                PatientListObjectsResponseType response = nps.listObjects(request);

                if (!nps.LastReturnXMLValidateResult.isValid)
                {
                    pImportAnalysis.Result = TestResult.Fail;
                    pImportAnalysis.Outputs.AddParameter("archiveContext Import", "List Fail:", "Response is not complied with XML Schema");
                    goto CLEANUP;
                }

                if (response.status.code != 0)
                {
                    pImportAnalysis.Result = TestResult.Fail;
                    pImportAnalysis.Outputs.AddParameter("archiveContext Import", "List Fail:", response.status.message);
                    goto CLEANUP;
                }

                if (ids.ExpectedValues.GetParameter("currentps").Value != null)
                {
                    if (response.presentationStates.Length.ToString() != ids.ExpectedValues.GetParameter("currentps").Value)
                    {
                        pImportAnalysis.Result = TestResult.Fail;
                        pImportAnalysis.Outputs.AddParameter("archiveContext Import", "Import Fail:", "Expected" + ids.ExpectedValues.GetParameter("currentps").Value + "PS, actual:" + response.presentationStates.Length.ToString());
                        goto CLEANUP;
                    }
                }

                request.current = false; // below to check non-current PS and analysis
                response = nps.listObjects(request);
                if (!nps.LastReturnXMLValidateResult.isValid)
                {
                    pImportAnalysis.Result = TestResult.Fail;
                    pImportAnalysis.Outputs.AddParameter("archiveContext Import", "List Fail:", "Response is not complied with XML Schema");
                    goto CLEANUP;
                }

                if (response.status.code != 0)
                {
                    pImportAnalysis.Result = TestResult.Fail;
                    pImportAnalysis.Outputs.AddParameter("archiveContext Import", "List Fail:", response.status.message);
                    goto CLEANUP;
                }

                if (ids.ExpectedValues.GetParameter("noncurrentps").Value != null)
                {
                    if (response.presentationStates == null || response.presentationStates.Length.ToString() != ids.ExpectedValues.GetParameter("noncurrentps").Value)
                    {
                        pImportAnalysis.Result = TestResult.Fail;
                        pImportAnalysis.Outputs.AddParameter("archiveContext Import", "Import Fail:", "Expected" + ids.ExpectedValues.GetParameter("noncurrentps").Value + "NON Current PS, actual response:" + nps.LastReturnXML);
                        goto CLEANUP;
                    }
                }

                if (ids.ExpectedValues.GetParameter("noncurrentanalysis").Value != null)
                {
                    if (response.analysiss == null || response.analysiss.Length.ToString() != ids.ExpectedValues.GetParameter("noncurrentanalysis").Value)
                    {
                        pImportAnalysis.Result = TestResult.Fail;
                        pImportAnalysis.Outputs.AddParameter("archiveContext Import", "Import Fail:", "Expected" + ids.ExpectedValues.GetParameter("noncurrentanalysis").Value + "NON Current Analysis, actual response:" + nps.LastReturnXML);
                        goto CLEANUP;
                    }
                }

                pImportAnalysis.Result = TestResult.Pass;
                pImportAnalysis.Outputs.AddParameter("archiveContext Import", "success import the context", "OK");

            CLEANUP:
                if (!string.IsNullOrEmpty(puid))
                {
                    pa.deletePatient(puid);
                }

                SaveRound(r);
            }

            Output();
        }
Exemple #41
0
        //////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// </summary>
        //////////////////////////////////////////////////////////////////////////
        private void OnStart(object sender, DoWorkEventArgs e)
        {
            var nantCommand   = Properties.Settings.Default.NANT_COMMAND;
            var nantArguments = string.Format(Properties.Settings.Default.NANT_PARAMS,  m_Filename, m_TargetNode["name"]);

            var workingDir = Path.GetDirectoryName( m_Filename );

            if ( !Path.IsPathRooted( nantCommand ) && !string.IsNullOrEmpty(workingDir) )
            {//if the path is not rooted, then make it relative to the mFileName path.
                nantCommand = Path.Combine( workingDir, nantCommand );
            }

            try
            {
                string nantOutput = null;

                // Create and initialize the process
                m_NAntProcess = new System.Diagnostics.Process();

                m_NAntProcess.StartInfo.UseShellExecute = false;
                m_NAntProcess.StartInfo.RedirectStandardError = true;
                m_NAntProcess.StartInfo.RedirectStandardOutput = true;
                m_NAntProcess.StartInfo.CreateNoWindow = true;
                m_NAntProcess.StartInfo.FileName = nantCommand;
                m_NAntProcess.StartInfo.WorkingDirectory = workingDir;
                m_NAntProcess.StartInfo.Arguments = nantArguments;

                // Start process
                m_NAntProcess.Start();

                // Read standard output and write string in console
                while ((nantOutput = m_NAntProcess.StandardOutput.ReadLine()) != null)
                {
                    if (m_BackgroundWorker.CancellationPending)
                    {
                        if (!m_NAntProcess.HasExited)
                        {
                            m_NAntProcess.Kill();
                            m_NAntProcess.WaitForExit();
                            e.Cancel = true;
                        }
                    }
                    else
                    {
                        nantOutput += System.Environment.NewLine;
                        m_BackgroundWorker.ReportProgress(0, nantOutput);
                    }
                }
            }
            catch (Exception e1)
            {
                // Trace exception on console
                WriteConsole("[NAntAddin]: Unexpected error occured while executing command: "
                    + Environment.NewLine
                    + "\t" + nantCommand + nantArguments
                    + Environment.NewLine
                    + Environment.NewLine
                    + "An exception has been raised with the following stacktrace:"
                    + Environment.NewLine
                    + "   " + e1.Message
                    + Environment.NewLine
                    + e1.StackTrace
                    + Environment.NewLine
                    + Environment.NewLine
                    + "Please check that NAnt command path is properly configured within NAntAddin options."
                    + Environment.NewLine
                );
            }
        }
        public void Execute(params object[] args)
        {
            string importPath = Params.importPath;
            string statusMessage = "Started import from  " + Params.Instance.importName;
            m_application.Messenger.AddInfo(statusMessage);
            m_application.MainWindow.StatusBar.WorkingStatus = statusMessage;
            Mouse.OverrideCursor = Cursors.Wait;

            // If Import program exists then call program
            if (File.Exists(importPath))
            {

                // Create temp output file
                string tempOrdersFile = System.IO.Path.GetTempFileName();

                // Create new Import process
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = importPath;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.Arguments = tempOrdersFile;
                try
                {
                    // Start Process
                    p.Start();
                    p.WaitForExit(600 * 1000);
                    // Abort process if it runs for more than 10 minutes.
                    if (p.HasExited == false)
                        p.Kill();

                    //If exectutable was successful
                    if (p.ExitCode == 0)
                    {
                        processOrders(tempOrdersFile);
                        m_application.Project.Save();
                        statusMessage = "Importing from " + Params.Instance.importName + " completed.";
                        m_application.Messenger.AddInfo(statusMessage);
                    }
                    else
                    {
                        statusMessage = "Import from " + Params.Instance.importName + " failed with Exit Code: " + p.ExitCode.ToString();
                        m_application.Messenger.AddError(statusMessage);
                    }

                    if (File.Exists(tempOrdersFile))
                        File.Delete(tempOrdersFile);

                }
                catch (Exception e)
                {
                    statusMessage = " Import from " + Params.Instance.importName + " failed: " + e.Message;
                    m_application.Messenger.AddError(statusMessage);
                }

                finally
                {
                    if (p != null)
                        p.Close();

                }
            }

            else
            {
                statusMessage = " Import from " + Params.Instance.importName + " failed! Specified file does not exist.";
                m_application.Messenger.AddError(statusMessage);
            }

            m_application.MainWindow.StatusBar.WorkingStatus = null;
            Mouse.OverrideCursor = null;
        }
        //Case 1570: 1.1.06.02_Import an archived FMS_Normal_contains shortcut of archived image(French FE Tool)
        public void Run_Import_ArchivedFMS_Case1570()
        {
            int runCount = 0;

            foreach (InputDataSet ids in this.Input.DataSets)
            {
                runCount++;
                Round r = this.NewRound(runCount.ToString(), "Import FMS1");
                CheckPoint pImportFMS = new CheckPoint("Import FMS1", "Import FMS using conversiontool");
                r.CheckPoints.Add(pImportFMS);
                string patientdir = ids.InputParameters.GetParameter("patientdir").Value;
                string patient_id = ids.InputParameters.GetParameter("patient_id").Value;
                string dpms_id = ids.InputParameters.GetParameter("dpms_id").Value;

                //call conversiontool to import archivedFMS
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + "\\ConversionTool version 1.0.4.0\\conversiontool.exe";
                p.StartInfo.Arguments = "-P\"" + patientdir + "\"";
                p.Start();
                System.Threading.Thread.Sleep(20000);
                p.Kill();

                string puid = null;
                PatientService ps = new PatientService();
                XMLParameter cInputQuery = new XMLParameter("filter");
                cInputQuery.AddParameter("dpms_id", dpms_id);
                cInputQuery.AddParameter("patient_id", patient_id);
                XMLResult rslQuery = ps.queryPatients(cInputQuery);
                if (rslQuery.IsErrorOccured)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "Query Fail:", rslQuery.Message);
                    SaveRound(r);
                    goto CLEANUP;
                }

                puid = rslQuery.SingleResult;
                //trigger the post import of FMS
                NewPatientService nps = new NewPatientService();
                PatientListObjectsRequestType request = new PatientListObjectsRequestType();
                request.type = PatientListObjectsType.all;
                request.currentSpecified = true;
                request.current = true;
                request.patientInternalId = puid;

                nps.listObjects(request);

                //wait the post import completed
                System.Threading.Thread.Sleep(10000);
                PatientListObjectsResponseType response = nps.listObjects(request);

                if (!nps.LastReturnXMLValidateResult.isValid)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "List Fail:", "Response is not complied with XML Schema");
                    SaveRound(r);
                    goto CLEANUP;
                }

                if (response.status.code != 0)
                {

                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "List Fail:", response.status.message);
                    SaveRound(r);
                    goto CLEANUP;
                }
                if (response.fmss == null)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "Import Fail:", "Expected 3 fms, actual none.");
                    SaveRound(r);
                    goto CLEANUP;
                }
                else if (response.fmss.Length != 3)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "Import Fail:", "Expected 3 fms, actual:" + response.fmss.Length.ToString());
                    SaveRound(r);
                    goto CLEANUP;
                }

                if (response.presentationStates == null)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "Import Fail:", "Expected 21 PS, actual none.");
                    SaveRound(r);
                    goto CLEANUP;
                }
                else if (response.presentationStates.Length != 21)
                {
                    pImportFMS.Result = TestResult.Fail;
                    pImportFMS.Outputs.AddParameter("archiveFMS Import", "Import Fail:", "Expected 21 PS, actual:" + response.presentationStates.Length.ToString());
                    SaveRound(r);
                    goto CLEANUP;
                }

                foreach (PresentationStateType pstate in response.presentationStates)
                {
                    if (pstate.image.tags != "archived" || pstate.image.archivePath == string.Empty)
                    {
                        pImportFMS.Result = TestResult.Fail;
                        pImportFMS.Outputs.AddParameter("archiveFMS Import", "Check Fail:", "archive tag or path is not correct");
                        SaveRound(r);
                        goto CLEANUP;
                    }
                }

                pImportFMS.Result = TestResult.Pass;
                pImportFMS.Outputs.AddParameter("archiveFMS Import", "Check Success:", "OK");
                SaveRound(r);

            CLEANUP:
                if (!string.IsNullOrEmpty(puid))
                {
                    ps.deletePatient(patient_id); //delete the patient
                }
            }
            Output();
        }
        public bool RunPyScript(string sArguments, int iTimeOutMinutes)
        {

            System.Diagnostics.ProcessStartInfo procStartInfo = null;
            System.Diagnostics.Process proc = null;
            RegistryKey rk = null;
            string sCommand = string.Empty;
            try
            {
                // Get sPythonDir from registry
                string sPythonDir = @"C:\Python27\ArcGIS10.1\";

                string subkey = @"SOFTWARE\Python\PythonCore\2.7\InstallPath";
                string value64 = string.Empty; 
                string value32 = string.Empty; 
                RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
                localKey = localKey.OpenSubKey(subkey);
                if (localKey != null)
                {
                    sPythonDir = localKey.GetValue("").ToString();
                }
                else
                {
                    RegistryKey localKey32 = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
                    localKey32 = localKey32.OpenSubKey(subkey);
                    if (localKey32 != null)
                    {
                        sPythonDir = localKey32.GetValue("").ToString();
                    }

                }

                sCommand = Path.Combine(sPythonDir, "python.exe") + " " + sArguments;                
                // Create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // "/c" tells cmd that you want it to execute the command that follows,
                // then exit.
                procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + sCommand);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.RedirectStandardError = true;
                procStartInfo.UseShellExecute = false;

                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;

                // Now you create a process, assign its ProcessStartInfo, and start it.
                proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                proc.WaitForExit(iTimeOutMinutes * 60 * 1000);


                // Get the output into a string.
                _errOutput = proc.StandardError.ReadToEnd();
                _stdOutput = proc.StandardOutput.ReadToEnd().TrimEnd('\r', '\n');               

                int exitCode = proc.ExitCode;
                Console.WriteLine("Exit Code: {0}", proc.ExitCode);

                if (exitCode != 0 && (!(string.IsNullOrEmpty(_errOutput))))
                {
                    _errOutput = "Error in RunPyScript! Command: " + sCommand + Environment.NewLine + _errOutput;
                    return false;
                }

                return true;
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
                // Log the exception and errors.
                _errOutput = "Error in RunPyScript! Command: " + sCommand + Environment.NewLine + objException.Message;
                return false;
            }
            finally
            {
                if (!(proc == null))
                {
                    if (!(proc.HasExited))
                    {
                        proc.Kill();
                    }
                    proc = null;
                }
                rk = null;
            }
        }
		protected void ScanCRecast () {
	//#if (!UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN) || UNITY_WEBPLAYER || UNITY_IPHONE || UNITY_ANDROID || UNITY_DASHBOARD_WIDGET || UNITY_XBOX360 || UNITY_PS3
#if UNITY_STANDALONE_OSX
			
#if FALSE
			System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
			myProcess.StartInfo.FileName = GetRecastPath ();//"/Users/arong/Recast/build/Debug/Recast";
			//System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo ();
			//startInfo.UseShellExecute = true;
			myProcess.StartInfo.UseShellExecute = false;
			myProcess.StartInfo.RedirectStandardInput = true;
			myProcess.StartInfo.RedirectStandardOutput = true;
			myProcess.StartInfo.Arguments = "";
			
			List<ExtraMesh> extraMeshes;
			//Get all meshes which should be used
			CollectMeshes (out extraMeshes, forcedBounds);
		
			Vector3[] inputVerts;
			int[] inputTris;
			//Get polygon soup from meshes
			Voxelize.CollectMeshes (extraMeshes,forcedBounds,out inputVerts, out inputTris);
			
			//Bild .obj file
			System.Text.StringBuilder arguments = new System.Text.StringBuilder ();
			arguments.Append ("o recastMesh.obj\n");
			for (int i=0;i<inputVerts.Length;i++) {
				arguments.Append ("v "+inputVerts[i].x.ToString ("0.000")+" ").Append (inputVerts[i].y.ToString ("0.000")+" ").Append (inputVerts[i].z.ToString ("0.000"));
				arguments.Append ("\n");
			}
			
			//Build .obj file tris
			for (int i=0;i<inputTris.Length;i+=3) {
				arguments.Append ("f "+(inputTris[i]+1)+"//0 ").Append ((inputTris[i+1]+1)+"//0 ").Append ((inputTris[i+2]+1)+"//0");
#if ASTARDEBUG
				Debug.DrawLine (inputVerts[inputTris[i]],inputVerts[inputTris[i+1]],Color.red);
				Debug.DrawLine (inputVerts[inputTris[i+1]],inputVerts[inputTris[i+2]],Color.red);
				Debug.DrawLine (inputVerts[inputTris[i+2]],inputVerts[inputTris[i]],Color.red);
#endif		
				arguments.Append ("\n");
			}
			
			string tmpPath = System.IO.Path.GetTempPath ();
			tmpPath += "recastMesh.obj";
			
			try {
				using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(tmpPath)) {
					outfile.Write (arguments.ToString ());
				}
				
				myProcess.StartInfo.Arguments = tmpPath
					+"\n"+cellSize+"\n"+
						cellHeight+"\n"+
						walkableHeight+"\n"+
						walkableClimb+"\n"+
						maxSlope+"\n"+
						maxEdgeLength+"\n"+
						contourMaxError+"\n"+
						regionMinSize+"\n"+
						characterRadius;
				
				
		/*		public int erosionRadius = 2; /< Voxels to erode away from the edges of the mesh /
		public float contourMaxError = 2F; /< Max distance from simplified edge to real edge /
		
		public float cellSize = 0.5F; /< Voxel sample size (x,z) /
		public float cellHeight = 0.4F; /< Voxel sample size (y) /
		public float walkableHeight = 2F; /< Character height/
		public float walkableClimb = 0.5F; /< Height the character can climb /
		public float maxSlope = 30; /< Max slope in degrees the character can traverse /
		public float maxEdgeLength = 20; /< Longer edges will be subdivided. Reducing this value can im
		public bool includeOutOfBounds = false;*/
				
				myProcess.Start ();
				System.IO.StreamReader sOut = myProcess.StandardOutput;
				
				//string result = sOut.ReadToEnd ();
				//Debug.Log (result);
				//return;
					
				bool failed = false;
				bool startedVerts = false;
				int readVerts = 0;
				bool startedTris = false;
				int vCount = -1;
				int readTris = 0;
				int trisCount = 0;
				Vector3[] verts = null;
				int[] tris = null;
				int internalVertCount = 0;
				
				Vector3 bmin = Vector3.zero;
				
				float cs = 1F;
				float ch = 1F;
				
				while (sOut.Peek() >= 0) 
		        {
					string line = sOut.ReadLine();
					int resultInt;
					
					if (line == "") {
						continue;
					}
					
		            if (!int.TryParse (line, out resultInt)) {
						//Debug.Log ("Syntax Error at '"+line+"'");
						failed = true;
						break;
					}
					
					if (!startedVerts) {
						verts = new Vector3[resultInt];
						
						if (resultInt == 0) {
							failed = true;
							break;
						}
						
						bmin.x = float.Parse (sOut.ReadLine());
						bmin.y = float.Parse (sOut.ReadLine());
						bmin.z = float.Parse (sOut.ReadLine());
						cs = float.Parse (sOut.ReadLine());
						ch = float.Parse (sOut.ReadLine());
						
						startedVerts = true;
						//Debug.Log ("Starting Reading "+resultInt+" verts "+bmin.ToString ()+" - "+cs+" * "+ch);
					} else if (readVerts < verts.Length) {
						resultInt *= 1;
						if (internalVertCount == 0) {
							verts[readVerts].x = resultInt*cs + bmin.x;
						} else if (internalVertCount == 1) {
							verts[readVerts].y = resultInt*ch + bmin.y;
						} else {
							verts[readVerts].z = resultInt*cs + bmin.z;
						}
						
						internalVertCount++;
						
						if (internalVertCount == 3) {
							internalVertCount = 0;
							readVerts++;
						}
						
					} else if (!startedTris) {
						
						trisCount = resultInt;
						startedTris = true;
					} else if (vCount == -1) {
						vCount = resultInt;
						tris = new int[trisCount*vCount];
						//Debug.Log ("Starting Reading "+trisCount+" - "+tris.Length+" tris at vertsCount "+readVerts);
						//Debug.Log ("Max vertices per polygon: "+vCount);
						
					} else if (readTris < tris.Length) {
						tris[readTris] = resultInt;
						readTris++;
					}
		        }
				
				if (!myProcess.HasExited)
		        {
					try {
						myProcess.Kill();
					} catch {}
		        }
				
				sOut.Close();
		    	myProcess.Close();
				
				if (failed) {
					Debug.LogError ("C Recast Failed");
					return;
				}
				
				SetMatrix (Matrix4x4.TRS (Vector3.zero,Quaternion.identity,Vector3.one));
				
				NavMeshGraph.GenerateNodes (this,verts,tris, out _vectorVertices, out _vertices);
			} finally {
				//Debug.Log (tmpPath);
				System.IO.File.Delete (tmpPath);
			}
#else
			Debug.LogError ("The C++ version of recast is not supported anymore");
#endif
			
	#else
			Debug.LogError ("The C++ version of recast can only be used in osx editor or osx standalone mode, I'm sure it cannot be used in the webplayer, but other platforms are not tested yet\n" +
				"If you are in the Unity Editor, try switching Platform to OSX Standalone just when scanning, scanned graphs can be cached to enable them to be used in a webplayer.");
	#endif
		}
Exemple #46
0
		/// <summary>
		/// Executes an executable.
		/// </summary>
		/// <param name="fileName">Executable name</param>
		/// <param name="parameters">Parameters</param>
		/// <param name="workingDir">Working directory</param>
		/// <param name="waitTillReturn">Wait till return</param>
		static void Execute(string fileName, string parameters, string workingDir, bool waitTillReturn) {
			System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
			bool started = false;
			try
			{
				myProcess.StartInfo.FileName = fileName;
				myProcess.StartInfo.Arguments = parameters;
				myProcess.StartInfo.WorkingDirectory = workingDir;
				myProcess.StartInfo.UseShellExecute = true;
				myProcess.Start();
				started = true;
				if (waitTillReturn) {
					myProcess.WaitForExit();
				}
			}
			catch (Win32Exception e)
			{
				if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
				{
					//Lextm.Windows.Forms.MessageBoxFactory.Error("Check if the path is valid. " + fileName);
				}
				else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
				{
					//Lextm.Windows.Forms.MessageBoxFactory.Error(
					//	"You do not have permission to run this file. " + fileName);
				}
				else if (e.NativeErrorCode == ERROR_NO_ASSOCIATION)
				{
					//Lextm.Windows.Forms.MessageBoxFactory.Error(
					//	"You must install necessary software to see this file. " + fileName);
				}
				else {
					//Lextm.Windows.Forms.MessageBoxFactory.Error(e.Message + " " + fileName);
				}
			}
			finally {
				if (waitTillReturn)
				{
					if (started && !myProcess.HasExited)
					{
						myProcess.Kill();
					}
					myProcess.Close();
				}
			}
		}
Exemple #47
0
        private bool PrintPDF(Investment2 newInvestment)
        {
            //Create the PDF for printing
            string FileName = "FIF_" + this.Investor.LastName + this.Investor.FirstName + ".pdf";
            string tempPath = Path.GetTempPath() + FileName;
            try
            {
                //Working code that creates a printable in-memory pdf
                using (PdfReader reader = new PdfReader(Properties.Resources.FIF_CertificateTemplate))
                {
                    using (FileStream fs = new FileStream(tempPath, FileMode.Create))
                    {
                        using (PdfStamper stamper = new PdfStamper(reader, fs))
                        {
                            stampFields(stamper, newInvestment);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(String.Format("Unable to create or print pdf file. \nError Message: {0}", ex.Message));
                File.Delete(tempPath);
                return false;
            }
            try
            {
                string printerPath = "";
                PrintDialog pd = new PrintDialog();
                var result = pd.ShowDialog();
                if (result == DialogResult.OK)
                {
                    printerPath = pd.PrinterSettings.PrinterName;
                }
                else
                {
                    File.Delete(tempPath);
                    return false;
                }

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {

                    process.StartInfo.FileName = tempPath;
                    process.StartInfo.Verb = "printto";
                    process.StartInfo.Arguments = "\"" + printerPath + "\"";

                    process.Start();

                    // I have to use this in case of Adobe Reader to close the window
                    process.WaitForInputIdle();
                    process.Kill();
                    File.Delete(tempPath);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(String.Format("Unable to send PDF to the printer.  \nError Message: ", ex.Message));
                File.Delete(tempPath);
                return false;
            }
            return true;
        }
Exemple #48
0
        public void realizarOperacion(string rawText)
        {
            switch (rawText)
            {
                case "Encender televisor":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_futbol;
                    break;
                case "Apagar televisor":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_apagada;
                    break;

                case "Encender radio":
                    procMusic = System.Diagnostics.Process.Start("wmplayer.exe", "http://www.stellar-attraction.com/wmp71.asx");
                    break;

                case "Apagar radio":
                    try
                    {
                        if (procMusic != null && procMusic.HasExited == false)
                            procMusic.Kill();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                    break;

                case "Apagar cancion":
                    if(player != null) player.Stop();
                    break;

                case "Encender lampara":
                    pictureBoxLamp.Image = SalonSUA.Properties.Resources.lampara_encendida;
                    break;
                case "Apagar lampara":
                    pictureBoxLamp.Image = SalonSUA.Properties.Resources.lampara_apagada;
                    break;

                case "Poner futbol":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_futbol;
                    break;
                case "Cambiar futbol":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_futbol;
                    break;

                case "Poner serie":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_serie;
                    break;
                case "Cambiar serie":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_serie;
                    break;

                case "Poner pelicula":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_pelicula;
                    break;
                case "Cambiar pelicula":
                    pictureBoxTV.Image = SalonSUA.Properties.Resources.tv_pelicula;
                    break;

                case "Poner cancion":

                case "Cambiar cancion":
                    var path = System.IO.Path.GetFullPath("..\\..\\sound");
                    PlayWAV(path + "\\single.wav", true);
                    break;

                case "Subir temperatura":
                    pictureBoxThermometer.Image = SalonSUA.Properties.Resources.termometro_encender;
                    break;
                case "Bajar temperatura":
                    pictureBoxThermometer.Image = SalonSUA.Properties.Resources.termometro_bajar;
                    break;

            }
        }
Exemple #49
0
 public void launch()
 {
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = file;
     try{
         System.Threading.Thread.Sleep(rand.Next(1, 10) * 1000);
         form.updateStatus("Starting new application..");
         p.Start();
         System.Threading.Thread.Sleep(rand.Next(10, 60) * 1000);
         form.updateStatus("Terminiating application..");
         p.Kill();
     }catch (InvalidOperationException ioe){
     }catch (Exception ex){
         p.Kill();
     }
 }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Try to kill winvnc on exit in case it is still running.
            //Since this is a single instance app there should only be one instance running
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            if (Globals.WinVncProcessID != -1)
            {
                p = System.Diagnostics.Process.GetProcessById(Globals.WinVncProcessID);
                p.Kill();
                p.WaitForExit();  // give time to exit before proceeding to try the delete
            }

            //System.Diagnostics.Process.Start(System.IO.Path.Combine(Globals.ProcomSupportLocalAppDataDirectory, "winvnc.exe") & " -kill")
            //System.Threading.Thread.Sleep(5000)

            try
            {
                // Since this is a single instance app there should only be able to be one copy of this directory
                // So we get rid of our temp files when finished.
                //System.IO.Directory.Delete(Globals.MajorSilenceSupportLocalAppDataDirectory, true);
                if (System.IO.Directory.Exists(Globals.MajorSilenceSupportLocalAppDataDirectory))
                {
                    DeleteFilesRecursively(new DirectoryInfo(Globals.MajorSilenceSupportLocalAppDataDirectory));
                }

            }
            catch (UnauthorizedAccessException uex)
            {
                MessageBox.Show("Error cleaning up temp support files." + uex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (IOException iex)
            {
                MessageBox.Show("Error cleaning up temp support files." + iex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            MessageBox.Show("MajorSilenceConnect Software Support is now closed.", "MajorSilenceConnect Support Closed", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
		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;
			}
		}
 /// <summary>
 /// Wraps and injects a process, used for .NET applications.
 /// </summary>
 /// <exception cref="FileNotFoundException">
 /// A <see cref="FileNotFoundException"/> is thrown if the executable for the wrapper process can't be found.
 /// <br />=OR=<br />
 /// A <see cref="FileNotFoundException"/> is thrown if the library to inject into the wrapper process can't be found.
 /// </exception>
 private void WrapAndInject()
 {
   // Get the location of the files needed.
   var wrapperLocation = HostCore.Configuration.Application.WrapperExecutable;
   var libraryLocation = HostCore.Configuration.Application.LibtoInject;
   if (!File.Exists(wrapperLocation))
     throw new FileNotFoundException("Unable to locate the wrapper executable.", wrapperLocation);
   if (!File.Exists(libraryLocation))
     throw new FileNotFoundException("Unable to locate the library to inject.", libraryLocation);
   // Start wrapper process.
   var startInfo = new ProcessStartInfo
                     {
                       FileName = wrapperLocation,
                       CreateNoWindow = true
                     };
   _process = SystemProcess.Start(startInfo);
   _process.EnableRaisingEvents = true;
   _process.Exited += Process_Exited;
   // Give the process time to start and thereby avoid an AccessViolationException when injecting
   //_process.WaitForInputIdle();  // Based on message-loop detection, incompatible with command line
   Thread.Sleep(500);
   // Inject wrapper.
   try
   {
     RemoteHooking.Inject(
       // The process to inject, in this case the wrapper.
       _process.Id,
       // Absolute paths of the libraries to inject, we use the same one for 32bit and 64bit
       libraryLocation, libraryLocation,
       // The name of the channel to use for IPC.
       _connection.ChannelName,
       // The location of the executable to start the wrapped process from.
       Path.Combine(_startInfo.WorkingDirectory.FileName, _startInfo.Files.Executable.FileName),
       // The arguments to pass to the main method of the executable. 
       _startInfo.Arguments);
   }
   catch (Exception e)
   {
     if (!_process.HasExited) _process.Kill();
     HostCore.Log.Critical("Injection procedure failed.", e);
     throw;
   }
   // Hide wrapper console window.
   if (!_process.HasExited)
     ProcessHelper.SetWindowState(_process.MainWindowHandle, WindowShowStyle.Hide);
 }
Exemple #53
0
		/// <summary>
		/// Restart the file reading at the beginning.
		/// </summary>
		/// <exception cref="IOException">The command cannot be executed.</exception>
		/// <exception cref="InvalidOperationException">The stream is not reopenable</exception>
		protected virtual void Reopen()
		{
			if (!reopenable) throw new InvalidOperationException("The stream is not reopenable.");
			Finish();
			if (proc != null)
			{
				try
				{
					proc.Kill();
					proc.WaitForExit();
				}
				catch
				{
				}
				//proc.WaitForExit();
				proc.Close();
				proc = null;
			}

			exitCode = -10;
			try
			{
				// **** threads must be restarted!!

				if (commandName.IndexOf('\\') < 0 && commandName.IndexOf('/') < 0) // && !File.Exists(commandName))
				{
					// should this be done? ***
					string foundName = FindInPath(commandName);
					if (foundName == null) foundName = FindInPath(commandName + ".exe");
					if (foundName == null) foundName = FindInPath(commandName + ".cmd");
					if (foundName == null) foundName = FindInPath(commandName + ".bat");
					if (foundName == null)
					{
						throw new InvalidOperationException("Stream cannot be created to wrap '" + commandName +
							"' because it cannot be found.");
					}
					commandName = foundName;
				}
				System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(commandName, commandArgs);
				//psi.WorkingDirectory = workingDir;
				psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
				psi.CreateNoWindow = true;
				psi.RedirectStandardInput = !skipStdin;  // is this always OK?
				psi.RedirectStandardOutput = true;
				psi.RedirectStandardError = true;
#if DOTNET2
				psi.StandardOutputEncoding = Encoding.UTF8;
#endif
				psi.UseShellExecute = false;

				if (psiCustomizer != null)
				{
					psiCustomizer(psi);
				}

				proc = System.Diagnostics.Process.Start(psi);

				StreamReader outReader = proc.StandardOutput;
				if (outReader == null)
				{
					throw new IOException("Cannot obtain output reader for command");
				}
				outStream = outReader.BaseStream;
				if (outStream == null)
				{
					throw new IOException("Cannot obtain output stream for command");
				}
#if !NO_BUFFER
				// this is a small buffer to make byte operations not be horribly expensive:
				//outStream = new BufferedStream(outStream, 4096 << 1);
				outStream = new BufferedStream(outStream, BUFFER_SIZE);
#endif
				errorThread = IOUtil.ConsumeBackground(proc.StandardError);

				// is this always OK?
				if (skipStdin)
				{
					inStream = null;
				}
				else
				{
					StreamWriter inWriter = proc.StandardInput;
					if (inWriter == null)
					{
						throw new IOException("Cannot obtain input writer for command");
					}
					inStream = inWriter.BaseStream;
					if (inStream == null)
					{
						throw new IOException("Cannot obtain input stream for command");
					}
#if !NO_BUFFER
					// this is a small buffer to make byte operations not be horribly expensive:
					//inStream = new BufferedStream(inStream, 4096 << 1);
					inStream = new BufferedStream(inStream, BUFFER_SIZE);
#endif
				}
				//Console.WriteLine("CmsStream: " + commandName + " " + commandArgs);
			}
			catch (System.ComponentModel.Win32Exception)
			{
				try
				{
					try
					{
						if (proc != null)
						{
							proc.Kill();
							proc.WaitForExit();
						}
						exitCode = proc.ExitCode;
					}
					catch
					{
					}
					proc.Close();
					proc = null;
				}
				catch
				{
				}
				//throw new InvalidOperationException("Stream cannot be created to wrap '" + commandName +
				//    "' because it cannot be found.");
				throw new InvalidOperationException(CommandMissingMessage);
			}
			catch
			{
				if (proc != null)
				{
					try
					{
						try
						{
							proc.Kill();
							proc.WaitForExit();
							exitCode = proc.ExitCode;
						}
						catch
						{
						}
						proc.Close();
						proc = null;
					}
					catch
					{
					}
				}
				throw;
			}
			exitCode = 0;
			position = 0;
		}
Exemple #54
0
        /// <summary>
        /// Executes and calls cabwiz.exe using the specified inf file.
        /// </summary>
        /// <param name="informationFile">A absolute path to the .inf file which is to be used by cabwiz.exe</param>
        /// <returns>The cabwiz.exe exit code. 0 indicates success, a non-zero value indicates failure.</returns>
        public int Run(string informationFile)
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("The application is already running.");
            }
            else
            {
                this.IsRunning = true;

                if (!System.IO.Directory.Exists(this.DestinationDirectory))
                {
                    System.IO.Directory.CreateDirectory(this.DestinationDirectory);
                }

                try
                {
                    using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                    {
                        p.StartInfo.FileName = this.FileName;
                        p.StartInfo.Arguments = this.GetArguments(informationFile);
                        p.StartInfo.CreateNoWindow = true;
                        p.StartInfo.RedirectStandardError = true;
                        p.StartInfo.RedirectStandardOutput = true;
                        p.StartInfo.UseShellExecute = false;

                        p.Start();

                        if (this.StandardOutput != null)
                        {
                            OutputForward.BeginReadToEnd(this.StandardOutput, p.StandardOutput);
                        }

                        if (this.StandardError != null)
                        {
                            OutputForward.BeginReadToEnd(this.StandardError, p.StandardError);
                        }

                        while (!p.HasExited)
                        {
                            if (this.CancelRequested)
                            {
                                p.WaitForExit(500);

                                if (!p.HasExited)
                                {
                                    p.Kill();
                                }
                            }
                            else
                            {
                                System.Threading.Thread.Sleep(300);
                            }
                        }

                        return p.ExitCode;
                    }
                }
                finally
                {
                    this.IsRunning = false;
                }
            }
        }
Exemple #55
0
        public InstallResult InstallAppx(string filepath)
        {
            var result = new InstallResult();

              try
              {
            var sb = new StringBuilder();
            sb.Append(@"add-appxpackage ");
            sb.Append(filepath);

            var process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;

            process.StartInfo.FileName = "powershell.exe";
            process.StartInfo.Arguments = sb.ToString();

            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            process.Start();

            var stdout = process.StandardOutput;
            var stderr = process.StandardError;

            result.Output = stdout.ReadToEnd();
            result.Error = stderr.ReadToEnd();

            if (!process.HasExited)
              process.Kill();

            stdout.Close();
            stderr.Close();
              }
              catch (Exception ex)
              {
            if (string.IsNullOrWhiteSpace(result.Error))
              result.Error = ex.Message;
            else
              result.Error += Environment.NewLine + ex.Message;
              }
              finally
              {
            File.Delete(filepath);
              }

              return result;
        }
        public void StartAndWatch()
        {
            while (!_stopEvt.WaitOne(0))
            {
                try
                {
                    System.Diagnostics.Process oProcess = new System.Diagnostics.Process();

                    oProcess.StartInfo.FileName = m_sBinPath;
                    oProcess.StartInfo.Arguments = m_sOptions;

                    oProcess.StartInfo.CreateNoWindow = true;
                    oProcess.StartInfo.UseShellExecute = false;

                    _log.DebugFormat("Start {0} {1}", oProcess.StartInfo.FileName, oProcess.StartInfo.Arguments);

                    oProcess.Start();

                    while (!_stopEvt.WaitOne(0) && !oProcess.HasExited)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(1.0));
                    }

                    _log.Info("The process exited or stop event received.");

                    if (!oProcess.HasExited)
                         oProcess.Kill();
                }
                catch (Exception e)
                {
                    _log.Error("Exception catched in StartAndWatch:", e);
                }
            }
        }
        string Create(int wordCount, double probability, Func<SQLiteCommand, string> statusSelector, Func<SQLiteCommand, IList<string>> wordSelector)
        {
            if (wordCount < 0)
                throw new ArgumentOutOfRangeException("wordCount", "wordCount must be greater than 0.");
            if (probability < 0.0 || 1.0 < probability)
                throw new ArgumentOutOfRangeException("probability", "probability must be in the range between 0.0 and 1.0.");

            string status;
            IList<string> words;
            using (var con = new SQLiteConnection("Data Source=" + dbPath))
            {
                con.Open();
                var command = con.CreateCommand();
                status = statusSelector(command);
                command = con.CreateCommand();
                words = wordSelector(command);
                con.Close();
            }

            // parse status
            string parseResult = string.Empty;
            var process = new System.Diagnostics.Process();
            process.StartInfo.FileName = System.IO.Path.Combine(mecabBinDir, "mecab.exe");
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.OutputDataReceived += (sender, e) => parseResult += e.Data;
            process.Start();
            process.BeginOutputReadLine();
            process.StandardInput.WriteLine(status);
            process.StandardInput.Flush();
            process.WaitForExit(10 * 1000);    // 10 sec. for timeout.
            process.Kill();

            // create the result
            Random rand = new Random();
            List<string> result = new List<string>();
            using (var reader = new System.IO.StringReader(parseResult))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var surface = line.Split('\t')[0];
                    var feature = line.Split('\t')[1];
                    if (!feature.Contains("名詞,"))
                    {
                        result.Add(surface);
                        continue;
                    }
                    if ((probability - rand.NextDouble()) >= 0.0)
                        result.Add(words[rand.Next(words.Count)]);
                    else
                        result.Add(surface);
                }
            }
            string tmp = string.Empty;
            result.ForEach(s => tmp += s);
            return tmp;
        }