Exemplo n.º 1
0
    private static bool IsCertOnKeychain(string keychain, X509Certificate2 certificate)
    {
        TimeSpan     MaxRegexTimeout         = TimeSpan.FromMinutes(1);
        const string CertificateSubjectRegex = "CN=(.*[^,]+).*";

        var subjectMatch = Regex.Match(certificate.Subject, CertificateSubjectRegex, RegexOptions.Singleline, MaxRegexTimeout);

        if (!subjectMatch.Success)
        {
            throw new InvalidOperationException($"Can't determine the subject for the certificate with subject '{certificate.Subject}'.");
        }

        var subject = subjectMatch.Groups[1].Value;

        // Run the find-certificate command, and look for the cert's hash in the output
        using var findCertificateProcess = Process.Start(new ProcessStartInfo(
                                                             MacOSFindCertificateOnKeychainCommandLine,
                                                             string.Format(CultureInfo.InvariantCulture, MacOSFindCertificateOnKeychainCommandLineArgumentsFormat, subject, keychain))
        {
            RedirectStandardOutput = true
        });

        var output = findCertificateProcess !.StandardOutput.ReadToEnd();

        findCertificateProcess.WaitForExit();

        var matches = Regex.Matches(output, MacOSFindCertificateOutputRegex, RegexOptions.Multiline, MaxRegexTimeout);
        var hashes  = matches.OfType <Match>().Select(m => m.Groups[1].Value).ToList();

        return(hashes.Any(h => string.Equals(h, certificate.Thumbprint, StringComparison.Ordinal)));
    }
Exemplo n.º 2
0
        public static string RunAndGetOutput(string exeFileName, string?arguments = null, int expectedRetCode = 0, string?startFolder = null)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(exeFileName);

            if (arguments != null)
            {
                startInfo.Arguments = arguments;
            }
            string?result = null;

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

            if (startFolder != null)
            {
                startInfo.WorkingDirectory = startFolder;
            }

            using (var process = Process.Start(startInfo))
            {
                // Do not wait for the child process to exit before reading to the end of its
                // redirected stream. Read the output stream first and then wait. Doing otherwise
                // might cause a deadlock.
                result = process !.StandardOutput.ReadToEnd();
                process.WaitForExit();
                Assert.True(expectedRetCode == process.ExitCode, $"Unexpected exit code: {process.ExitCode} (expecting {expectedRetCode}). Process output: {result}");
            }

            return(result);
        }
 private CompilerResult CreateCompilerResult()
 {
     return(new CompilerResult {
         StandardOutput = StandardOutput.ReadToEnd(),
         StandardError = StandardError.ReadToEnd(),
         CompilationTime = (int)ExitTime.Subtract(StartTime).TotalMilliseconds
     });
 }
Exemplo n.º 4
0
 private RunResult CreateRunResult()
 {
     return(new RunResult {
         Output = StandardOutput.ReadToEnd(),
         Error = StandardError.ReadToEnd(),
         RunTime = (int)ExitTime.Subtract(StartTime).TotalMilliseconds
     });
 }
Exemplo n.º 5
0
        public string StartAndReadStandardOutput()
        {
            Start();

            // Reading the standard output HAS to go before
            // WaitForExit, or it will hang forever on output > 4096 bytes
            string output = StandardOutput.ReadToEnd();

            WaitForExit();

            return(output.TrimEnd());
        }
Exemplo n.º 6
0
        public static (string compilerOutPutStdErros, string execFileOutputStdOutput, bool compiledSuccessfully) executeFile(string myFileToExec)
        {
            //string cComp = "gcc.exe";
            string JavaComp            = "java.exe";
            string PythonComp          = "python.exe";
            string compilerUsed        = "";
            string argumentsToCompiler = "";


            if (Path.GetExtension(myFileToExec).Equals(".exe"))
            {
                compilerUsed        = myFileToExec;
                argumentsToCompiler = $"";
            }
            else if (Path.GetExtension(myFileToExec).Equals(".py"))
            {
                compilerUsed        = PythonComp;
                argumentsToCompiler = $"\"{myFileToExec}\"";
            }
            else
            {
                compilerUsed        = JavaComp;
                argumentsToCompiler = $"{myFileToExec}";
            }

            using (Process myProcess = new Process())
            {
                myProcess.StartInfo.FileName               = compilerUsed;
                myProcess.StartInfo.UseShellExecute        = false;
                myProcess.StartInfo.RedirectStandardError  = true;
                myProcess.StartInfo.RedirectStandardInput  = true;
                myProcess.StartInfo.RedirectStandardOutput = true;
                myProcess.StartInfo.CreateNoWindow         = true;
                myProcess.StartInfo.Arguments              = argumentsToCompiler;

                myProcess.Start();
                string debuggError = myProcess.StandardError.ReadToEnd();

                if (debuggError.Equals(""))
                {
                    return(debuggError, myProcess.StandardOutput.ReadToEnd(), true);
                }
                else
                {
                    return(debuggError, myProcess.StandardOutput.ReadToEnd(), false);
                }
            }
        }
        /// <summary>
        /// 获取 WMIC 查询输出
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private static string GetWmicOutput(string query)
        {
            var info = new ProcessStartInfo("wmic")
            {
                UseShellExecute        = false,
                Arguments              = query,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
            };

            var output = string.Empty;

            using (var process = Process.Start(info))
            {
                output = process !.StandardOutput.ReadToEnd();
            }
            return(output.Trim());
        }
Exemplo n.º 8
0
        public static async Task <(int InstallCount, bool HasSettingsFile, string Output)> InstallExtensionsAsync(VsHive hive, IEnumerable <string> extensions)
        {
            using (var visualStudioInstaller = new TempFile(EmbeddedResourceUtil.ExtractResource(Assembly.GetExecutingAssembly(), "VsixTesting.ExtensionInstaller.exe")))
            {
                var process = Process.Start(new ProcessStartInfo
                {
                    FileName  = visualStudioInstaller.Path,
                    Arguments = string.Join(" ", new string[]
                    {
                        "--ApplicationPath", Quote(hive.ApplicationPath),
                        "--RootSuffix", hive.RootSuffix,
                        "--MajorVersion", hive.Version.Major.ToString(),
                        "--ExtensionPaths",
                    }.Concat(extensions.Select(e => Quote(e)))),
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                });

                await process.WaitForExitAsync();

                var result          = process.ExitCode;
                var hasSettingsFile = true;

                if (result < 0)
                {
                    throw new Exception(process.StandardError.ReadToEnd());
                }
                else if (result >= 9999)
                {
                    result         -= 9999;
                    hasSettingsFile = false;
                }

                return(result, hasSettingsFile, process.StandardOutput.ReadToEnd());
            }

            string Quote(string str) => $"\"{str}\"";
        }
Exemplo n.º 9
0
        public bool Run()
        {
            Start();
            StandardInput.Write("chcp 437" + Environment.NewLine);
            StandardInput.Write("ping 8.8.8.8 -n 1" + Environment.NewLine);
            StandardInput.Close();
            String output = StandardOutput.ReadToEnd();

            WaitForExit();
            Close();
            //var a = from line in output.Split('\n')
            //        where line.IndexOf("Reply from 8.8.8.8: ") != -1
            //        let c =  line.Replace("Reply from 8.8.8.8: ","").Split(' ')
            var list = output.Split('\n').Where(c =>
            {
                return(c.IndexOf("Reply from 8.8.8.8: ") != -1);
            }).Select(c =>
            {
                return(c.Replace("Reply from 8.8.8.8: ", "").Replace("\r", "").Split(' '));
            }).FirstOrDefault();

            if (list != null)
            {
                var dic = list.Select(t =>
                {
                    return(t.Split('='));
                }).Select(m =>
                {
                    return(new { k = m[0], v = m[1] });
                }).ToDictionary(i => i.k, v => v.v);
                if (dic.ContainsKey("time"))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 10
0
        public IEnumerable <string> GetOutput()
        {
            int    stdOutIndex   = 0;
            int    stdErrorIndex = 0;
            int    BUF_SIZE      = 4096;
            string output        = "";

            while (!HasExited)
            {
                char[] buf = new char[BUF_SIZE];
                if (StandardOutput.Peek() > -1)
                {
                    stdOutIndex += StandardOutput.Read(buf, stdOutIndex, BUF_SIZE);
                    output       = (new string(buf)).Trim();
                }
                else if (StandardError.Peek() > -1)
                {
                    stdErrorIndex += StandardError.Read(buf, stdErrorIndex, BUF_SIZE);
                    output         = (new string(buf)).Trim();
                }
                else
                {
                    output = "";
                }
                if (!string.IsNullOrEmpty(output))
                {
                    yield return(output);
                }
            }

            output = (StandardOutput.ReadToEnd().Trim() + "\r\n" + StandardError.ReadToEnd().Trim()).Trim();
            //Console.WriteLine($"Final output: {output}");
            if (!string.IsNullOrEmpty(output))
            {
                yield return(output);
            }
        }
Exemplo n.º 11
0
        private static void RemoveCertificateFromKeyChain(string keyChain, X509Certificate2 certificate)
        {
            var processInfo = new ProcessStartInfo(
                MacOSDeleteCertificateCommandLine,
                string.Format(
                    CultureInfo.InvariantCulture,
                    MacOSDeleteCertificateCommandLineArgumentsFormat,
                    certificate.Thumbprint.ToUpperInvariant(),
                    keyChain
                    ))
            {
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            if (Log.IsEnabled())
            {
                Log.MacOSRemoveCertificateFromKeyChainStart(keyChain, GetDescription(certificate));
            }

            using (var process = Process.Start(processInfo))
            {
                var output = process !.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    Log.MacOSRemoveCertificateFromKeyChainError(process.ExitCode);
                    throw new InvalidOperationException($@"There was an error removing the certificate with thumbprint '{certificate.Thumbprint}'.

{output}");
                }
            }

            Log.MacOSRemoveCertificateFromKeyChainEnd();
        }
Exemplo n.º 12
0
        public override bool IsTrusted(X509Certificate2 certificate)
        {
            var subjectMatch = Regex.Match(certificate.Subject, CertificateSubjectRegex, RegexOptions.Singleline, MaxRegexTimeout);

            if (!subjectMatch.Success)
            {
                throw new InvalidOperationException($"Can't determine the subject for the certificate with subject '{certificate.Subject}'.");
            }
            var subject = subjectMatch.Groups[1].Value;

            using var checkTrustProcess = Process.Start(new ProcessStartInfo(
                                                            MacOSFindCertificateCommandLine,
                                                            string.Format(CultureInfo.InvariantCulture, MacOSFindCertificateCommandLineArgumentsFormat, subject))
            {
                RedirectStandardOutput = true
            });
            var output = checkTrustProcess !.StandardOutput.ReadToEnd();

            checkTrustProcess.WaitForExit();
            var matches = Regex.Matches(output, MacOSFindCertificateOutputRegex, RegexOptions.Multiline, MaxRegexTimeout);
            var hashes  = matches.OfType <Match>().Select(m => m.Groups[1].Value).ToList();

            return(hashes.Any(h => string.Equals(h, certificate.Thumbprint, StringComparison.Ordinal)));
        }