Пример #1
0
                public void Should_Throw_If_Settings_Are_Null()
                {
                    // Given
                    var          context  = Substitute.For <ICakeContext>();
                    const string fileName = "git";

                    // When
                    var result = Record.Exception(() =>
                                                  ProcessExtensions.StartProcess(context, fileName, null));

                    // Then
                    Assert.IsType <ArgumentNullException>(result);
                    Assert.Equal("settings", ((ArgumentNullException)result).ParamName);
                }
Пример #2
0
        private static void Extract(string method, string source, string target)
        {
            // use intermediate temp directory to reset cygwin directories ACLs
            string tempPath = target + ".temp";

            Directory.CreateDirectory(tempPath);
            Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\tar.exe");
            Logger.Debug("Extracting {0} to {2} using {1} method", source, method, target);
            switch (method)
            {
            case "zip":
            {
                ZipFile.ExtractToDirectory(source, tempPath);
                break;
            }

            case "tgz":
            {
                ProcessResult result = ProcessExtensions.RunCommandAndGetOutput(Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\tar.exe"), string.Format("-C {0} -zxpf {1}", LinuxFiles.Cygpath(tempPath), LinuxFiles.Cygpath(source)));
                Logger.Debug(result.StdOut + result.StdErr);
                break;
            }

            case "tar":
            {
                ProcessResult result = ProcessExtensions.RunCommandAndGetOutput(Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\tar.exe"), string.Format("-C {0} -xpf {1}", LinuxFiles.Cygpath(tempPath), LinuxFiles.Cygpath(source)));
                Logger.Debug(result.StdOut + result.StdErr);
                break;
            }

            default:
            {
                throw new Exception(string.Format("Packaging method {0} not yet supported.", method));
            }
            }

            DirectoryUtil.DirectoryCopy(tempPath, target, true);
            Directory.Delete(tempPath, true);

            string[] files = Directory.GetFileSystemEntries(target);
            if (files.Length == 1)
            {
                Logger.Debug(string.Join(",", files));
                // A directory of one file is not legal move everyone up a level (github zip's are this way)
                string to_delete = files[0] + ".to_delete";
                Directory.Move(files[0], to_delete);
                DirectoryUtil.DirectoryCopy(to_delete, target, true);
                Directory.Delete(to_delete);
            }
        }
Пример #3
0
                public void Should_Throw_If_Filename_Is_Null()
                {
                    // Given
                    var context  = Substitute.For <ICakeContext>();
                    var settings = new ProcessSettings();

                    // When
                    var result = Record.Exception(() =>
                                                  ProcessExtensions.StartProcess(context, null, settings));

                    // Then
                    Assert.IsType <ArgumentNullException>(result);
                    Assert.Equal("fileName", ((ArgumentNullException)result).ParamName);
                }
Пример #4
0
        /// <summary>
        /// Get list of branches and the commit ids they point to
        /// </summary>
        ///
        public IEnumerable <GitRef> GetBranches()
        {
            var r = ProcessExtensions.ExecuteCaptured(false, false, null, "git", "-C", Path, "show-ref", "--heads");

            switch (r.ExitCode)
            {
            case 0:
            case 1:
                return(ParseRefLines(StringExtensions.SplitLines(r.StandardOutput)));

            default:
                throw new GitException("Get branches failed", r);
            }
        }
Пример #5
0
                public void Should_Throw_If_Context_Is_Null()
                {
                    // Given
                    const string fileName = "git";
                    var          settings = new ProcessSettings();

                    // When
                    var result = Record.Exception(() =>
                                                  ProcessExtensions.StartProcess(null, fileName, settings));

                    // Then
                    Assert.IsType <ArgumentNullException>(result);
                    Assert.Equal("context", ((ArgumentNullException)result).ParamName);
                }
    /// <summary>
    /// Builds a new release.
    /// </summary>
    /// <param name="cancellationToken">Used to cancel the current build.</param>
    /// <returns>True if a build has started and the operation completed, else false.</returns>
    public async Task <bool> BuildAsync(CancellationToken cancellationToken = default)
    {
        // Check if Auto Delta can be performed.
        if (AutomaticDelta && !Singleton <ReleaseMetadata> .Instance.CanReadFromDirectory(OutputFolder, null, out _, out _))
        {
            var description = string.Format(Resources.PublishAutoDeltaWarningDescriptionFormat.Get(), Singleton <ReleaseMetadata> .Instance.GetDefaultFileName());
            Actions.DisplayMessagebox(Resources.PublishAutoDeltaWarningTitle.Get(), description);
            return(false);
        }

        // Perform Build
        CanBuild = false;
        try
        {
            await Task.Run(async() =>
            {
                await PublishAsync(new PublishArgs()
                {
                    PublishTarget       = PublishTarget,
                    OutputFolder        = OutputFolder,
                    ModTuple            = _modTuple,
                    IgnoreRegexes       = IgnoreRegexes.Select(x => x.Value).ToList(),
                    IncludeRegexes      = IncludeRegexes.Select(x => x.Value).ToList(),
                    Progress            = new Progress <double>(d => BuildProgress = d * 100),
                    AutomaticDelta      = AutomaticDelta,
                    CompressionLevel    = CompressionLevel,
                    CompressionMethod   = CompressionMethod,
                    OlderVersionFolders = OlderVersionFolders.Select(x => x.Value).ToList(),
                    PackageName         = PackageName,
                    MetadataFileName    = _modTuple.Config.ReleaseMetadataFileName,
                    ChangelogPath       = ChangelogPath,
                    ReadmePath          = ReadmePath
                });
            });

            ProcessExtensions.OpenFileWithExplorer(OutputFolder);
        }
        catch (Exception ex)
        {
            Errors.HandleException(ex);
            return(false);
        }
        finally
        {
            CanBuild = true;
        }

        return(true);
    }
Пример #7
0
 private void BtnStart_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(PathToExe))
     {
         Stopwatch sw = new Stopwatch();
         sw.Start();
         (bool, PROCESS_INFORMATION)data = ProcessStart.StartProcess(PathToExe, ProcessCreationFlags.ZERO_FLAG);
         if (data.Item1)
         {
             Process Genshin = Process.GetProcesses().ToList().Find((p) => p.ProcessName == "GenshinImpact");
             if (Genshin != null)
             {
                 try
                 {
                     Thread.Sleep(1000);
                     string path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "HelloWorldDLL.dll");
                     if (!File.Exists(path))
                     {
                         throw new ApplicationException($"Code: {path} does not exists");
                     }
                     IntPtr threadAddress = DLLInjection.Inject(Genshin, path);
                     ProcessExtensions.NativeMethods.CloseHandle(threadAddress);
                     sw.Stop();
                     lblTime.Text = $"{sw.Elapsed.Seconds}:{sw.Elapsed.Milliseconds}";
                     if (threadAddress != IntPtr.Zero)
                     {
                         ProcessExtensions.Resume(Genshin, threadAddress);
                     }
                     else
                     {
                         throw new ApplicationException($"Code: {Marshal.GetLastWin32Error()}");
                     }
                 }
                 catch (ApplicationException ex)
                 {
                     MessageBox.Show("ERROR:\n" + ex.Message);
                 }
                 finally
                 {
                     ProcessExtensions.NativeMethods.CloseHandle(data.Item2.hProcess);
                 }
             }
             else
             {
                 MessageBox.Show("ERROR: FAILED TO GET GENSHIN PROCESS");
             }
         }
     }
 }
Пример #8
0
        public void GetDescription_WebJob_ReturnsExpectedResult(string webJobName, string webJobType, string expectedValue)
        {
            Dictionary <string, string> environment = new Dictionary <string, string>();

            if (webJobName != null)
            {
                environment[WellKnownEnvironmentVariables.WebJobsName] = webJobName;
            }
            if (webJobType != null)
            {
                environment[WellKnownEnvironmentVariables.WebJobsType] = webJobType;
            }

            Assert.Equal(expectedValue, ProcessExtensions.GetDescription(environment));
        }
Пример #9
0
        public void Multiple_Method_Switches_Runs_All_Specified_Methods()
        {
            var results = ProcessExtensions.ExecuteDotnet(
                testRunner, Quote("--method", "A.A.b", "--method", "B.B.b", includeExcludeTests));

            AssertZeroExitCode(results.ExitCode);
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.A.a()");
            AssertIncludeExcludeMethodRan(results.Output, "A.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.a()");
            AssertIncludeExcludeMethodRan(results.Output, "B.B.b()");
        }
Пример #10
0
 private static void Build(string path)
 {
     if (Directory.Exists(Path.Combine(path, "src")))
     {
         Logger.Debug(ProcessExtensions.RunCommandAndGetOutput(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe", "", Path.Combine(path, "src")).StdOut);
         foreach (string assembly in Directory.GetFiles(Path.Combine(path, "bin"), "*.dll"))
         {
             Logger.Debug(ProcessExtensions.RunCommandAndGetOutput(@"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe", string.Format("install {0}", assembly)).StdOut);
         }
         foreach (string assembly in Directory.GetFiles(Path.Combine(path, "bin"), "*.exe"))
         {
             Logger.Debug(ProcessExtensions.RunCommandAndGetOutput(@"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe", string.Format("install {0}", assembly)).StdOut);
         }
     }
 }
Пример #11
0
        public static async Task <ProcessOutput> Execute(this string bash, bool stripStdoutTrailingNewline = true, CancellationToken cancellationToken = default)
        {
            var(exitCode, stdOut, stdErr) = await ProcessExtensions.ExecuteBashViaTempFile(bash, includeMnt : PathsRequireMnt, cancellationToken);

            // if (exitCode != 0)
            //	throw new BashNonzeroExitCodeException(exitCode);

            if (stripStdoutTrailingNewline)
            {
                stdOut = stdOut.TrimEnd('\n', '\r');
                stdErr = stdErr.TrimEnd('\n', '\r');
            }

            return(exitCode, stdOut, stdErr);
        }
Пример #12
0
        public void Unqualified_Method_Switch_Is_Constrained_By_Class_Switches()
        {
            var results = ProcessExtensions.ExecuteDotnet(
                testRunner, Quote("--class", "B.A", "--method", "b", includeExcludeTests));

            AssertZeroExitCode(results.ExitCode);
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.A.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.a()");
            AssertIncludeExcludeMethodRan(results.Output, "B.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.b()");
        }
Пример #13
0
        public void Qualified_Method_Switch_Does_Not_Include_Other_Unqualified_Methods_In_Class()
        {
            var results = ProcessExtensions.ExecuteDotnet(
                testRunner, Quote("--class", "A.A", "--method", "a", "--method", "B.B.b", includeExcludeTests));

            AssertZeroExitCode(results.ExitCode);
            AssertIncludeExcludeMethodRan(results.Output, "A.A.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.a()");
            AssertIncludeExcludeMethodRan(results.Output, "B.B.b()");
        }
Пример #14
0
 /// <nodoc />
 public CacheablePipInfo(
     Pip pip,
     PipExecutionContext context,
     ReadOnlyArray <FileArtifactWithAttributes> outputs,
     ReadOnlyArray <FileArtifact> dependencies,
     ReadOnlyArray <DirectoryArtifact> directoryOutputs,
     ReadOnlyArray <DirectoryArtifact> directoryDependencies)
     : base(pip, context)
 {
     CacheableStaticOutputsCount = ProcessExtensions.GetCacheableOutputsCount(outputs);
     Outputs               = outputs;
     Dependencies          = dependencies;
     DirectoryOutputs      = directoryOutputs;
     DirectoryDependencies = directoryDependencies;
 }
Пример #15
0
        public void OpenUrlInSystemBrowser(Uri url)
        {
            string reportPath = url.ToString();

            m_logger.Info("Starting process: {0}", AppAssociationHelper.PathToDefaultBrowser);
            var sanitizedArgs = "\"" + Regex.Replace(reportPath, @"(\\+)$", @"$1$1") + "\"";

            var sanitizedPath = "\"" + Regex.Replace(AppAssociationHelper.PathToDefaultBrowser, @"(\\+)$", @"$1$1") + "\"" + " " + sanitizedArgs;

            ProcessExtensions.StartProcessAsCurrentUser(null, sanitizedPath);

            var cmdPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");

            ProcessExtensions.StartProcessAsCurrentUser(cmdPath, string.Format("/c start \"{0}\"", reportPath));
        }
Пример #16
0
        public void Qualified_Class_Switch_Runs_That_Exact_Class()
        {
            var results = ProcessExtensions.ExecuteDotnet(
                testRunner, Quote("--class", "A.A", includeExcludeTests));

            AssertZeroExitCode(results.ExitCode);
            AssertIncludeExcludeMethodRan(results.Output, "A.A.a()");
            AssertIncludeExcludeMethodRan(results.Output, "A.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.a()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.b()");
        }
Пример #17
0
        public void Unqualified_Method_Switch_Runs_Methods_With_That_Name()
        {
            var results = ProcessExtensions.ExecuteDotnet(
                testRunner, Quote("--method", "b", includeExcludeTests));

            AssertZeroExitCode(results.ExitCode);
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.A.a()");
            AssertIncludeExcludeMethodRan(results.Output, "A.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "A.B.a()");
            AssertIncludeExcludeMethodRan(results.Output, "A.B.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.A.a()");
            AssertIncludeExcludeMethodRan(results.Output, "B.A.b()");
            AssertIncludeExcludeMethodDidNotRun(results.Output, "B.B.a()");
            AssertIncludeExcludeMethodRan(results.Output, "B.B.b()");
        }
Пример #18
0
        public async Task StringTab()
        {
            const string deserializesToTab = "\"\\t\"";

            void defaultJavascriptEncoderTabDeserialization()
            {
                Assert(JsonSerializer.Deserialize <string>(deserializesToTab) == "\t");
            }

            void unsafeJavascriptEncoderTabDeserialization()
            {
                var options = new JsonSerializerOptions {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                Assert(JsonSerializer.Deserialize <string>(deserializesToTab, options) == "\t");
            }

            // this is correct js because it's tested in preTest via temp file rather than via bash
            // this is what the JS should be such that a tab is printed:
            const string correct_js = "\nvar result = \"\\t\";\n\nconsole.log('__DEBUG__');\nconsole.log(JSON.stringify(result));\n";

            async Task preTest()
            {
                var(_, stdOut, _, _) = await ProcessExtensions.ExecuteJSViaTempFile(correct_js);

                Assert(stdOut == deserializesToTab + "\n");
            }

            defaultJavascriptEncoderTabDeserialization();
            unsafeJavascriptEncoderTabDeserialization();
            await preTest();


            // literal JS:
            // console.log("\t");
            const string input = "\t";

            // test the built JS:
            string js = ProcessExtensions.ExecuteJS_Builder(NO_IMPORTS, input);

            Assert(correct_js == js);

            // test the built JS, escaping to bash and executing:
            string jsOutput = await executeJS((object)input);

            Assert(jsOutput == deserializesToTab + "\n");             // if this fails it must be the bashEscape
        }
        public void LaunchTest(TestContext testContext)
        {
            var file = testContext.TestHarnessPath;

            file = urlBuilder.GenerateFileUrl(testContext, file, fullyQualified: true);

            // Start IE.
            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                UseShellExecute = true,
                FileName        = BrowserPathHelper.GetBrowserPath("ie"),
                Arguments       = string.Format("-noframemerging -suspended -debug {0}", file)
                                  // -noframemerging
                                  //      This is what VS does when launching the script debugger.
                                  //      Unsure whether strictly necessary.
                                  // -suspended
                                  //      This is what VS does when launching the script debugger.
                                  //      Seems to cause IE to suspend all threads which is what we want.
                                  // -debug
                                  //      This is what VS does when launching the script debugger.
                                  //      Not sure exactly what it does.
            };
            Process ieMainProcess = Process.Start(startInfo);

            // Get child 'tab' process spawned by IE.
            // We need to wait a few ms for IE to open the process.
            Process ieTabProcess = null;

            for (int i = 0;; ++i)
            {
                System.Threading.Thread.Sleep(10);
                ieTabProcess = ProcessExtensions.FindFirstChildProcessOf(ieMainProcess.Id);
                if (ieTabProcess != null)
                {
                    break;
                }
                if (i > 400)   // 400 * 10 = 4s timeout
                {
                    throw new InvalidOperationException("Timeout waiting for Internet Explorer child process to start.");
                }
            }

            // Debug the script in that tab process.
            DteHelpers.DebugAttachToProcess(ieTabProcess.Id, "script");

            // Resume the threads in the IE process which where started off suspended.
            ieTabProcess.Resume();
        }
Пример #20
0
        // TestProcessPath returns the path to the test process.
        //~ func TestProcessPath(t *testing.T, s ...string) string {
        public static string TestProcessPath(params string[] s)
        {
            //~ cs := []string{"-test.run=TestExternalTokenHelperProcess", "--", "GO_WANT_HELPER_PROCESS"}
            //~ cs = append(cs, s...)
            //~ return fmt.Sprintf(
            //~     "%s %s",
            //~     os.Args[0],
            //~     strings.Join(cs, " "))
            var cs = new List <string>
            {
                "-test.run=TestExternalTokenHelperProcess", "--", "GO_WANT_HELPER_PROCESS"
            };

            cs.AddRange(s);
            return($"\"{ProcessExtensions.GetArv0()}\" {string.Join(" ", cs)}");
        }
        private async Task LaunchClient(Game game)
        {
            if (game == Game.Rs3 && !await _jarService.HasAccess(Game.Rs3))
            {
                await _logger.Log("You do not have access to RSPeer 3 Inuvation.");

                await _logger.Log("Visit https://rspeer.org/runescape-3-rs3-bot/ for more information.");

                ProcessExtensions.OpenUrl("https://rspeer.org/runescape-3-rs3-bot/");
                return;
            }
            await _launchService.Launch(new BotPanelUserRequest
            {
                Game = game
            });
        }
Пример #22
0
        /// <summary>
        /// Called when the myService fires event for hardware has changed.
        /// </summary>
        static void myService_HardwareChangedEvent()
        {
            // WORKAROUND: The event is called a number of times, but we only want to set the wallpaper once,
            // so here we check that it at least 3 seconds since the wallpaper was set the last time.
            if (DateTime.Now > lastSetTime.AddSeconds(3))
            {
                lastSetTime = DateTime.Now;

                String    processName = Path.GetFileNameWithoutExtension(AppToRun);
                Process[] processList = Process.GetProcessesByName(processName);
                if (processList.Length == 0)
                {
                    ProcessExtensions.StartProcessAsCurrentUser(AppToRun);
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Check out a particular commit
        /// </summary>
        ///
        /// <exception cref="InvalidOperationException">
        /// The repository has uncommitted changes
        /// </exception>
        ///
        /// <exception cref="GitException">
        /// The checkout operation failed
        /// </exception>
        ///
        public void Checkout(GitRev rev)
        {
            Guard.NotNull(rev, nameof(rev));

            if (HasUncommittedChanges())
            {
                throw new InvalidOperationException("Repository contains uncommitted changes");
            }

            var r = ProcessExtensions.ExecuteCaptured(false, false, null, "git", "-C", Path, "checkout", rev);

            if (r.ExitCode != 0)
            {
                throw new GitException("Checkout failed", r);
            }
        }
Пример #24
0
        public void ProcessTestRun()
        {
            // Run simple command which should exit successfully
            var output = ProcessExtensions.Run("%COMSPEC%", "/C DIR /A", "%TEMP%", 2);

            Assert.IsTrue(output.Output?.Length > 0);
            Assert.IsFalse(output.TimedOut);
            Assert.IsTrue(output.ReturnCode.HasValue);
            Assert.IsTrue(output.ReturnCode == 0);

            // Run command with timeout that will never exit (test timeout)
            output = ProcessExtensions.Run("NOTEPAD.EXE", null, null, 2);
            Assert.IsTrue(output.Output?.Length == 0);
            Assert.IsTrue(output.TimedOut);
            Assert.IsFalse(output.ReturnCode.HasValue);
        }
Пример #25
0
        public IActionResult GetProperties(int processId)
        {
            if (!GetProcess(processId, out var process, out var errorResult))
            {
                return(errorResult);
            }

            var dto = new ProcessPropertiesDto();

            using (process)
            {
                using (var searcher = new ManagementObjectSearcher("root\\CIMV2", $"SELECT * FROM Win32_Process WHERE ProcessId = {processId}"))
                    using (var results = searcher.Get())
                    {
                        var wmiProcess = results.Cast <ManagementObject>().SingleOrDefault();
                        if (wmiProcess == null)
                        {
                            return(NotFound());
                        }

                        dto.ApplyProperties(process, wmiProcess);

                        if (wmiProcess.TryGetProperty("ExecutablePath", out string executablePath))
                        {
                            try
                            {
                                dto.Icon = FileUtilities.GetFileIcon(executablePath, 32);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }
                    }

                try
                {
                    dto.IsWow64Process = ProcessExtensions.Is64BitProcess(process.Handle);
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            return(Ok(dto));
        }
Пример #26
0
        public void Execute(object parameter)
        {
            _canExecute = false;
            RaiseCanExecute(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            // Start
            var selectedMod  = _manageModsViewModel.SelectedModTuple;
            var modDirectory = Path.GetDirectoryName(selectedMod.Path);
            var outputPath   = Path.GetDirectoryName(modDirectory);

            Converter.FromModDirectory(modDirectory, outputPath, selectedMod.Config);
            ProcessExtensions.OpenFileWithExplorer(outputPath);

            // End
            _canExecute = true;
            RaiseCanExecute(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
Пример #27
0
        public IEnumerable <GitCommitInfo> RevList(int maxCount, IEnumerable <GitRev> revs)
        {
            Guard.NotNull(revs, nameof(revs));
            revs = revs.ToList();
            if (!revs.Any())
            {
                throw new ArgumentException("Empty", nameof(revs));
            }
            if (revs.Any(rev => rev == null))
            {
                throw new ArgumentException("Null item", nameof(revs));
            }

            if (maxCount < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(maxCount));
            }

            var args =
                new List <string>()
            {
                "-C", Path, "rev-list", "--format=fuller", "--date=iso-strict", "--parents",
            };

            if (maxCount >= 0)
            {
                args.Add($"--max-count={maxCount}");
            }

            args.AddRange(revs.Select(rev => rev.ToString()));

            try
            {
                return
                    (ParseRevList(
                         ProcessExtensions.ExecuteAndRead(
                             null, false, true, null,
                             "git", args.ToArray())
                         .GetEnumerator()));
            }

            catch (ProcessExecuteException pex)
            {
                throw new GitException(pex.Result);
            }
        }
Пример #28
0
        //~ func helperPath(s ...string) string {
        private string helperPath(params string[] s)
        {
            //~ cs := []string{"-test.run=TestExternalTokenHelperProcess", "--"}
            //~ cs = append(cs, s...)
            //~ return fmt.Sprintf(
            //~     "%s %s",
            //~     os.Args[0],
            //~     strings.Join(cs, " "))
            var cs = new List <string>
            {
                "-test.run=TestExternalTokenHelperProcess", "--"
            };

            cs.InsertRange(0, Environment.GetCommandLineArgs());
            cs.AddRange(s);
            return($"\"{ProcessExtensions.GetArv0()}\" {string.Join(" ", cs)}");
        }
Пример #29
0
    private static int Start()
    {
        if (!File.Exists(Path.Combine(D2Path, D2Exe)) || !File.Exists(Path.Combine(Application.StartupPath, D2BSDLL)))
        {
            return(-1);
        }
        ProcessStartInfo processStartInfo = new ProcessStartInfo(Path.Combine(D2Path, D2Exe), " " + D2Args);

        processStartInfo.UseShellExecute  = false;
        processStartInfo.WorkingDirectory = D2Path;
        Process.EnterDebugMode();
        Process process = new Process();

        process.StartInfo = processStartInfo;
        process           = Kernel32.StartSuspended(process, processStartInfo);
        byte[] buffer = new byte[2];
        Kernel32.LoadRemoteLibrary(process, Path.Combine(D2Path, "D2Gfx.dll"));
        Kernel32.WriteProcessMemory(process, (IntPtr)1873327792, new byte[2]
        {
            235,
            69
        });
        IntPtr address = (IntPtr)1873327792;

        Kernel32.Resume(process);
        process.WaitForInputIdle();
        Kernel32.Suspend(process);
        Kernel32.WriteProcessMemory(process, address, buffer);
        Kernel32.Resume(process);
        Thread.Sleep(LoadDelay);
        Process[] childProcesses = ProcessExtensions.GetChildProcesses(process);
        if (childProcesses.Length > 0)
        {
            Process[] array = childProcesses;
            foreach (Process process2 in array)
            {
                if (IsD2Window(process2))
                {
                    process2.WaitForInputIdle();
                    return(process2.Id);
                }
            }
        }
        return(process.Id);
    }
Пример #30
0
        WriteDot(Target targetToBuild)
        {
            if (!Enabled)
            {
                return;
            }
            var debugDir = Graph.Workspace.GetTraceDirectory();
            var dotFile  = Path.Combine(debugDir, Invariant($"graph{DotCount:d2}.dot"));
            var pngFile  = Path.Combine(debugDir, Invariant($"graph{DotCount:d2}.dot.png"));
            var dot      =
                EnvironmentExtensions.IsWindows
            ? "C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe"
            : "dot";

            File.WriteAllLines(dotFile, ToDot(targetToBuild));
            ProcessExtensions.Execute(false, false, null, dot, "-Tpng", "-o" + pngFile, dotFile);
            DotCount++;
        }
Пример #31
0
        private static bool SetTimeZonePrivilege(ref ProcessExtensions.TokenPrivileges previousState)
        {
            if (!Process.GetCurrentProcess().SetPrivilegeTokens(PrivilegeName, ref previousState))
            {
                Log.WarnFormat("Could not set time zone: unable to set appropriate privileges for process");
                return false;
            }

            return true;
        }