Esempio n. 1
0
        private static async Task RedirectionToFileAsync()
        {
            var tempFile = Path.GetTempFileName();

            var si = new ChildProcessStartInfo("env")
            {
                ExtraEnvironmentVariables = new Dictionary <string, string> {
                    { "A", "A" }
                },
                StdOutputRedirection = OutputRedirection.File,
                StdErrorRedirection  = OutputRedirection.File,
                StdOutputFile        = tempFile,
                StdErrorFile         = tempFile,
            };

            using (var p = ChildProcess.Start(si))
            {
                await p.WaitForExitAsync();
            }

            // LANG=C.UTF-8
            // ...
            Console.WriteLine(File.ReadAllText(tempFile));
            File.Delete(tempFile);
        }
        public void Run(string testExecutable, string testName, ITestOutput output)
        {
            var commandLineGenerator = new CommandLineGenerator();
            var options = TestRunnerOptions.FromDteProperties(_dte.Properties["BoostTest", "TestRunner"]);
            var testRunnerProcess = new ChildProcess(commandLineGenerator.Generate(testExecutable, testName, options));
            testRunnerProcess.StartSuspended();

            var process =
                _dte.Debugger.LocalProcesses.Cast<EnvDTE.Process>().SingleOrDefault(p => p.ProcessID == testRunnerProcess.Pid);
            if (process == null)
            {
                throw new InvalidOperationException("Couldn't find the process : " + testExecutable);
            }

            process.Attach();

            testRunnerProcess.Resume()
                .ContinueWith(
                    x =>
                    {
                        if (x.IsCompleted)
                        {
                            output.Clear();
                            output.OutputString(DateTime.Now.ToLongTimeString() + " : Test (Debug) : " + testName + "\n");
                            output.OutputString(x.Result);
                        }
                    });
        }
Esempio n. 3
0
        public IEnumerable <ChildProcess> GetChildProcesses(int pid, WebDrivers driverType)
        {
            var processes = new HashSet <ChildProcess>();

            try
            {
                var query = new ObjectQuery($"select * from win32_process where ParentProcessId={pid}");
                using (var searcher = new ManagementObjectSearcher(query))
                    using (var collection = searcher.Get())
                        foreach (ManagementObject item in collection)
                        {
                            using (item)
                            {
                                var childProcess      = new ChildProcess(item, driverType);
                                var processExecutable = Path.GetFileNameWithoutExtension(childProcess.ExecutablePath);
                                if (driverExecutableNames.Any(
                                        n => string.Equals(
                                            processExecutable,
                                            n,
                                            StringComparison.InvariantCultureIgnoreCase)))
                                {
                                    processes.Add(childProcess);
                                }
                            }
                        }
            }
            catch { }

            return(processes);
        }
Esempio n. 4
0
            static async Task SpawnCmdAsync()
            {
                var si = new ChildProcessStartInfo("sleep", "3s");

                using var p = ChildProcess.Start(si);
                await p.WaitForExitAsync();
            }
Esempio n. 5
0
        public void ObjectDisposed()
        {
            ChildProcess childProc;

            using (childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME)) { }
            childProc.ClearConsole();
        }
Esempio n. 6
0
 protected void RegisterProcess(ChildProcess process)
 {
     lock (_lock)
     {
         _process.Add(process.Handle, process);
     }
 }
Esempio n. 7
0
 public void ReadNullRegex()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.Match(null);
     }
 }
Esempio n. 8
0
        private static async Task RedirectionToFileAsync()
        {
            var tempFile = Path.GetTempFileName();

            var si = new ChildProcessStartInfo("cmd", "/C", "set")
            {
                ExtraEnvironmentVariables = new Dictionary <string, string> {
                    { "A", "A" }
                },
                StdOutputRedirection = OutputRedirection.File,
                StdErrorRedirection  = OutputRedirection.File,
                StdOutputFile        = tempFile,
                StdErrorFile         = tempFile,
                Flags    = ChildProcessFlags.UseCustomCodePage,
                CodePage = Encoding.Default.CodePage, // UTF-8 on .NET Core
            };

            using (var p = ChildProcess.Start(si))
            {
                await p.WaitForExitAsync();
            }

            // A=A
            // ALLUSERSPROFILE=C:\ProgramData
            // ...
            Console.WriteLine(File.ReadAllText(tempFile));
            File.Delete(tempFile);
        }
Esempio n. 9
0
        // Truely asynchronous WaitForExitAsync: WaitForExitAsync does not consume a thread-pool thread.
        // You will not need a dedicated thread for handling a child process.
        // You can handle more processes than the number of threads.
        private static async Task WaitForExitAsync()
        {
            const int N = 128;

            var stopWatch = Stopwatch.StartNew();
            var tasks     = new Task[N];

            for (int i = 0; i < N; i++)
            {
                tasks[i] = SpawnCmdAsync();
            }

            // Spawned 128 processes.
            // The 128 processes have exited.
            // Elapsed Time: 3367 ms
            Console.WriteLine("Spawned {0} processes.", N);
            await Task.WhenAll(tasks);

            Console.WriteLine("The {0} processes have exited.", N);
            Console.WriteLine("Elapsed Time: {0} ms", stopWatch.ElapsedMilliseconds);

            async Task SpawnCmdAsync()
            {
                var si = new ChildProcessStartInfo("cmd", "/C", "timeout", "3")
                {
                    StdInputRedirection  = InputRedirection.ParentInput,
                    StdOutputRedirection = OutputRedirection.NullDevice,
                };

                using (var p = ChildProcess.Start(si))
                {
                    await p.WaitForExitAsync();
                }
            }
        }
Esempio n. 10
0
        void KillAllProcesses(IEnumerable <ChildProcess> processes)
        {
            if (configuration.ProcessTerminationEnabled)
            {
                foreach (var processItem in processes)
                {
                    try
                    {
                        var process = Process.GetProcessById(processItem.ProcessId);

                        Log.Debug($"Process {processItem.Name} PID {processItem.ProcessId} is evaluated for termination");

                        if (string.Equals(
                                processItem.Name,
                                process.ProcessName,
                                StringComparison.InvariantCultureIgnoreCase))
                        {
                            Log.Debug($"Process {processItem.Name} PID {processItem.ProcessId} is about to be terminated");
                            process.Kill();
                            Log.Debug($"Process {processItem.Name} PID {processItem.ProcessId} was terminated");
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Debug($"An exception when terminating process {processItem.Name} PID {processItem.ProcessId} {e.Message}");
                    }
                }
            }
            processes = new ChildProcess[0];
        }
Esempio n. 11
0
 public void WriteNullString()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.WriteLine(null);
     }
 }
Esempio n. 12
0
 public void MatchTimeout()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME, new ChildProcessOptions() { TimeoutMilliseconds = 0 }))
     {
         childProc.Match(new Regex(Guid.NewGuid().ToString()));
     }
 }
Esempio n. 13
0
        private async Task InstallForgeInOldWay(string installerPath)
        {
            var cp = new ChildProcess(BmclCore.Config.Javaw, new[] { "-jar", installerPath });

            cp.Start();
            await cp.WaitForExitAsync();
        }
Esempio n. 14
0
        protected void StopProcess(bool restart = false)
        {
            lock (lockObj) {
                _restartProcess = restart;

                ChildProcess.Kill(true);
            }
        }
Esempio n. 15
0
 public void SimpleRead()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(Environment.CurrentDirectory + ">");
         Assert.IsTrue(content.Contains(Environment.CurrentDirectory + ">"));
     }
 }
Esempio n. 16
0
 public void SimpleReadUntilPrompt()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         Console.WriteLine(content);
         Assert.IsTrue(content.EndsWith(TestEnvironment.PROMPT_CHAR.ToString()));
     }
 }
Esempio n. 17
0
        public virtual void EvalExec(RCRunner runner, RCClosure closure, RCString command)
        {
            RCAsyncState state   = new RCAsyncState(runner, closure, command);
            long         handle  = CreateHandle();
            ChildProcess process = new ChildProcess(this, handle, state, true);

            RegisterProcess(process);
            process.Start();
        }
Esempio n. 18
0
 public void SimpleMatch()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.WriteLine("dir");
         Match m = childProc.Match(new Regex(@"Volume Serial Number is (?<VolumeSerial>[0-9A-F]{4}-[0-9A-F]{4})"));
         Console.WriteLine("Primary volume serial number: {0}", m.Groups["VolumeSerial"].Value);
         Assert.IsTrue(m.Success);
     }
 }
 public void DefaultConsoleClearsAfterMatch()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         childProc.WriteLine("echo \"hello world\"");
         content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         Assert.AreEqual(1, content.Count((c) => c.Equals(TestEnvironment.PROMPT_CHAR)));
     }
 }
Esempio n. 20
0
        public virtual void EvalSpawn(RCRunner runner, RCClosure closure, RCString command)
        {
            RCAsyncState state   = new RCAsyncState(runner, closure, command);
            long         handle  = CreateHandle();
            ChildProcess process = new ChildProcess(this, handle, state, false);

            RegisterProcess(process);
            process.Start();
            runner.Yield(closure, new RCLong(handle));
        }
Esempio n. 21
0
 public void MatchTimeout()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME, new ChildProcessOptions()
     {
         TimeoutMilliseconds = 0
     }))
     {
         childProc.Match(new Regex(Guid.NewGuid().ToString()));
     }
 }
Esempio n. 22
0
 public void DefaultConsoleClearsAfterMatch()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         childProc.WriteLine("echo \"hello world\"");
         content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         Assert.AreEqual(1, content.Count((c) => c.Equals(TestEnvironment.PROMPT_CHAR)));
     }
 }
Esempio n. 23
0
            static async Task SpawnCmdAsync()
            {
                var si = new ChildProcessStartInfo("sleep", "3s")
                {
                    StdInputRedirection  = InputRedirection.ParentInput,
                    StdOutputRedirection = OutputRedirection.NullDevice,
                };

                using var p = ChildProcess.Start(si);
                await p.WaitForExitAsync();
            }
Esempio n. 24
0
            static async Task SpawnCmdAsync(int i)
            {
                var si = new ChildProcessStartInfo("waitfor", "/T", "3", $"pause{i}")
                {
                    StdInputRedirection  = InputRedirection.ParentInput,
                    StdOutputRedirection = OutputRedirection.NullDevice,
                    Flags = ChildProcessFlags.AttachToCurrentConsole,
                };

                using var p = ChildProcess.Start(si);
                await p.WaitForExitAsync();
            }
Esempio n. 25
0
        public async Task <Step> Run(CallStack stack)
        {
            var variables = stack.CurrentVariables.Values;

            // map input parameters in from variables
            var childInputs = new ValueSet(InputMapping.ToDictionary(m => m.Key, m => variables[m.Value.Name]));

            // actually run the process, with the inputs named as it expects
            var response = await ChildProcess.Run(childInputs, stack);

            string returnPath = response.ReturnPath;
            var    outputs    = response.Outputs;

            // map any output parameters back out into variables
            if (outputs != null)
            {
                foreach (var kvp in OutputMapping)
                {
                    variables[kvp.Value.Name] = outputs.Values[kvp.Key];
                }
            }

            if (returnPath == null)
            {
                if (!ReturnPaths.Any())
                {
                    return(DefaultReturnPath);
                }

                if (ChildProcess is SystemProcess)
                {
                    throw new CursiveRunException(stack, $"System process \"{ChildProcess.Name}\" unexpectedly returned a null value");
                }
                else
                {
                    throw new CursiveRunException(stack, $"Step {ID} unexpectedly returned a null value");
                }
            }

            if (!ReturnPaths.TryGetValue(returnPath, out Step nextStep))
            {
                if (ChildProcess is SystemProcess)
                {
                    throw new CursiveRunException(stack, $"System process \"{ChildProcess.Name}\" returned an unexpected value: {returnPath}");
                }
                else
                {
                    throw new CursiveRunException(stack, $"Step {ID} returned an unexpected value: {returnPath}");
                }
            }

            return(nextStep);
        }
    private Task RunTranscoderAsync(string localPdbPath, string outputDirectory, CancellationToken cancellationToken)
    {
        string arguments = $"-pdb \"{localPdbPath}\"";

        Dictionary <string, string> environment = new Dictionary <string, string>
        {
            { "_NT_SYMBOL_PATH", Path.Combine(Path.GetPathRoot(localPdbPath), "unused") },
            { "_NT_SYMCACHE_PATH", outputDirectory }
        };

        return(ChildProcess.RunAndThrowOnFailureAsync(transcoderPath, arguments, environment, cancellationToken));
    }
Esempio n. 27
0
        public void Execute()
        {
            var dnxPath     = Process.GetCurrentProcess().Modules[0].FileName;
            var dnxFolder   = Path.GetDirectoryName(dnxPath);
            var toolingPath = Path.Combine(
                dnxFolder,
                "lib",
                "Microsoft.Dnx.Tooling",
                "Microsoft.Dnx.Tooling.dll");

            if (!File.Exists(toolingPath))
            {
                toolingPath = Path.Combine(
                    dnxFolder,
                    "lib",
                    "Microsoft.Framework.PackageManager",
                    "Microsoft.Framework.PackageManager.dll");
            }

            var childProcess = new ChildProcess();
            var results      = childProcess.Execute(dnxPath, $@"""{toolingPath}"" commands install {PackageId} {PackageVersion}");

            const string writingLockFile = "Writing lock file ";
            var          lockFiles       = results.Item2
                                           .Split("\r\n".ToArray())
                                           .Where(x => x.StartsWith(writingLockFile))
                                           .Select(x => x.Substring(writingLockFile.Length))
                                           .Where(File.Exists);

            var runtimeAssemblies = new List <string>();

            foreach (var lockFile in lockFiles)
            {
                var root    = JToken.Parse(File.ReadAllText(lockFile));
                var targets = root["targets"];
                var target  = targets[Services.ApplicationEnvironment.RuntimeFramework.ToString()];
                foreach (var package in target.OfType <JProperty>())
                {
                    var packageRuntime = package.Value["runtime"];
                    if (packageRuntime != null)
                    {
                        foreach (var assembly in packageRuntime.OfType <JProperty>())
                        {
                            runtimeAssemblies.Add(Path.Combine(package.Name, assembly.Name));
                        }
                    }
                }
            }
            File.WriteAllLines(
                $"Command.{PackageId}.txt",
                runtimeAssemblies.Select(x => $"{Path.GetFileNameWithoutExtension(x)}={x.Replace('/', Path.DirectorySeparatorChar)}"));
        }
Esempio n. 28
0
        protected void DoExec(object obj)
        {
            RCAsyncState state = (RCAsyncState)obj;

            try
            {
                ChildProcess process = (ChildProcess)state.Other;
                process.Start();
            }
            catch (Exception ex)
            {
                state.Runner.Report(state.Closure, ex);
            }
        }
        public void CanExecuteInAChildProcessAndRedirectOutputToString()
        {
            string command_line = "sample_test -t complex_numbers/add_complex_numbers";
            string result = string.Empty;
            var proc = new ChildProcess(command_line);
            proc.Start()
                .ContinueWith(
                (task) =>
                {
                    result = task.Result;
                }).Wait();

            const string expected_result = "Running 1 test case...\r\n\r\n*** No errors detected\r\n";
            Assert.AreEqual(expected_result, result);
        }
Esempio n. 30
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    ChildProcess.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
Esempio n. 31
0
        private static async Task RedirectionToFileAsync()
        {
            var si = new ChildProcessStartInfo("cmd", "/C", "set")
            {
                StdOutputRedirection = OutputRedirection.File,
                StdOutputFile        = "env.txt",
            };

            using (var p = ChildProcess.Start(si))
            {
                await p.WaitForExitAsync();
            }

            // ALLUSERSPROFILE=C:\ProgramData
            // ...
            Console.WriteLine(File.ReadAllText("env.txt"));
        }
Esempio n. 32
0
        private static async Task BasicAsync()
        {
            var si = new ChildProcessStartInfo("cmd", "/C", "echo", "foo")
            {
                StdOutputRedirection = OutputRedirection.OutputPipe,
            };

            using var p = ChildProcess.Start(si);
            using (var sr = new StreamReader(p.StandardOutput !))
            {
                // "foo"
                Console.Write(await sr.ReadToEndAsync());
            }
            await p.WaitForExitAsync();

            // ExitCode: 0
            Console.WriteLine("ExitCode: {0}", p.ExitCode);
        }
Esempio n. 33
0
 public void InvalidModelsCache(string[] services, ulong[] others, bool byPublish)
 {
     //HostRuntimeContext无services实例需要更新
     //先通知本机所有子进程更新缓存
     ChildProcess.InvalidModelsCache(services, others);
     //再更新主进程缓存
     if (others != null)
     {
         for (int i = 0; i < others.Length; i++)
         {
             models.TryRemove(others[i]);
         }
     }
     //最后通知整个集群
     if (byPublish)
     {
         //TODO:***** 广播事件至集群
     }
 }
        public void Run(string testExecutable, string testName, ITestOutput output)
        {
            var commandLineGenerator = new CommandLineGenerator();
            var options = TestRunnerOptions.FromDteProperties(_dte.Properties["BoostTest", "TestRunner"]);
            var commandLine = commandLineGenerator.Generate(testExecutable, testName, options);

            var testRunnerProcess = new ChildProcess(commandLine);
            testRunnerProcess.Start()
                    .ContinueWith(
                    result =>
                    {
                        if (result.IsCompleted)
                        {
                            output.Clear();
                            output.OutputString(DateTime.Now.ToLongTimeString() + " : Test : " + testName + "\n");
                            output.OutputString(result.Result);
                        }
                    });
        }
Esempio n. 35
0
        public void TestExistingProcessStillAliveAfterDispose()
        {
            using (Process p = new Process())
            {
                try
                {
                    p.StartInfo.FileName        = TestEnvironment.CMD_EXE_NAME;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow  = true;
                    p.Start();
                    using (ChildProcess childProc = new ChildProcess(p.Id)) { }

                    Assert.IsFalse(p.HasExited);
                }
                finally
                {
                    p.Kill();
                }
            }
        }
Esempio n. 36
0
 public void WriteNullString()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.WriteLine(null);
     }
 }
Esempio n. 37
0
 public void SimpleMatch()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.WriteLine("dir");
         Match m = childProc.Match(new Regex(@"Volume Serial Number is (?<VolumeSerial>[0-9A-F]{4}-[0-9A-F]{4})"));
         Console.WriteLine("Primary volume serial number: {0}", m.Groups["VolumeSerial"].Value);
         Assert.IsTrue(m.Success);
     }
 }
Esempio n. 38
0
 public void ObjectDisposed()
 {
     ChildProcess childProc;
     using (childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME)) { }
     childProc.ClearConsole();
 }
Esempio n. 39
0
        public void TestExistingProcessStillAliveAfterDispose()
        {
            using (Process p = new Process())
            {
                try
                {
                    p.StartInfo.FileName = TestEnvironment.CMD_EXE_NAME;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow = true;
                    p.Start();
                    using (ChildProcess childProc = new ChildProcess(p.Id)) { }

                    Assert.IsFalse(p.HasExited);
                }
                finally
                {
                    p.Kill();
                }
            }
        }
Esempio n. 40
0
 public void ReadNullRegex()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         childProc.Match(null);
     }
 }
Esempio n. 41
0
 public void ProcessNoExist()
 {
     using (ChildProcess childProc = new ChildProcess(Guid.NewGuid().ToString() + ".exe")) { }
 }
Esempio n. 42
0
        private void ConnectionThreadEntry()
        {
            try
            {
                string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                m_Connection = StaticExports.CreateTargetControl(m_Host, m_RemoteIdent, username, true);

                if (m_Connection.Connected)
                {
                    string api = "No API detected";
                    if (m_Connection.API.Length > 0) api = m_Connection.API;
                    this.BeginInvoke((MethodInvoker)delegate
                    {
                        if (m_Connection.PID == 0)
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, api);
                            SetText(String.Format("{0}", m_Connection.Target));
                        }
                        else
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                     m_Connection.Target, m_Connection.PID, api);
                            SetText(String.Format("{0} [PID {1}]", m_Connection.Target, m_Connection.PID));
                        }
                        connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                    });
                }
                else
                {
                    throw new ReplayCreateException(ReplayCreateStatus.NetworkIOFailed);
                }

                while (m_Connection.Connected)
                {
                    m_Connection.ReceiveMessage();

                    if (m_TriggerCapture)
                    {
                        m_Connection.TriggerCapture((uint)m_CaptureNumFrames);
                        m_TriggerCapture = false;
                    }

                    if (m_QueueCapture)
                    {
                        m_Connection.QueueCapture((uint)m_CaptureFrameNum);
                        m_QueueCapture = false;
                        m_CaptureFrameNum = 0;
                    }

                    if (m_CopyLogLocalPath != "")
                    {
                        m_Connection.CopyCapture(m_CopyLogID, m_CopyLogLocalPath);
                        m_CopyLogLocalPath = "";
                        m_CopyLogID = uint.MaxValue;
                    }

                    List<uint> dels = new List<uint>();
                    lock (m_DeleteLogs)
                    {
                        dels.AddRange(m_DeleteLogs);
                        m_DeleteLogs.Clear();
                    }

                    foreach(var del in dels)
                        m_Connection.DeleteCapture(del);

                    if (m_Disconnect)
                    {
                        m_Connection.Shutdown();
                        m_Connection = null;
                        return;
                    }

                    if (m_Connection.InfoUpdated)
                    {
                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            if (m_Connection.PID == 0)
                            {
                                connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, m_Connection.API);
                                SetText(String.Format("{0}", m_Connection.Target));
                            }
                            else
                            {
                                connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                         m_Connection.Target, m_Connection.PID, m_Connection.API);
                                SetText(String.Format("{0} [PID {1}]", m_Connection.Target, m_Connection.PID));
                            }
                            connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                        });

                        m_Connection.InfoUpdated = false;
                    }

                    if (m_Connection.CaptureExists)
                    {
                        uint capID = m_Connection.CaptureFile.ID;
                        DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0);
                        timestamp = timestamp.AddSeconds(m_Connection.CaptureFile.timestamp).ToLocalTime();
                        byte[] thumb = m_Connection.CaptureFile.thumbnail;
                        string path = m_Connection.CaptureFile.path;
                        bool local = m_Connection.CaptureFile.local;

                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            CaptureAdded(capID, m_Connection.Target, m_Connection.API, thumb, timestamp, path, local);
                        });
                        m_Connection.CaptureExists = false;
                    }

                    if (m_Connection.CaptureCopied)
                    {
                        uint capID = m_Connection.CaptureFile.ID;
                        string path = m_Connection.CaptureFile.path;

                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            CaptureCopied(capID, path);
                        });

                        m_Connection.CaptureCopied = false;
                    }

                    if (m_Connection.ChildAdded)
                    {
                        if (m_Connection.NewChild.PID != 0)
                        {
                            try
                            {
                                ChildProcess c = new ChildProcess();
                                c.PID = (int)m_Connection.NewChild.PID;
                                c.ident = m_Connection.NewChild.ident;
                                c.name = Process.GetProcessById((int)m_Connection.NewChild.PID).ProcessName;

                                lock (m_Children)
                                {
                                    m_Children.Add(c);
                                }
                            }
                            catch (Exception)
                            {
                                // process expired/doesn't exist anymore
                            }
                        }

                        m_Connection.ChildAdded = false;
                    }
                }

                this.BeginInvoke((MethodInvoker)delegate
                {
                    connectionStatus.Text = "Connection closed";
                    connectionIcon.Image = global::renderdocui.Properties.Resources.disconnect;

                    numFrames.Enabled = captureDelay.Enabled = captureFrame.Enabled =
                        triggerCapture.Enabled = queueCap.Enabled = false;

                    ConnectionClosed();
                });
            }
            catch (ReplayCreateException)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    SetText("Connection failed");
                    connectionStatus.Text = "Connection failed";
                    connectionIcon.Image = global::renderdocui.Properties.Resources.delete;

                    ConnectionClosed();
                });
            }
        }
Esempio n. 43
0
        private void ConnectionThreadEntry()
        {
            try
            {
                string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                m_Connection = StaticExports.CreateRemoteAccessConnection(m_Host, m_RemoteIdent, username, true);

                if (m_Connection.Connected)
                {
                    string api = "...";
                    if (m_Connection.API.Length > 0) api = m_Connection.API;
                    this.BeginInvoke((MethodInvoker)delegate
                    {
                        if (m_Connection.PID == 0)
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, api);
                            Text = String.Format("{0} ({1})", m_Connection.Target, api);
                        }
                        else
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} [PID {1}] ({2})",
                                     m_Connection.Target, m_Connection.PID, api);
                            Text = String.Format("{0} [PID {1}] ({2})", m_Connection.Target, m_Connection.PID, api);
                        }
                        connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                    });
                }
                else
                {
                    throw new ApplicationException();
                }

                while (m_Connection.Connected)
                {
                    m_Connection.ReceiveMessage();

                    if (m_TriggerCapture)
                    {
                        m_Connection.TriggerCapture();
                        m_TriggerCapture = false;
                    }

                    if (m_QueueCapture)
                    {
                        m_Connection.QueueCapture((uint)m_CaptureFrameNum);
                        m_QueueCapture = false;
                        m_CaptureFrameNum = 0;
                    }

                    if (m_Disconnect)
                    {
                        m_Connection.Shutdown();
                        m_Connection = null;
                        return;
                    }

                    if (m_Connection.InfoUpdated)
                    {
                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            connectionStatus.Text = String.Format("Connection established to {0} ({1})", m_Connection.Target, m_Connection.API);
                            Text = String.Format("{0} ({1})", m_Connection.Target, m_Connection.API);
                            connectionIcon.Image = global::renderdocui.Properties.Resources.connect;
                        });

                        m_Connection.InfoUpdated = false;
                    }

                    if (m_Connection.CaptureExists)
                    {
                        uint capID = m_Connection.CaptureFile.ID;
                        DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0);
                        timestamp = timestamp.AddSeconds(m_Connection.CaptureFile.timestamp).ToLocalTime();
                        byte[] thumb = m_Connection.CaptureFile.thumbnail;
                        string path = m_Connection.CaptureFile.localpath;

                        if (path.Length == 0 || File.Exists(path))
                        {
                            this.BeginInvoke((MethodInvoker)delegate
                            {
                                CaptureAdded(capID, m_Connection.Target, m_Connection.API, thumb, timestamp);
                                if (path.Length > 0)
                                    CaptureRetrieved(capID, path);
                            });
                            m_Connection.CaptureExists = false;

                            if (path.Length == 0)
                                m_Connection.CopyCapture(capID, m_Core.TempLogFilename("remotecopy_" + m_Connection.Target));
                        }
                    }

                    if (m_Connection.CaptureCopied)
                    {
                        uint capID = m_Connection.CaptureFile.ID;
                        string path = m_Connection.CaptureFile.localpath;

                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            CaptureRetrieved(capID, path);
                        });
                        m_Connection.CaptureCopied = false;
                    }

                    if (m_Connection.ChildAdded)
                    {
                        if (m_Connection.NewChild.PID != 0)
                        {
                            try
                            {
                                ChildProcess c = new ChildProcess();
                                c.PID = (int)m_Connection.NewChild.PID;
                                c.ident = m_Connection.NewChild.ident;
                                c.name = Process.GetProcessById((int)m_Connection.NewChild.PID).ProcessName;

                                lock (m_Children)
                                {
                                    m_Children.Add(c);
                                }
                            }
                            catch (Exception)
                            {
                                // process expired/doesn't exist anymore
                            }
                        }

                        m_Connection.ChildAdded = false;
                    }
                }

                this.BeginInvoke((MethodInvoker)delegate
                {
                    connectionStatus.Text = "Connection closed";
                    connectionIcon.Image = global::renderdocui.Properties.Resources.disconnect;

                    ConnectionClosed();
                });
            }
            catch (ApplicationException)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    Text = (m_Host.Length > 0 ? (m_Host + " - ") : "") + "Connection failed";
                    connectionStatus.Text = "Connection failed";
                    connectionIcon.Image = global::renderdocui.Properties.Resources.delete;

                    ConnectionClosed();
                });
            }
        }
Esempio n. 44
0
        public void VerifyProxyDeadOnDispose()
        {
            Process[] powerShells = null;

            try
            {
                using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
                {
                    powerShells = Process.GetProcessesByName(TestEnvironment.PROXY_PROCESS_NAME);
                    Assert.AreEqual(1, powerShells.Length);
                }
                TestUtilities.WaitForProcessExitAndThrow(powerShells[0]);
            }
            finally
            {
                if (powerShells != null)
                {
                    Array.ForEach(powerShells, (p) => p.Dispose());
                }
            }
        }
Esempio n. 45
0
 public void TestExistingProcess()
 {
     using (Process p = new Process())
     {
         try
         {
             p.StartInfo.FileName = TestEnvironment.CMD_EXE_NAME;
             p.StartInfo.UseShellExecute = false;
             p.StartInfo.CreateNoWindow = true;
             p.Start();
             using (ChildProcess childProc = new ChildProcess(p.Id))
             {
                 string prompt = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
                 Console.WriteLine(prompt);
             }
         }
         finally
         {
             p.Kill();
         }
     }
 }
Esempio n. 46
0
 public void SimpleRead()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(Environment.CurrentDirectory + ">");
         Assert.IsTrue(content.Contains(Environment.CurrentDirectory + ">"));
     }
 }
Esempio n. 47
0
 public void SimpleReadUntilPrompt()
 {
     using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
     {
         string content = childProc.Read(TestEnvironment.PROMPT_CHAR.ToString());
         Console.WriteLine(content);
         Assert.IsTrue(content.EndsWith(TestEnvironment.PROMPT_CHAR.ToString()));
     }
 }
Esempio n. 48
0
 public void VerifyChildDeadOnDispose()
 {
     Process p = null;
     try
     {
         using (ChildProcess childProc = new ChildProcess(TestEnvironment.CMD_EXE_NAME))
         {
             p = Process.GetProcessById(childProc.ChildProcessId);
         }
         TestUtilities.WaitForProcessExitAndThrow(p);
     }
     finally
     {
         if (p != null)
         {
             p.Dispose();
         }
     }
 }