Example #1
0
        public bool AttachToProcess(ProcessOutput processOutput, EnvDTE.Process process, Guid[] engines = null)
        {
            // Retry the attach itself 3 times before displaying a Retry/Cancel
            // dialog to the user.
            var dte = GetDTE();

            dte.SuppressUI = true;
            try {
                try {
                    if (engines == null)
                    {
                        process.Attach();
                    }
                    else
                    {
                        var process3 = process as EnvDTE90.Process3;
                        if (process3 == null)
                        {
                            return(false);
                        }
                        process3.Attach2(engines.Select(engine => engine.ToString("B")).ToArray());
                    }
                    return(true);
                } catch (COMException) {
                    if (processOutput.Wait(TimeSpan.FromMilliseconds(500)))
                    {
                        // Process exited while we were trying
                        return(false);
                    }
                }
            } finally {
                dte.SuppressUI = false;
            }

            // Another attempt, but display UI.
            process.Attach();
            return(true);
        }
Example #2
0
        private static async Task <int> Run(int port)
        {
            using (var client = new TcpClient()) {
                await client.ConnectAsync(IPAddress.Loopback, port);

                var utf8 = new UTF8Encoding(false);
                using (var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true))
                    using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                        var filename = await reader.ReadLineAsync();

                        var args = (await reader.ReadLineAsync()).Split('|')
                                   .Select(s => utf8.GetString(Convert.FromBase64String(s)))
                                   .ToList();
                        var workingDir = await reader.ReadLineAsync();

                        var env = (await reader.ReadLineAsync()).Split('|')
                                  .Select(s => s.Split(new[] { '=' }, 2))
                                  .Select(s => new KeyValuePair <string, string>(s[0], utf8.GetString(Convert.FromBase64String(s[1]))))
                                  .ToList();
                        var outputEncoding = await reader.ReadLineAsync();

                        var errorEncoding = await reader.ReadLineAsync();

                        return(await ProcessOutput.Run(
                                   filename,
                                   args,
                                   workingDir,
                                   env,
                                   false,
                                   new StreamRedirector(writer, outputPrefix : "OUT:", errorPrefix : "ERR:"),
                                   quoteArgs : false,
                                   elevate : false,
                                   outputEncoding : string.IsNullOrEmpty(outputEncoding)?null : Encoding.GetEncoding(outputEncoding),
                                   errorEncoding : string.IsNullOrEmpty(errorEncoding)?null : Encoding.GetEncoding(errorEncoding)
                                   ));
                    }
            }
        }
Example #3
0
        public bool AttachToProcess(ProcessOutput processOutput, EnvDTE.Process process, Guid[] engines = null)
        {
            // Retry the attach itself 3 times before displaying a Retry/Cancel
            // dialog to the user.
            var dte = GetDTE();
            dte.SuppressUI = true;
            try {
                try {
                    if (engines == null) {
                        process.Attach();
                    } else {
                        var process3 = process as EnvDTE90.Process3;
                        if (process3 == null) {
                            return false;
                        }
                        process3.Attach2(engines.Select(engine => engine.ToString("B")).ToArray());
                    }
                    return true;
                } catch (COMException) {
                    if (processOutput.Wait(TimeSpan.FromMilliseconds(500))) {
                        // Process exited while we were trying
                        return false;
                    }
                }
            } finally {
                dte.SuppressUI = false;
            }

            // Another attempt, but display UI.
            process.Attach();
            return true;
        }
Example #4
0
        public bool AttachToProcess(ProcessOutput processOutput, Guid[] engines)
        {
            var debugger3 = (EnvDTE90.Debugger3)GetDTE().Debugger;
            var processes = debugger3.LocalProcesses;
            for (int i = 1; i < processes.Count; ++i) {
                var process = processes.Item(i);
                if (process.ProcessID == processOutput.ProcessId) {
                    return AttachToProcess(processOutput, process, engines);
                }
            }

            return false;
        }
Example #5
0
        public bool AttachToProcess(ProcessOutput processOutput, Guid portSupplier, string transportQualifierUri)
        {
            var debugger3 = (EnvDTE90.Debugger3)GetDTE().Debugger;
            var transports = debugger3.Transports;
            EnvDTE80.Transport transport = null;
            for (int i = 1; i <= transports.Count; ++i) {
                var t = transports.Item(i);
                if (Guid.Parse(t.ID) == portSupplier) {
                    transport = t;
                    break;
                }
            }
            if (transport == null) {
                return false;
            }

            var processes = debugger3.GetProcesses(transport, transportQualifierUri);
            if (processes.Count < 1) {
                return false;
            }

            var process = processes.Item(1);
            return AttachToProcess(processOutput, process);
        }
Example #6
0
        /// <summary>
        /// Runs the file with the provided settings as a user with
        /// administrative permissions. The window is always hidden and output
        /// is provided to the redirector when the process terminates.
        /// </summary>
        /// <param name="filename">Executable file to run.</param>
        /// <param name="arguments">Arguments to pass.</param>
        /// <param name="workingDirectory">Starting directory.</param>
        /// <param name="redirector">
        /// An object to receive redirected output.
        /// </param>
        /// <param name="quoteArgs"></param>
        /// <returns>A <see cref="ProcessOutput"/> object.</returns>
        public static ProcessOutput RunElevated(
            string filename,
            IEnumerable <string> arguments,
            string workingDirectory,
            Redirector redirector,
            bool quoteArgs          = true,
            Encoding outputEncoding = null,
            Encoding errorEncoding  = null
            )
        {
            var outFile = Path.GetTempFileName();
            var errFile = Path.GetTempFileName();
            var psi     = new ProcessStartInfo("cmd.exe");

            psi.CreateNoWindow  = true;
            psi.WindowStyle     = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            psi.Verb            = "runas";

            string args;

            if (quoteArgs)
            {
                args = string.Join(" ", arguments.Where(a => a != null).Select(QuoteSingleArgument));
            }
            else
            {
                args = string.Join(" ", arguments.Where(a => a != null));
            }
            psi.Arguments = string.Format("/S /C \"{0} {1} >>{2} 2>>{3}\"",
                                          QuoteSingleArgument(filename),
                                          args,
                                          QuoteSingleArgument(outFile),
                                          QuoteSingleArgument(errFile)
                                          );
            psi.WorkingDirectory = workingDirectory;
            psi.CreateNoWindow   = true;
            psi.UseShellExecute  = true;

            var process = new Process();

            process.StartInfo = psi;
            var result = new ProcessOutput(process, redirector);

            if (redirector != null)
            {
                result.Exited += (s, e) => {
                    try {
                        try {
                            var lines = File.ReadAllLines(outFile, outputEncoding ?? Encoding.Default);
                            foreach (var line in lines)
                            {
                                redirector.WriteLine(line);
                            }
                        } catch (Exception ex) when(!ex.IsCriticalException())
                        {
                            redirector.WriteErrorLine("Failed to obtain standard output from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString()))
                            {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard output from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                        try {
                            var lines = File.ReadAllLines(errFile, errorEncoding ?? outputEncoding ?? Encoding.Default);
                            foreach (var line in lines)
                            {
                                redirector.WriteErrorLine(line);
                            }
                        } catch (Exception ex) when(!ex.IsCriticalException())
                        {
                            redirector.WriteErrorLine("Failed to obtain standard error from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString()))
                            {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard error from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                    } finally {
                        try {
                            File.Delete(outFile);
                        } catch { }
                        try {
                            File.Delete(errFile);
                        } catch { }
                    }
                };
            }
            return(result);
        }
Example #7
0
 public void StartServer() {
     _process = ProcessOutput.Run(
         IisExpressPath,
         new[] { "/config:" + Path.Combine(_dir, "applicationHost.config"), "/systray:false" },
         null,
         null,
         false,
         new OutputRedirector("IIS")
     );
     Console.WriteLine("Server started: {0}", _process.Arguments);
 }
Example #8
0
 private static void DumpOutput(ProcessOutput process) {
     Console.WriteLine(process.Arguments);
     foreach (var line in process.StandardOutputLines) {
         Console.WriteLine(line);
     }
     foreach (var line in process.StandardErrorLines) {
         Console.Error.WriteLine(line);
     }
 }
Example #9
0
        /// <summary>
        /// Runs the file with the provided settings as a user with
        /// administrative permissions. The window is always hidden and output
        /// is provided to the redirector when the process terminates.
        /// </summary>
        /// <param name="filename">Executable file to run.</param>
        /// <param name="arguments">Arguments to pass.</param>
        /// <param name="workingDirectory">Starting directory.</param>
        /// <param name="redirector">
        /// An object to receive redirected output.
        /// </param>
        /// <param name="quoteArgs"></param>
        /// <returns>A <see cref="ProcessOutput"/> object.</returns>
        public static ProcessOutput RunElevated(
            string filename,
            IEnumerable<string> arguments,
            string workingDirectory,
            Redirector redirector,
            bool quoteArgs = true,
            Encoding outputEncoding = null,
            Encoding errorEncoding = null
        ) {
            var outFile = Path.GetTempFileName();
            var errFile = Path.GetTempFileName();
            var psi = new ProcessStartInfo("cmd.exe");
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            psi.Verb = "runas";

            string args;
            if (quoteArgs) {
                args = string.Join(" ", arguments.Where(a => a != null).Select(QuoteSingleArgument));
            } else {
                args = string.Join(" ", arguments.Where(a => a != null));
            }
            psi.Arguments = string.Format("/S /C \"{0} {1} >>{2} 2>>{3}\"",
                QuoteSingleArgument(filename),
                args,
                QuoteSingleArgument(outFile),
                QuoteSingleArgument(errFile)
            );
            psi.WorkingDirectory = workingDirectory;
            psi.CreateNoWindow = true;
            psi.UseShellExecute = true;

            var process = new Process();
            process.StartInfo = psi;
            var result = new ProcessOutput(process, redirector);
            if (redirector != null) {
                result.Exited += (s, e) => {
                    try {
                        try {
                            var lines = File.ReadAllLines(outFile, outputEncoding ?? Encoding.Default);
                            foreach (var line in lines) {
                                redirector.WriteLine(line);
                            }
                        } catch (Exception ex) when(!ex.IsCriticalException()) {
                            redirector.WriteErrorLine("Failed to obtain standard output from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString())) {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard output from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                        try {
                            var lines = File.ReadAllLines(errFile, errorEncoding ?? outputEncoding ?? Encoding.Default);
                            foreach (var line in lines) {
                                redirector.WriteErrorLine(line);
                            }
                        } catch (Exception ex) when(!ex.IsCriticalException()) {
                            redirector.WriteErrorLine("Failed to obtain standard error from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString())) {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard error from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                    } finally {
                        try {
                            File.Delete(outFile);
                        } catch { }
                        try {
                            File.Delete(errFile);
                        } catch { }
                    }
                };
            }
            return result;
        }