Esempio n. 1
0
 private ProcessHelper GetCommandRunner()
 {
     if (CommandRunner == null)
     {
         CommandRunner = new ProcessHelper();
     }
     return CommandRunner;
 }
Esempio n. 2
0
        public void Processor_TwoColorValues_ShouldPass(TypeOfProcess typeCode, IColor colorOne, IColor colorTwo)
        {
            var processor = new Processor();
            var processHelper = new ProcessHelper<IProcessor>(processor);

            processHelper.Process(colorOne, colorTwo);

            Assert.Equal(typeCode, processor.LastProcess);
        }
Esempio n. 3
0
        public void Process(IColor colorOne, IColor colorTwo)
        {
            var helper = new ProcessHelper();
            colorOne.Accept(helper);
            colorTwo.Accept(helper);

            helper.Process(this);
            //через конструтор копирования
            helper.ProcessByConstructor(this);
        }
Esempio n. 4
0
        private void CompileOutProc(Project project, string target = null)
        {
            string msBuildPath = Environment.ExpandEnvironmentVariables(string.Format(@"%WinDir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"));
            Console.WriteLine("Invoke MsBuild from {0}", msBuildPath);

            ProcessHelper processHelper = new ProcessHelper();
            string targetArg = target == null ? "" : " /target:" + target;
            int exitCode = processHelper.RunProcess(msBuildPath, "/nologo /v:m \"{0}\" {1}", project.FullPath, targetArg);
            LastCompilationOutput = processHelper.ConsoleOutput;
            if (exitCode > 0)
                throw new Exception("Build failed");
        }
Esempio n. 5
0
        public override void TestSuiteFinished(TestCaseSummary testResultsSummary)
        {
            base.TestSuiteFinished(testResultsSummary);

            if (!runContext.IsDataCollectionEnabled || testResultsSummary.CoverageObject == null)
            {
                return;
            }

            var directory = runContext.SolutionDirectory;
            var coverageHtmlFile = CoverageOutputGenerator.WriteHtmlFile(directory, testResultsSummary.CoverageObject);
            var processHelper = new ProcessHelper();

            processHelper.LaunchFileInBrowser(coverageHtmlFile);
        }
        public void TestProcessNfieldOrPs_ArrayObject_CallsCorrectActions()
        {
            ArrayList input = new ArrayList();
            PSObject arrayInput = new PSObject(input);
            PSObject psInput = new PSObject();
            input.Add(psInput);
            input.Add(psInput);

            int count = 0;

            var mockedMapper = new Mock<IPSObjectMapper>();
            mockedMapper.Setup(x => x.To<Interviewer>(psInput))
                .Returns(new Interviewer());
            ProcessHelper target = new ProcessHelper(mockedMapper.Object);

            target.ProcessNfieldOrPs<Interviewer>(arrayInput,
                    (item) => { ++count; });

            Assert.Equal(2, count);
        }
        public CurrencyWindowViewModel()
        {
            if (ChannelSession.Settings.Currency.All(c => !c.Value.IsPrimary))
            {
                this.IsPrimary = true;
            }

            this.OnlineRate  = CurrencyAcquireRateTypeEnum.Minutes;
            this.OfflineRate = CurrencyAcquireRateTypeEnum.Disabled;

            this.AutomaticResetRate = CurrencyResetRateEnum.Never;

            this.AddRankCommand = this.CreateCommand(async(parameter) =>
            {
                if (string.IsNullOrEmpty(this.NewRankName))
                {
                    await DialogHelper.ShowMessage("A rank name must be specified");
                    return;
                }

                if (this.NewRankAmount < 0)
                {
                    await DialogHelper.ShowMessage("A minimum amount must be specified");
                    return;
                }

                if (this.Ranks.Any(r => r.Name.Equals(this.NewRankName) || r.Amount == this.NewRankAmount))
                {
                    await DialogHelper.ShowMessage("Every rank must have a unique name and minimum amount");
                    return;
                }

                RankModel newRank = new RankModel(this.NewRankName, this.NewRankAmount);
                this.Ranks.Add(newRank);

                var tempRanks = this.Ranks.ToList();

                this.Ranks.Clear();
                foreach (RankModel rank in tempRanks.OrderBy(r => r.Amount))
                {
                    this.Ranks.Add(rank);
                }

                this.NewRankName   = string.Empty;
                this.NewRankAmount = 0;
            });

            this.ManualResetCommand = this.CreateCommand(async(parameter) =>
            {
                if (await DialogHelper.ShowConfirmation(string.Format("Do you want to reset all {0} points?", this.CurrencyRankIdentifierString)))
                {
                    if (this.Currency != null)
                    {
                        await this.Currency.Reset();
                    }
                }
            });

            this.RetroactivelyGivePointsCommand = this.CreateCommand(async(parameter) =>
            {
                if (await DialogHelper.ShowConfirmation(string.Format("This option will reset all {0} points for this {0} & assign an amount to each user that directly equals the SAVED online rate, not the currently edited online rate. Before using this option, please save all edits to this {0}, re-edit it, then select this option." +
                                                                      Environment.NewLine + Environment.NewLine + "EX: If the Online Rate is \"1 Per Hour\" and a user has 16 viewing hours, then that user's {0} points will be set to 16." +
                                                                      Environment.NewLine + Environment.NewLine + "This process may take some time; are you sure you wish to do this?", this.CurrencyRankIdentifierString)))
                {
                    if (this.Currency != null && this.Currency.AcquireInterval > 0)
                    {
                        if (this.Currency.SpecialTracking != CurrencySpecialTrackingEnum.None)
                        {
                            await DialogHelper.ShowMessage("The rate type for this currency does not support retroactively giving points.");
                            return;
                        }

                        await this.Currency.Reset();
                        foreach (MixItUp.Base.Model.User.UserDataModel userData in ChannelSession.Settings.UserData.Values)
                        {
                            int intervalsToGive = userData.ViewingMinutes / this.Currency.AcquireInterval;
                            this.Currency.AddAmount(userData, this.Currency.AcquireAmount * intervalsToGive);
                            if (userData.TwitchUserRoles.Contains(UserRoleEnum.Mod) || userData.TwitchUserRoles.Contains(UserRoleEnum.ChannelEditor))
                            {
                                this.Currency.AddAmount(userData, this.Currency.ModeratorBonus * intervalsToGive);
                            }
                            else if (userData.TwitchUserRoles.Contains(UserRoleEnum.Subscriber))
                            {
                                this.Currency.AddAmount(userData, this.Currency.SubscriberBonus * intervalsToGive);
                            }
                            ChannelSession.Settings.UserData.ManualValueChanged(userData.ID);
                        }
                    }
                }
            });

            this.ImportFromFileCommand = this.CreateCommand(async(parameter) =>
            {
                this.userImportData.Clear();
                if (await DialogHelper.ShowConfirmation(string.Format("This will allow you to import the total amounts that each user had, assign them to this {0}, and will overwrite any amounts that each user has." +
                                                                      Environment.NewLine + Environment.NewLine + "This process may take some time; are you sure you wish to do this?", this.CurrencyRankIdentifierString)))
                {
                    try
                    {
                        string filePath = ChannelSession.Services.FileService.ShowOpenFileDialog();
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            string fileContents = await ChannelSession.Services.FileService.ReadFile(filePath);
                            string[] lines      = fileContents.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
                            if (lines.Count() > 0)
                            {
                                foreach (string line in lines)
                                {
                                    long id         = 0;
                                    string username = null;
                                    int amount      = 0;

                                    string[] segments = line.Split(new string[] { " ", "\t", "," }, StringSplitOptions.RemoveEmptyEntries);
                                    if (segments.Count() == 2)
                                    {
                                        if (!int.TryParse(segments[1], out amount))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }

                                        if (!long.TryParse(segments[0], out id))
                                        {
                                            username = segments[0];
                                        }
                                    }
                                    else if (segments.Count() == 3)
                                    {
                                        if (!long.TryParse(segments[0], out id))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }

                                        if (!int.TryParse(segments[2], out amount))
                                        {
                                            throw new InvalidOperationException("File is not in the correct format");
                                        }
                                    }
                                    else
                                    {
                                        throw new InvalidOperationException("File is not in the correct format");
                                    }

                                    UserViewModel user = null;
                                    if (amount > 0)
                                    {
                                        if (id > 0)
                                        {
                                            MixItUp.Base.Model.User.UserDataModel userData = ChannelSession.Settings.GetUserDataByTwitchID(id.ToString());
                                            if (userData != null)
                                            {
                                                user = new UserViewModel(userData);
                                            }
                                            else
                                            {
                                                UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByID(id.ToString());
                                                if (twitchUser != null)
                                                {
                                                    user = new UserViewModel(twitchUser);
                                                }
                                            }
                                        }
                                        else if (!string.IsNullOrEmpty(username))
                                        {
                                            UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(username);
                                            if (twitchUser != null)
                                            {
                                                user = new UserViewModel(twitchUser);
                                            }
                                        }
                                    }

                                    if (user != null)
                                    {
                                        if (!this.userImportData.ContainsKey(user.ID))
                                        {
                                            this.userImportData[user.ID] = amount;
                                        }
                                        this.userImportData[user.ID] = Math.Max(this.userImportData[user.ID], amount);
                                        this.ImportFromFileText      = string.Format("{0} {1}...", this.userImportData.Count(), MixItUp.Base.Resources.Imported);
                                    }
                                }

                                foreach (var kvp in this.userImportData)
                                {
                                    if (ChannelSession.Settings.UserData.ContainsKey(kvp.Key))
                                    {
                                        MixItUp.Base.Model.User.UserDataModel userData = ChannelSession.Settings.UserData[kvp.Key];
                                        this.Currency.SetAmount(userData, kvp.Value);
                                    }
                                }

                                this.ImportFromFileText = MixItUp.Base.Resources.ImportFromFile;
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                    }

                    await DialogHelper.ShowMessage("We were unable to import the data. Please ensure your file is in one of the following formats:" +
                                                   Environment.NewLine + Environment.NewLine + "<USERNAME> <AMOUNT>" +
                                                   Environment.NewLine + Environment.NewLine + "<USER ID> <AMOUNT>" +
                                                   Environment.NewLine + Environment.NewLine + "<USER ID> <USERNAME> <AMOUNT>");

                    this.ImportFromFileText = MixItUp.Base.Resources.ImportFromFile;
                }
            });

            this.ExportToFileCommand = this.CreateCommand(async(parameter) =>
            {
                string filePath = ChannelSession.Services.FileService.ShowSaveFileDialog(this.Currency.Name + " Data.txt");
                if (!string.IsNullOrEmpty(filePath))
                {
                    StringBuilder fileContents = new StringBuilder();
                    foreach (MixItUp.Base.Model.User.UserDataModel userData in ChannelSession.Settings.UserData.Values.ToList())
                    {
                        fileContents.AppendLine(string.Format("{0} {1} {2}", userData.TwitchID, userData.Username, this.Currency.GetAmount(userData)));
                    }
                    await ChannelSession.Services.FileService.SaveFile(filePath, fileContents.ToString());
                }
            });

            this.HelpCommand = this.CreateCommand((parameter) =>
            {
                ProcessHelper.LaunchLink("https://github.com/SaviorXTanren/mixer-mixitup/wiki/Currency,-Rank,-&-Inventory");
                return(Task.FromResult(0));
            });
        }
Esempio n. 8
0
 public static void Gen()
 {
     ProcessHelper.Run("protogen.bat", null, "../Proto/", false);
     AssetDatabase.Refresh();
 }
Esempio n. 9
0
        public void Invoke(IDictionary <string, string> argsDictionary)
        {
            // Setup logging if enabled
            string logFile;

            if (argsDictionary.TryGetValue(LogFileArgument, out logFile))
            {
                EqtTrace.InitializeVerboseTrace(logFile);
            }

#if NET451
            if (EqtTrace.IsInfoEnabled)
            {
                var appConfigText = System.IO.File.ReadAllText(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                EqtTrace.Info("DefaultEngineInvoker: Using Application Configuration: '{0}'", appConfigText);
            }
#endif

            // vstest.console < 15.5 won't send endpoint and role arguments.
            // So derive endpoint from port argument and Make connectionRole as Client.
            string endpoint = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, EndpointArgument);
            if (string.IsNullOrWhiteSpace(endpoint))
            {
                var port = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, "--port");
                endpoint = IPAddress.Loopback + ":" + port;
            }

            ConnectionRole connectionRole = ConnectionRole.Client;
            string         role           = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, RoleArgument);
            if (string.IsNullOrWhiteSpace(role) && string.Equals(role, "host", StringComparison.OrdinalIgnoreCase))
            {
                connectionRole = ConnectionRole.Host;
            }

            // Start Processing of requests
            using (var requestHandler = new TestRequestHandler(new TestHostConnectionInfo {
                Endpoint = endpoint, Role = connectionRole, Transport = Transport.Sockets
            }))
            {
                // Attach to exit of parent process
                var parentProcessId = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, ParentProcessIdArgument);
                EqtTrace.Info("DefaultEngineInvoker: Monitoring parent process with id: '{0}'", parentProcessId);

                // In remote scenario we cannot monitor parent process, so we expect user to pass parentProcessId as -1
                if (parentProcessId != -1)
                {
                    var processHelper = new ProcessHelper();
                    processHelper.SetExitCallback(
                        parentProcessId,
                        () =>
                    {
                        EqtTrace.Info("DefaultEngineInvoker: ParentProcess '{0}' Exited.", parentProcessId);
                        new PlatformEnvironment().Exit(1);
                    });
                }

                // Initialize Communication
                EqtTrace.Info("DefaultEngineInvoker: Initialize communication on endpoint address: '{0}'", endpoint);
                requestHandler.InitializeCommunication();

                // Initialize DataCollection Communication if data collection port is provided.
                var dcPort = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, DataCollectionPortArgument);
                if (dcPort > 0)
                {
                    var dataCollectionTestCaseEventSender = DataCollectionTestCaseEventSender.Create();
                    dataCollectionTestCaseEventSender.InitializeCommunication(dcPort);
                    dataCollectionTestCaseEventSender.WaitForRequestSenderConnection(ClientListenTimeOut);
                }

                // Start processing async in a different task
                EqtTrace.Info("DefaultEngineInvoker: Start Request Processing.");
                var processingTask = this.StartProcessingAsync(requestHandler, new TestHostManagerFactory());

                // Wait for processing to complete.
                Task.WaitAny(processingTask);

                if (dcPort > 0)
                {
                    // Close socket communication connection.
                    DataCollectionTestCaseEventSender.Instance.Close();
                }
            }
        }
Esempio n. 10
0
        public async Task kernel_server_honors_log_path()
        {
            using var logPath        = DisposableDirectory.Create();
            using var outputReceived = new ManualResetEvent(false);
            var outputLock     = new object();
            var receivedOutput = false;
            var errorLines     = new List <string>();

            // start as external process
            var kernelServerProcess = ProcessHelper.Start(
                command: "dotnet",
                args: $@"interactive stdio --log-path ""{logPath.Directory.FullName}""",
                workingDir: new DirectoryInfo(Directory.GetCurrentDirectory()),
                output: _line =>
            {
                lock (outputLock)
                {
                    if (!receivedOutput)
                    {
                        receivedOutput = true;
                        outputReceived.Set();
                    }
                }
            },
                error: errorLines.Add);

            // wait for log file to be created
            var logFile = await logPath.Directory.WaitForFile(
                timeout : TimeSpan.FromSeconds(2),
                predicate : _file => true); // any matching file is the one we want

            errorLines.Should().BeEmpty();
            logFile.Should().NotBeNull("unable to find created log file");

            // submit code
            var submissionJson = @"{""token"":""abc"",""commandType"":""SubmitCode"",""command"":{""code"":""1+1"",""submissionType"":0,""targetKernelName"":null}}";
            await kernelServerProcess.StandardInput.WriteLineAsync(submissionJson);

            await kernelServerProcess.StandardInput.FlushAsync();

            // wait for output to proceed
            var gotOutput = outputReceived.WaitOne(timeout: TimeSpan.FromSeconds(2));

            gotOutput.Should().BeTrue("expected to receive on stdout");

            // kill
            kernelServerProcess.StandardInput.Close(); // simulate Ctrl+C
            await Task.Delay(TimeSpan.FromSeconds(2)); // allow logs to be flushed

            kernelServerProcess.Kill();
            kernelServerProcess.WaitForExit(2000).Should().BeTrue();
            errorLines.Should().BeEmpty();

            // check log file for expected contents
            (await logFile.WaitForFileCondition(
                 timeout: TimeSpan.FromSeconds(2),
                 predicate: file => file.Length > 0))
            .Should().BeTrue("expected non-empty log file");
            var logFileContents = File.ReadAllText(logFile.FullName);

            logFileContents.Should().Contain("ℹ OnAssemblyLoad: ");
        }
Esempio n. 11
0
        public void Build_ExecutesPreAndPostBuildScripts_WithinBenvContext()
        {
            // Arrange
            var volume = CreateWebFrontEndVolume();

            using (var sw = File.AppendText(Path.Combine(volume.MountedHostDir, "build.env")))
            {
                sw.NewLine = "\n";
                sw.WriteLine("PRE_BUILD_SCRIPT_PATH=scripts/prebuild.sh");
                sw.WriteLine("POST_BUILD_SCRIPT_PATH=scripts/postbuild.sh");
            }
            var scriptsDir = Directory.CreateDirectory(Path.Combine(volume.MountedHostDir, "scripts"));

            using (var sw = File.AppendText(Path.Combine(scriptsDir.FullName, "prebuild.sh")))
            {
                sw.NewLine = "\n";
                sw.WriteLine("#!/bin/bash");
                sw.WriteLine("echo \"Pre-build script: $node\"");
                sw.WriteLine("echo \"Pre-build script: $npm\"");
            }
            using (var sw = File.AppendText(Path.Combine(scriptsDir.FullName, "postbuild.sh")))
            {
                sw.NewLine = "\n";
                sw.WriteLine("#!/bin/bash");
                sw.WriteLine("echo \"Post-build script: $node\"");
                sw.WriteLine("echo \"Post-build script: $npm\"");
            }
            if (RuntimeInformation.IsOSPlatform(Settings.LinuxOS))
            {
                ProcessHelper.RunProcess(
                    "chmod",
                    new[] { "-R", "777", scriptsDir.FullName },
                    workingDirectory: null,
                    waitTimeForExit: null);
            }

            var appDir = volume.ContainerDir;
            var script = new ShellScriptBuilder()
                         .AddBuildCommand($"{appDir} -l nodejs --language-version 6")
                         .ToString();

            // Act
            var result = _dockerCli.Run(
                Settings.BuildImageName,
                volume,
                commandToExecuteOnRun: "/bin/bash",
                commandArguments:
                new[]
            {
                "-c",
                script
            });

            // Assert
            RunAsserts(
                () =>
            {
                Assert.True(result.IsSuccess);
                Assert.Matches(@"Pre-build script: /opt/nodejs/6.\d+.\d+/bin/node", result.StdOut);
                Assert.Matches(@"Pre-build script: /opt/nodejs/6.\d+.\d+/bin/npm", result.StdOut);
                Assert.Matches(@"Post-build script: /opt/nodejs/6.\d+.\d+/bin/node", result.StdOut);
                Assert.Matches(@"Post-build script: /opt/nodejs/6.\d+.\d+/bin/npm", result.StdOut);
            },
                result.GetDebugInfo());
        }
Esempio n. 12
0
        public void BuildSample([ValueSource("GetSampleData")] SampleTestData sampleTestData)
        {
            try {
                var data = sampleTestData.SampleTest;
                if (!string.IsNullOrEmpty(data.KnownFailure))
                {
                    Assert.Ignore(data.KnownFailure);
                }

                var environment_variables = new Dictionary <string, string> ();
                environment_variables ["MD_APPLE_SDK_ROOT"] = Path.GetDirectoryName(Path.GetDirectoryName(Configuration.XcodeLocation));
                switch (data.Project.Platform)
                {
                case TestPlatform.iOS:
                case TestPlatform.tvOS:
                case TestPlatform.watchOS:
                    environment_variables ["MD_MTOUCH_SDK_ROOT"] = Path.Combine(Configuration.IOS_DESTDIR, "Library", "Frameworks", "Xamarin.iOS.framework", "Versions", "Current");
                    environment_variables ["TargetFrameworkFallbackSearchPaths"]         = Path.Combine(Configuration.IOS_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild-frameworks");
                    environment_variables ["MSBuildExtensionsPathFallbackPathsOverride"] = Path.Combine(Configuration.IOS_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild");
                    break;

                case TestPlatform.macOS:
                    environment_variables ["TargetFrameworkFallbackSearchPaths"]         = Path.Combine(Configuration.MAC_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild-frameworks");
                    environment_variables ["MSBuildExtensionsPathFallbackPathsOverride"] = Path.Combine(Configuration.MAC_DESTDIR, "Library", "Frameworks", "Mono.framework", "External", "xbuild");
                    environment_variables ["XamarinMacFrameworkRoot"] = Path.Combine(Configuration.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current");
                    environment_variables ["XAMMAC_FRAMEWORK_PATH"]   = Path.Combine(Configuration.MAC_DESTDIR, "Library", "Frameworks", "Xamarin.Mac.framework", "Versions", "Current");
                    break;

                default:
                    throw new NotImplementedException(sampleTestData.Platform.ToString());
                }

                var file_to_build = sampleTestData.SampleTest.Project.RelativePath;
                var target        = string.Empty;
                if (data.BuildSolution)
                {
                    file_to_build = data.Solution;
                    target        = Path.GetFileNameWithoutExtension(data.Project.RelativePath).Replace('.', '_');
                }

                var repo = CloneRepo();
                file_to_build = Path.Combine(repo, file_to_build);

                if (data.RemoveProjects != null)
                {
                    if (String.IsNullOrEmpty(data.Solution))
                    {
                        Assert.Fail("'RemoveProjects' used without a 'Solution' path!");
                    }
                    var sln_path     = Path.Combine(repo, data.Solution);
                    var filtered_sln = new List <string> (File.ReadAllLines(sln_path));
                    foreach (var p in data.RemoveProjects)
                    {
                        for (int i = 0; i < filtered_sln.Count; i++)
                        {
                            var line = filtered_sln [i];
                            if (line.StartsWith("Project(", StringComparison.Ordinal))
                            {
                                if (line.Contains($") = \"{p}\", \""))
                                {
                                    filtered_sln.RemoveAt(i);
                                    filtered_sln.RemoveAt(i);                                      // EndProject (same `i` as things moved up)
                                    break;
                                }
                            }
                        }
                    }
                    File.WriteAllLines(sln_path, filtered_sln);
                }

                ProcessHelper.BuildSolution(file_to_build, sampleTestData.Platform, sampleTestData.Configuration, environment_variables, sampleTestData.Timeout, target, data.CodesignKey);
                Console.WriteLine("✅ {0} succeeded.", TestContext.CurrentContext.Test.FullName);
            } catch (Exception e) {
                Console.WriteLine("❌ {0} failed: {1}", TestContext.CurrentContext.Test.FullName, e.Message);
                throw;
            }
        }
        public CommunityCommandsMainControlViewModel(MainWindowViewModel windowViewModel)
            : base(windowViewModel)
        {
            this.BackCommand = this.CreateCommand(async() =>
            {
                if (this.ShowMyCommands)
                {
                    await this.NavigateToCategories();
                }
                else if (this.ShowUserCommands)
                {
                    await this.NavigateToCategories();
                }
                else if (this.ShowSearch)
                {
                    await this.NavigateToCategories();
                }
                else if (this.ShowCommandDetails)
                {
                    if (this.MyCommands.Count > 0)
                    {
                        this.ClearAllShows();
                        this.ShowMyCommands = true;
                    }
                    else if (this.UserCommands.Count > 0)
                    {
                        this.ClearAllShows();
                        this.ShowUserCommands = true;
                    }
                    else if (this.SearchResults.Count > 0)
                    {
                        this.ClearAllShows();
                        this.ShowSearch = true;
                    }
                    else
                    {
                        await this.NavigateToCategories();
                    }
                }
            });

            this.SearchCommand = this.CreateCommand(async() =>
            {
                try
                {
                    this.CurrentResultsPage = 0;
                    await this.PerformSearch();
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.GetCommandDetailsCommand = this.CreateCommand(async(id) =>
            {
                try
                {
                    CommunityCommandDetailsModel commandDetails = await ChannelSession.Services.CommunityCommandsService.GetCommandDetails((Guid)id);
                    if (commandDetails != null)
                    {
                        this.CommandDetails = new CommunityCommandDetailsViewModel(commandDetails);

                        this.ClearAllShows();
                        this.ShowCommandDetails = true;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.WebsiteLinkCommand = this.CreateCommand(() =>
            {
                ProcessHelper.LaunchLink(this.CommandDetails?.WebsiteURL);
            });

            this.GetUserCommandsCommand = this.CreateCommand(async() =>
            {
                try
                {
                    this.CurrentResultsPage = 0;
                    await this.PerformUserCommands();
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.GetMyCommandsCommand = this.CreateCommand(async() =>
            {
                try
                {
                    this.CurrentResultsPage = 0;
                    await this.PerformMyCommands();
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.EditMyCommandCommand = this.CreateCommand(async(id) =>
            {
                try
                {
                    CommunityCommandDetailsModel commandDetails = await ChannelSession.Services.CommunityCommandsService.GetCommandDetails((Guid)id);
                    if (commandDetails != null)
                    {
                        this.CommandDetails = new MyCommunityCommandDetailsViewModel(commandDetails);

                        this.ClearAllShows();
                        this.ShowCommandDetails = true;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.DeleteMyCommandCommand = this.CreateCommand(async() =>
            {
                try
                {
                    if (this.CommandDetails.IsMyCommand && await DialogHelper.ShowConfirmation(MixItUp.Base.Resources.CommunityCommandsDeleteMyCommandConfirmation))
                    {
                        await ChannelSession.Services.CommunityCommandsService.DeleteCommand(this.CommandDetails.ID);

                        this.GetMyCommandsCommand.Execute(null);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });

            this.PreviousResultsCommand = this.CreateCommand(async() =>
            {
                this.CurrentResultsPage--;
                if (this.ShowMyCommands)
                {
                    await this.PerformMyCommands();
                }
                else if (this.ShowUserCommands)
                {
                    await this.PerformUserCommands();
                }
                else if (this.ShowSearch)
                {
                    await this.PerformSearch();
                }
            });

            this.NextResultsCommand = this.CreateCommand(async() =>
            {
                this.CurrentResultsPage++;
                if (this.ShowMyCommands)
                {
                    await this.PerformMyCommands();
                }
                else if (this.ShowUserCommands)
                {
                    await this.PerformUserCommands();
                }
                else if (this.ShowSearch)
                {
                    await this.PerformSearch();
                }
            });
        }
Esempio n. 14
0
        public static async Task <(int, string)> PsAsync()
        {
            var(err, stdout, stderr) = await ProcessHelper.RunProcessAsync("docker", $"ps");

            return(err, await stdout.ReadToEndAsync());
        }
Esempio n. 15
0
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            await CommandHelper.SaveFiles();

            await ProcessHelper.RunTortoiseGitFileCommand("diff");
        }
Esempio n. 16
0
        public void CreatePackage(ServiceDefinition definition, string rootPath, DevEnv type, out string standardOutput, out string standardError)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(
                    "definition",
                    string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition"));
            }
            if (string.IsNullOrEmpty(rootPath) || File.Exists(rootPath))
            {
                throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath");
            }

            // Track the directories that are created by GetOrCreateCleanPath
            // to avoid publishing iisnode log files so we can delete the temp
            // copies when we're finished packaging
            Dictionary<string, string> tempDirectories = new Dictionary<string, string>();
            try
            {
                string roles =
                    // Get the names of all web and worker roles
                    Enumerable.Concat(
                        definition.WebRole.NonNull().Select(role => role.name),
                        definition.WorkerRole.NonNull().Select(role => role.name))
                    // Get the name and safe path for each role (i.e., if the
                    // role has files that shouldn't be packaged, it'll be
                    // copied to a temp location without those files)
                    .Select(name => GetOrCreateCleanPath(rootPath, name, tempDirectories, type))
                    // Format the role name and path as a role argument
                    .Select(nameAndPath => string.Format(Resources.RoleArgTemplate, nameAndPath.Key, nameAndPath.Value))
                    // Join all the role arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string sites =
                    // Get all of the web roles
                    definition.WebRole.NonNull()
                    // Get all the sites in each role and format them all as
                    // site arguments
                    .SelectMany(role =>
                        // Format each site as a site argument
                        role.Sites.Site.Select(site =>
                            string.Format(
                                Resources.SitesArgTemplate,
                                role.name,
                                site.name,
                                tempDirectories.GetValueOrDefault(role.name, rootPath))))
                    // Join all the site arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string args = string.Format(
                    type == DevEnv.Local ? Resources.CsPackLocalArg : Resources.CsPackCloudArg,
                    rootPath,
                    roles,
                    sites);

                // Run CsPack to generate the package
                ProcessHelper.StartAndWaitForProcess(
                    new ProcessStartInfo(
                        Path.Combine(AzureSdkBinDirectory, Resources.CsPackExe),
                        args),
                    out standardOutput,
                    out standardError);
            }
            finally
            {
                // Cleanup any temp directories
                tempDirectories.Values.ForEach(dir => Directory.Delete(dir, true));
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Creates a copy of a local directory, and returns a DockerVolume instance for mounting that copy in a
        /// container.
        /// </summary>
        /// <param name="hostDir">local directory to be used in a container</param>
        /// <returns>DockerVolume instance that can be used to mount the new copy of `originalDir`.</returns>
        public static DockerVolume CreateMirror(string hostDir)
        {
            if (string.IsNullOrEmpty(hostDir))
            {
                throw new ArgumentException($"'{nameof(hostDir)}' cannot be null or empty.");
            }

            if (!Directory.Exists(hostDir))
            {
                throw new ArgumentException($"'{nameof(hostDir)}' must point to an existing directory.");
            }

            var dirInfo = new DirectoryInfo(hostDir);

            // Copy the host directory to a different location and mount that one as it's always possible that a
            // single sample app could be tested by different tests and we do not want to modify its original state
            // and also it would not be nice to see changes in git repository when running tests.

            // Since Docker containers run as 'root' and any content written into the mounted directory is owned by
            // the 'root', the CI agent which runs as a non-root account cannot delete that content, so we try to
            // create content in a well known location on the CI agent so that these folders are deleted during the
            // clean-up task.
            var    agentName   = Environment.GetEnvironmentVariable(VstsAgentNameEnivronmentVariable);
            string tempDirRoot = null;

            if (string.IsNullOrEmpty(agentName))
            {
                // On dev machines, create the temporary folders underneath the 'bin' hierarchy itself. This way
                // a user can clean those folders when they do 'git clean -xdf' on their source repo.
                var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
                tempDirRoot = fileInfo.Directory.FullName;
            }
            else
            {
                // Put the folders in a well known location which the CI build definition looks for to clean up.
                tempDirRoot = Path.Combine(Path.GetTempPath(), MountedHostDirRootName);
            }

            var writableHostDir = Path.Combine(
                tempDirRoot,
                Guid.NewGuid().ToString("N"),
                dirInfo.Name);

            CopyDirectories(hostDir, writableHostDir, copySubDirs: true);

            // Grant permissions to the folder we just copied on the host machine. The permisions here allow the
            // user(a non-root user) in the container to read/write/execute files.
            var linuxOS = OSPlatform.Create("LINUX");

            if (RuntimeInformation.IsOSPlatform(linuxOS))
            {
                ProcessHelper.RunProcess(
                    "chmod",
                    new[] { "-R", "777", writableHostDir },
                    workingDirectory: null,
                    waitTimeForExit: null);
            }

            var containerDirName = dirInfo.Name;

            // Note: Path.Combine is the ideal solution here but this would fail when we run the
            // tests on a windows machine (which most of us use).
            var containerDir = $"{ContainerDirRoot}/{containerDirName}";

            return(new DockerVolume(hostDir, writableHostDir, containerDir));
        }
Esempio n. 18
0
        public IContainer CreateContainer(ContainerSpec containerSpec)
        {
            Guard.NotNull(containerSpec, "containerSpec");

            UndoStack  undoStack = new UndoStack();
            IContainer container;

            try
            {
                var handle = containerSpec.Handle;
                if (String.IsNullOrEmpty(handle))
                {
                    handle = handleHelper.GenerateHandle();
                }

                var id = handleHelper.GenerateId(handle);

                var user = ContainerUser.Create(userManager, id);
                undoStack.Push(() => user.Delete());

                var directory = directoryFactory.Create(fileSystem, containerBasePath, id);
                directory.CreateSubdirectories(user);
                undoStack.Push(directory.Destroy);

                directory.CreateBindMounts(containerSpec.BindMounts, user);

                var jobObject = new JobObject(id);
                undoStack.Push(() => jobObject.Dispose());

                var containerHostClient = containerHostService.StartContainerHost(id, directory, jobObject, user.GetCredential());
                undoStack.Push(() => containerHostClient.Shutdown());

                var constrainedProcessRunner = new ConstrainedProcessRunner(containerHostClient);
                undoStack.Push(() => constrainedProcessRunner.Dispose());

                var processHelper    = new ProcessHelper();
                var dependencyHelper = new ContainerHostDependencyHelper();

                var diskQuotaControl = diskQuotaManager.CreateDiskQuotaControl(directory);

                container = new Container(
                    id,
                    handle,
                    user,
                    directory,
                    containerPropertiesService,
                    tcpPortManager,
                    jobObject,
                    diskQuotaControl,
                    processRunner,
                    constrainedProcessRunner,
                    processHelper,
                    containerSpec.Environment,
                    dependencyHelper);

                containerPropertiesService.SetProperties(container, containerSpec.Properties);
                lock (containers)
                {
                    containers.Add(container);
                }
            }
            catch (Exception e)
            {
                try
                {
                    undoStack.UndoAll();
                    throw;
                }
                catch (AggregateException undoException)
                {
                    throw new AggregateException(new[] { e, undoException });
                }
            }

            return(container);
        }
Esempio n. 19
0
        public override void TestSuiteFinished(TestCaseSummary testResultsSummary)
        {
            base.TestSuiteFinished(testResultsSummary);

            if(!runContext.IsDataCollectionEnabled || testResultsSummary.CoverageObject == null)
            {
                return;
            }

            try
            {
                // If we do not have a solutiondirectory, we assume that we are running in tfs build
                // In that case we only write to the testrundirectory and do not open a browser
                if(string.IsNullOrEmpty(runContext.SolutionDirectory))
                {
                    ChutzpahTracer.TraceInformation("Chutzpah runs in TFSBuild, writing coverage file to {0}", runContext.TestRunDirectory);

                    var directory = runContext.TestRunDirectory;
                    CoverageOutputGenerator.WriteHtmlFile(Path.Combine(directory, Constants.CoverageHtmlFileName), testResultsSummary.CoverageObject);

                }
                else
                {
                    ChutzpahTracer.TraceInformation("Chutzpah runs not in TFSBuild opening coverage file in browser");

                    var directory = runContext.SolutionDirectory;
                    var coverageHtmlFile = CoverageOutputGenerator.WriteHtmlFile(Path.Combine(directory, Constants.CoverageHtmlFileName), testResultsSummary.CoverageObject);
                    var processHelper = new ProcessHelper();

                    processHelper.LaunchFileInBrowser(coverageHtmlFile);
                }
            }
            catch(Exception e)
            {
                frameworkHandle.SendMessage(TestMessageLevel.Error, string.Format("Error while writing coverage output: {0}", e));
            }
        }
        public void TestProcessNfieldOrPs_ObjectCanBeMapped_CallsNfieldAction()
        {
            int count = 0;

            var mockedMapper = new Mock<IPSObjectMapper>();
            var input = new PSObject();
            mockedMapper.Setup(x => x.To<Interviewer>(input))
                .Returns(new Interviewer());
            ProcessHelper target = new ProcessHelper(mockedMapper.Object);

            target.ProcessNfieldOrPs<Interviewer>(input,
                    (item) => { ++count; });

            Assert.Equal(1, count);
        }
Esempio n. 21
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Build Electron Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                if (!parser.Arguments.ContainsKey(_paramTarget))
                {
                    Console.WriteLine($"Error: missing '{_paramTarget}' argument.");
                    Console.WriteLine(COMMAND_ARGUMENTS);
                    return false;
                }

                var desiredPlatform = parser.Arguments[_paramTarget][0];
                string specifiedFromCustom = string.Empty;
                if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                {
                    specifiedFromCustom = parser.Arguments[_paramTarget][1];
                }

                string configuration = "Release";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid}...");

                string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "obj", "desktop", desiredPlatform);

                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }
                else
                {
                    Directory.Delete(tempPath, true);
                    Directory.CreateDirectory(tempPath);
                }


                Console.WriteLine("Executing dotnet publish in this directory: " + tempPath);

                string tempBinPath = Path.Combine(tempPath, "bin");

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid} under {configuration}-Configuration...");

                string publishReadyToRun = "/p:PublishReadyToRun=";
                if (parser.Arguments.ContainsKey(_paramPublishReadyToRun))
                {
                    publishReadyToRun += parser.Arguments[_paramPublishReadyToRun][0];
                }
                else
                {
                    publishReadyToRun += "true";
                }

                var resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} -c \"{configuration}\" --output \"{tempBinPath}\" {publishReadyToRun} --self-contained", Directory.GetCurrentDirectory());

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);
                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (parser.Arguments.ContainsKey(_paramPackageJson))
                {
                    Console.WriteLine("Copying custom package.json.");

                    File.Copy(parser.Arguments[_paramPackageJson][0], Path.Combine(tempPath, "package.json"), true);
                }

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (Directory.Exists(checkForNodeModulesDirPath) == false || parser.Contains(_paramForceNodeInstall) || parser.Contains(_paramPackageJson))
                {
                    Console.WriteLine("Start npm install...");
                }
                ProcessHelper.CmdExecute("npm install --production", tempPath);

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p . --sourceMap false", hosthookDir);
                }

                Console.WriteLine("Build Electron Desktop Application...");

                // Specifying an absolute path supercedes a relative path
                string buildPath = Path.Combine(Directory.GetCurrentDirectory(), "bin", "desktop");
                if (parser.Arguments.ContainsKey(_paramAbsoluteOutput))
                {
                    buildPath = parser.Arguments[_paramAbsoluteOutput][0];
                }
                else if (parser.Arguments.ContainsKey(_paramOutputDirectory))
                {
                    buildPath = Path.Combine(Directory.GetCurrentDirectory(), parser.Arguments[_paramOutputDirectory][0]);
                }

                Console.WriteLine("Executing electron magic in this directory: " + buildPath);

                string electronArch = "x64";
                if (parser.Arguments.ContainsKey(_paramElectronArch))
                {
                    electronArch = parser.Arguments[_paramElectronArch][0];
                }

                string electronParams = "";
                if (parser.Arguments.ContainsKey(_paramElectronParams))
                {
                    electronParams = parser.Arguments[_paramElectronParams][0];
                }

                // ToDo: Make the same thing easer with native c# - we can save a tmp file in production code :)
                Console.WriteLine("Create electron-builder configuration file...");

                string manifestFileName = "electron.manifest.json";

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    manifestFileName = parser.Arguments[_manifest].First();
                }

                ProcessHelper.CmdExecute($"node build-helper.js " + manifestFileName, tempPath);

                Console.WriteLine($"Package Electron App for Platform {platformInfo.ElectronPackerPlatform}...");
                ProcessHelper.CmdExecute($"npx electron-builder . --config=./bin/electron-builder.json --{platformInfo.ElectronPackerPlatform} --{electronArch} -c.electronVersion=9.0.0 {electronParams}", tempPath);

                Console.WriteLine("... done");

                return true;
            }));
        }
Esempio n. 22
0
        protected override void Execute(GVFSEnlistment enlistment)
        {
            string diagnosticsRoot = Path.Combine(enlistment.DotGVFSRoot, "diagnostics");

            if (!Directory.Exists(diagnosticsRoot))
            {
                Directory.CreateDirectory(diagnosticsRoot);
            }

            string archiveFolderPath = Path.Combine(diagnosticsRoot, "gvfs_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));

            Directory.CreateDirectory(archiveFolderPath);

            using (FileStream diagnosticLogFile = new FileStream(Path.Combine(archiveFolderPath, "diagnostics.log"), FileMode.CreateNew))
                using (this.diagnosticLogFileWriter = new StreamWriter(diagnosticLogFile))
                {
                    this.WriteMessage("Collecting diagnostic info into temp folder " + archiveFolderPath);

                    this.WriteMessage(string.Empty);
                    this.WriteMessage("gvfs version " + ProcessHelper.GetCurrentProcessVersion());

                    GitVersion gitVersion = null;
                    string     error      = null;
                    if (!string.IsNullOrEmpty(enlistment.GitBinPath) && GitProcess.TryGetVersion(enlistment.GitBinPath, out gitVersion, out error))
                    {
                        this.WriteMessage("git version " + gitVersion.ToString());
                    }
                    else
                    {
                        this.WriteMessage("Could not determine git version. " + error);
                    }

                    this.WriteMessage(enlistment.GitBinPath);
                    this.WriteMessage(string.Empty);
                    this.WriteMessage("Enlistment root: " + enlistment.EnlistmentRoot);
                    this.WriteMessage("Cache Server: " + CacheServerResolver.GetCacheServerFromConfig(enlistment));

                    string localCacheRoot;
                    string gitObjectsRoot;
                    this.GetLocalCachePaths(enlistment, out localCacheRoot, out gitObjectsRoot);
                    string actualLocalCacheRoot = !string.IsNullOrWhiteSpace(localCacheRoot) ? localCacheRoot : gitObjectsRoot;
                    this.WriteMessage("Local Cache: " + actualLocalCacheRoot);
                    this.WriteMessage(string.Empty);

                    this.PrintDiskSpaceInfo(actualLocalCacheRoot, this.EnlistmentRootPathParameter);

                    this.RecordVersionInformation();

                    this.ShowStatusWhileRunning(
                        () =>
                        this.RunAndRecordGVFSVerb <StatusVerb>(archiveFolderPath, "gvfs_status.txt") != ReturnCode.Success ||
                        this.RunAndRecordGVFSVerb <UnmountVerb>(archiveFolderPath, "gvfs_unmount.txt", verb => verb.SkipLock = true) == ReturnCode.Success,
                        "Unmounting",
                        suppressGvfsLogMessage: true);

                    this.ShowStatusWhileRunning(
                        () =>
                    {
                        // .gvfs
                        this.CopyAllFiles(enlistment.EnlistmentRoot, archiveFolderPath, GVFSConstants.DotGVFS.Root, copySubFolders: false);

                        if (!GVFSPlatform.Instance.IsUnderConstruction)
                        {
                            // driver
                            this.FlushKernelDriverLogs();
                            string kernelLogsFolderPath = GVFSPlatform.Instance.KernelDriver.LogsFolderPath;

                            // This copy sometimes fails because the OS has an exclusive lock on the etl files. The error is not actionable
                            // for the user so we don't write the error message to stdout, just to our own log file.
                            this.CopyAllFiles(Path.GetDirectoryName(kernelLogsFolderPath), archiveFolderPath, Path.GetFileName(kernelLogsFolderPath), copySubFolders: false, hideErrorsFromStdout: true);
                        }

                        // .git
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Root, copySubFolders: false);
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Hooks.Root, copySubFolders: false);
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Info.Root, copySubFolders: false);
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Logs.Root, copySubFolders: true);
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Refs.Root, copySubFolders: true);
                        this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Objects.Info.Root, copySubFolders: false);
                        this.LogDirectoryEnumeration(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Pack.Root, "packs-local.txt");
                        this.LogLooseObjectCount(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Root, "objects-local.txt");

                        // databases
                        this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), GVFSConstants.DotGVFS.Databases.Name, copySubFolders: false);

                        // local cache
                        this.CopyLocalCacheData(archiveFolderPath, localCacheRoot, gitObjectsRoot);

                        // corrupt objects
                        this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), GVFSConstants.DotGVFS.CorruptObjectsName, copySubFolders: false);

                        if (GVFSPlatform.Instance.SupportsGVFSService)
                        {
                            // service
                            this.CopyAllFiles(
                                Paths.GetServiceDataRoot(string.Empty),
                                archiveFolderPath,
                                this.ServiceName,
                                copySubFolders: true);
                        }

                        if (GVFSPlatform.Instance.SupportsGVFSUpgrade)
                        {
                            // upgrader
                            this.CopyAllFiles(
                                ProductUpgrader.GetUpgradesDirectoryPath(),
                                archiveFolderPath,
                                ProductUpgrader.LogDirectory,
                                copySubFolders: true,
                                targetFolderName: ProductUpgrader.UpgradeDirectoryName);
                            this.LogDirectoryEnumeration(
                                ProductUpgrader.GetUpgradesDirectoryPath(),
                                Path.Combine(archiveFolderPath, ProductUpgrader.UpgradeDirectoryName),
                                ProductUpgrader.DownloadDirectory,
                                "downloaded-assets.txt");
                        }

                        return(true);
                    },
                        "Copying logs");

                    this.ShowStatusWhileRunning(
                        () => this.RunAndRecordGVFSVerb <MountVerb>(archiveFolderPath, "gvfs_mount.txt") == ReturnCode.Success,
                        "Mounting",
                        suppressGvfsLogMessage: true);

                    this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFS.Root), "logs", copySubFolders: false);
                }

            string zipFilePath = archiveFolderPath + ".zip";

            this.ShowStatusWhileRunning(
                () =>
            {
                ZipFile.CreateFromDirectory(archiveFolderPath, zipFilePath);
                PhysicalFileSystem.RecursiveDelete(archiveFolderPath);

                return(true);
            },
                "Creating zip file",
                suppressGvfsLogMessage: true);

            this.Output.WriteLine();
            this.Output.WriteLine("Diagnostics complete. All of the gathered info, as well as all of the output above, is captured in");
            this.Output.WriteLine(zipFilePath);
        }
Esempio n. 23
0
        private void RecycleGuard()
        {
            // 创建自己的日志
            IDLog log = new TinyLog();

            log.Init(_config.ID + "_" + _config.AppName, _config.ID + "_" + _config.AppName + "/log");
            int count1 = 0;

            _appErrExecutor.Log = log;

            //监控间隔提醒
            if (_config.GuardInternal < 1500)
            {
                log.Fatal("注意: 配置的监控间隔小于1.5秒,监控非常容易出问题,监控停止!GuardInternal:" + _config.GuardInternal);
                return;
            }
            else if (_config.GuardInternal < 5000)
            {
                log.Warn("注意: 配置的监控间隔小于5秒,可能存在问题!GuardInternal:" + _config.GuardInternal);
            }


            while (Common.IsRun)
            {
                Thread.Sleep(_config.GuardInternal);
                log.Info("开始一次守护主流程+++++++++++++++++++++++++++++++++++++++++++++++");
                //进行进程守护 // 不管是哪种守护类型,都需要进行守护
                try
                {
                    if (_config.AppType == (int)Enums.EnumAppType.务)
                    {
                        ServiceManger sm = new ServiceManger();
                        if (sm.GetServiceValue(_config.AppName, "State").ToString().Equals(ServiceState.Stopped))
                        {
                            log.Error("服务状态已停止,开始处理错误");
                            _appErrExecutor.HandleError(Enums.EnumHandleCondition.务进程停止, _config, LastProcessTime);
                            continue;
                        }
                        else
                        {
                            log.Info("服务状态正在运行!");
                            LastProcessTime = DateTime.Now;
                        }
                    }
                    else
                    {
                        if (ProcessHelper.ExistProcess(_config.AppName) == false)
                        {
                            log.Error("进程已停止,开始处理错误");
                            _appErrExecutor.HandleError(Enums.EnumHandleCondition.务进程停止, _config, LastProcessTime);
                            continue;
                        }
                        else
                        {
                            log.Info("进程运行正常!");
                            LastProcessTime = DateTime.Now;
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(string.Format("进程守护 ID[{0}] 名称[{1}] 出错: ", _config.ID, _config.AppName) + ex.ToString());
                    continue;
                }

                if (_config.GuardType == (int)Enums.EnumGuardType.心跳守护)
                {
                    log.Info("开始心跳检测");
                    try
                    {
                        log.Info("开始检测状态中心健康情况");
                        IStateCenterConnector connector = StateCenterConnectorFactory.GetAvailableConnector();
                        if (connector == null || !connector.IsCenterAlived())
                        {
                            log.Error("状态中心无法连接,开始处理错误:");
                            _appErrExecutor.HandleError(Enums.EnumHandleCondition.务不可见, _config, LastStateCenterTime);
                            continue;
                        }
                        else
                        {
                            log.Info("状态中心连接正常");
                            LastStateCenterTime = DateTime.Now;
                        }
                        string beatName = ComputerInfo.GetMacAddress() + "." + _config.AppName;
                        log.Info(string.Format("开始获取心跳时间:[{0}]", beatName));
                        // 心跳检测
                        DateTime?lastBeatTime = connector.GetLastBeatTime(beatName);
                        if (lastBeatTime.HasValue == false)
                        {
                            log.Error("连接的服务未向中心发出心跳,首次连接不正常,不进行处理");
                            count1++;
                            if (count1 > 100)
                            {
                                log.Error("超过100次,无法抓取到首次心跳反应,监控终止");
                                return;
                            }
                        }
                        else
                        {
                            //首次心跳
                            if (LastBeatTime == null)
                            {
                                LastBeatTime = lastBeatTime;
                                log.Info("首次心跳时间:" + LastBeatTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                            else
                            {
                                log.Info("远程心跳时间: " + lastBeatTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                                //先判断是链路是否通着,只有通着的时候,才判断是否心跳
                                if (connector.IsClientAlived(beatName))
                                {
                                    if (lastBeatTime.Value == LastBeatTime.Value)
                                    {
                                        log.Error(string.Format("心跳未进行:处理问题  lastBeatTime:" + lastBeatTime.Value.ToString("yyyy-MM-dd HH:mm:ss")));
                                        _appErrExecutor.HandleError(Enums.EnumHandleCondition.务可见心脏停止跳动, _config, LastBeatTime);
                                    }
                                    else
                                    {
                                        LastBeatTime = lastBeatTime;
                                        log.Info("正常心跳");
                                        //重置状态
                                        _appErrExecutor.ResetState();
                                    }
                                }
                                else
                                {
                                    log.Error("客户端服务未能正常连接到状态中心,心跳监控失效");
                                    continue;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(string.Format("心跳 ID[{0}] 名称[{1}] 出错: ", _config.ID, _config.AppName) + ex.ToString());
                        continue;
                    }
                }
            }
        }
Esempio n. 24
0
        private void CreateEngine(ProcessHelper p)
        {
            try
            {
                Engine engine = new Engine(p.Process);
                Engine.Current = engine;

                p.Owner.CallUI <TextBlock>("Tag", "Account").SetUI <TextBlock>("Text", "Waiting for D3 to start...");
                p.Owner.CallUI <TextBlock>("Tag", "BattleTag").SetUI <TextBlock>("Text", "Gathering information...");

                while (engine == null)
                {
                    Thread.Sleep(1000);
                    engine         = new Engine(p.Process);
                    Engine.Current = engine;
                }

                while (engine.ApplicationLoopCount == 0)
                {
                    Thread.Sleep(1000);
                }

                Engine.Current = engine;
                p.Engine       = engine;

                p.Owner.CallUI <TextBlock>("Tag", "Account").SetUI <TextBlock>("Text", "Trying to resolve BattleTag");
                p.Owner.CallUI <TextBlock>("Tag", "BattleTag").SetUI <TextBlock>("Text", "Waiting for login into Diablo III");

                while (engine.Memory.Reader.ReadChain <int>(OffsetConversion.ScreenManager, OffsetConversion.BattleNetClient, OffsetConversion.SelectedHeroes) == 0) // Haven't loaded a hero or logged-in
                {
                    Thread.Sleep(1000);
                }

                if (Config.Get <FKAccounts>().GetAccount(HeroReader.GetBattleTag.ToString()) == null)
                {
                    p.Owner.CallUI <TextBlock>("Tag", "Account").SetUI <TextBlock>("Text", "This account has not been setup");
                    p.Owner.CallUI <TextBlock>("Tag", "Account").SetUI <TextBlock>("Foreground", Extensions.HexToBrush("#ff4444"));
                    p.Owner.CallUI <TextBlock>("Tag", "BattleTag").SetUI <TextBlock>("Text", "You need to configure it in Settings > Multibox Accounts");
                    return;
                }

                p.Owner.CallUI <TextBlock>("Tag", "Account").SetUI <TextBlock>("Text", Config.Get <FKAccounts>().GetAccount(HeroReader.GetBattleTag.ToString()).Nickname);
                p.AccountSettings = Config.Get <FKAccounts>().GetAccount(HeroReader.GetBattleTag.ToString());

                p.Loaded  = true;
                p.Enabled = true;

                //Extensions.Execute.UIThread(()=> p.Owner.CallUI<Image>("Tag", "EnableAcc").CheckBox(p.Enabled));
                p.Owner.CallUI <Image>("Tag", "EnableAcc").SetUI <Image>("Tag", p);

                p.Owner.CallUI <TextBlock>("Tag", "BattleTag").SetUI <TextBlock>("Text", HeroReader.GetBattleTag.ToString());


                if (Config.Get <FKAccounts>().GetAccount(HeroReader.GetBattleTag.ToString()).MainAccount)
                {
                    Extensions.Execute.UIThread(() =>
                    {
                        p.Owner.CallUI <Image>("Tag", "MainAccountSel").Source = Extensions.FKImage("./app");
                        p.Owner.CallUI <Image>("Tag", "MainAccountSel").FindParent <StackPanel>().ToolTip = new TextBlock {
                            Text = "This is set as your main account"
                        };
                    });
                }

                HeroData(p);
            }

            catch (Exception e)
            {
                Extensions.Execute.UIThread(() => MessageBox.Show(e.ToString()));
            }
        }
Esempio n. 25
0
 public XUnitHelper(Tracer tracer, FileSystemHelper fileSystem, ProcessHelper process)
 {
     _fileSystem = fileSystem;
     _process    = process;
     _tracer     = tracer;
 }
Esempio n. 26
0
 private void RemoveHandler(ProcessHelper Helper)
 {
     Helper.Process.Exited -= Helper.ExitHandler;
     Helper.Dispose();
     PHelper.Remove(Helper.Key);
 }
Esempio n. 27
0
        public static async Task ShowUserDialog(UserViewModel user)
        {
            if (user != null && !user.IsAnonymous)
            {
                object result = await DialogHelper.ShowCustom(new UserDialogControl(user));

                if (result != null)
                {
                    UserDialogResult dialogResult = EnumHelper.GetEnumValueFromString <UserDialogResult>(result.ToString());
                    switch (dialogResult)
                    {
                    case UserDialogResult.Purge:
                        await ChannelSession.Services.Chat.PurgeUser(user);

                        break;

                    case UserDialogResult.Timeout1:
                        await ChannelSession.Services.Chat.TimeoutUser(user, 60);

                        break;

                    case UserDialogResult.Timeout5:
                        await ChannelSession.Services.Chat.TimeoutUser(user, 300);

                        break;

                    case UserDialogResult.Ban:
                        if (await DialogHelper.ShowConfirmation(string.Format("This will ban the user {0} from this channel. Are you sure?", user.DisplayName)))
                        {
                            await ChannelSession.Services.Chat.BanUser(user);
                        }
                        break;

                    case UserDialogResult.Unban:
                        await ChannelSession.Services.Chat.UnbanUser(user);

                        break;

                    case UserDialogResult.Follow:
                        await ChannelSession.TwitchUserConnection.FollowUser(ChannelSession.TwitchUserNewAPI, user.GetTwitchNewAPIUserModel());

                        break;

                    case UserDialogResult.Unfollow:
                        await ChannelSession.TwitchUserConnection.UnfollowUser(ChannelSession.TwitchUserNewAPI, user.GetTwitchNewAPIUserModel());

                        break;

                    case UserDialogResult.PromoteToMod:
                        if (await DialogHelper.ShowConfirmation(string.Format("This will promote the user {0} to a moderator of this channel. Are you sure?", user.DisplayName)))
                        {
                            await ChannelSession.Services.Chat.ModUser(user);
                        }
                        break;

                    case UserDialogResult.DemoteFromMod:
                        if (await DialogHelper.ShowConfirmation(string.Format("This will demote the user {0} from a moderator of this channel. Are you sure?", user.DisplayName)))
                        {
                            await ChannelSession.Services.Chat.UnmodUser(user);
                        }
                        break;

                    case UserDialogResult.ChannelPage:
                        ProcessHelper.LaunchLink(user.ChannelLink);
                        break;

                    case UserDialogResult.EditUser:
                        UserDataModel userData = ChannelSession.Settings.GetUserData(user.ID);
                        if (userData != null)
                        {
                            UserDataEditorWindow window = new UserDataEditorWindow(userData);
                            await Task.Delay(100);

                            window.Show();
                            await Task.Delay(100);

                            window.Focus();
                        }
                        break;

                    case UserDialogResult.Close:
                    default:
                        // Just close
                        break;
                    }
                }
            }
        }
Esempio n. 28
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Start Electron Desktop Application...");

                string aspCoreProjectPath = "";

                if (_args.Length > 0)
                {
                    if (Directory.Exists(_args[0]))
                    {
                        aspCoreProjectPath = _args[0];
                    }
                }
                else
                {
                    aspCoreProjectPath = Directory.GetCurrentDirectory();
                }

                string tempPath = Path.Combine(aspCoreProjectPath, "obj", "Host");
                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                var platformInfo = GetTargetPlatformInformation.Do(String.Empty, String.Empty);

                string tempBinPath = Path.Combine(tempPath, "bin");
                var resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} --output \"{tempBinPath}\"", aspCoreProjectPath);

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (Directory.Exists(checkForNodeModulesDirPath) == false)
                {
                    Console.WriteLine("node_modules missing in: " + checkForNodeModulesDirPath);

                    Console.WriteLine("Start npm install...");
                    ProcessHelper.CmdExecute("npm install", tempPath);
                }
                else
                {
                    Console.WriteLine("Skip npm install, because node_modules directory exists in: " + checkForNodeModulesDirPath);
                }

                string path = Path.Combine(tempPath, "node_modules", ".bin");

                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    Console.WriteLine("Invoke electron.cmd - in dir: " + path);
                    ProcessHelper.CmdExecute(@"electron.cmd ""..\..\main.js""", path);
                }
                else
                {
                    Console.WriteLine("Invoke electron - in dir: " + path);
                    ProcessHelper.CmdExecute(@"./electron ""../../main.js""", path);
                }

                return true;
            }));
        }
Esempio n. 29
0
 public static void Main(string [] args)
 {
     ProcessHelper.Exit(Main2(args));               // Work around #499702
 }
Esempio n. 30
0
        internal override async Task <bool> OnAfterUpdate(SafeDictionary <string, object> keys)
        {
            if (Debugger.IsAttached)
            {
                if (MessageBox.Show("Install updates?", "Caution", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    return(true);
                }
            }
            ReportProgress("Installing Updates");
            await Task.Delay(1000);

            var dir = new DirectoryInfo(Common.Path() + "Updates");

            if (!dir.Exists)
            {
                dir.Create();
            }

            var name = Environment.MachineName;

            try
            {
                var resp =
                    await
                    ServerRequestHelper.GetObjectFromServerAsync <TerminalInfoResponse>(keys["hospitalserver"].ToString(),
                                                                                        "get_terminal_info/");

                name = resp.Result.TerminalName;
            }
            catch
            {
                //maybe get_terminal_info not implemented - compatibility
            }

            var nameRequiresChange = name != Environment.MachineName;

            ////throw new Exception("Sfgfg");
            var response =
                await
                ServerRequestHelper.GetObjectFromServerAsync <List <UpdatePackage> >(keys["hospitalserver"].ToString(), "get_terminal_updates/");

            var updates = new List <Update>();
            var freeze  = FreezeHelper.IsFreezeEnabled();

            if (!response.Success)
            {
                return(true);
            }
            if (nameRequiresChange)
            {
                if (await LockdownManager.IsFrozen() == true)
                {
                    ReportProgress("Rebooting to unfreeze");
                    await Task.Delay(1500);

                    LockdownManager.Unfreeze();
                    App.ShutdownSafe(false);
                    return(true);
                }
            }
            response.Result.ForEach(p => p.Updates.ForEach(u => u.PackageId = p.Id));

            if (nameRequiresChange)
            {
                if (Debugger.IsAttached)
                {
                    if (MessageBox.Show("Change hostname?", "Question", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        Common.SetMachineName(name);
                    }
                }
                else
                {
                    Common.SetMachineName(name);
                    ReportProgress("Rebooting to change hostname");
                    await Task.Delay(3000);

                    ProcessHelper.Reboot();
                    return(true);
                }
            }
            foreach (var package in response.Result)
            {
                ReportProgress(package.Name);
                foreach (var update in package.Updates)
                {
                    try
                    {
                        if (SkipUpdate(update.Id))
                        {
                            continue;
                        }
                        if (await LockdownManager.IsFrozen() == true)
                        {
                            ReportProgress("Rebooting to unfreeze");
                            await Task.Delay(1500);

                            LockdownManager.Unfreeze();
                            App.ShutdownSafe(false);
                            return(true);
                        }
                        updates.Add(update);
                        var tempPath  = System.IO.Path.GetTempPath(); //C:\\Users\\<UserName>\\AppData\\Local\\Temp
                        var updateDir = new DirectoryInfo(tempPath + "PanaceaUpdates\\" + update.Id);
                        if (!updateDir.Exists)
                        {
                            updateDir.Create();
                        }

                        await _webClient.DownloadFileTaskAsync(
                            new Uri(keys["hospitalserver"] + "/" + update.PatchScript),
                            updateDir + "\\" + Path.GetFileName(update.PatchScript));

                        foreach (var file in update.RequiredFiles)
                        {
                            await _webClient.DownloadFileTaskAsync(
                                new Uri(keys["hospitalserver"] + "/" + file),
                                updateDir + "\\" + Path.GetFileName(file));
                        }
                        ReportProgress("Installing...");
                        var code = await Task.Run(() =>
                        {
                            var info = new ProcessStartInfo()
                            {
                                WorkingDirectory = updateDir.ToString(),
                                FileName         = updateDir + "\\" + Path.GetFileName(update.PatchScript),
                                CreateNoWindow   = true,
                                UseShellExecute  = false,
                                Verb             = "runas"
                            };
                            var p = new Process {
                                StartInfo = info
                            };
                            try
                            {
                                p.Start();
                                p.WaitForExit();
                                return(p.ExitCode);
                            }
                            catch
                            {
                                return(9001);
                            }
                        });

                        //OnProgressFiles(code == 0 ? "Installation successful!" : "Installation failed");
                        await Task.Delay(1000);

                        update.Installed = code == 0;
                        update.ExitCode  = code;

                        if (code != 0)
                        {
                            continue;
                        }
                        AddRegistryUpdate(update);
                        await ReportToServer(keys["hospitalserver"].ToString(), update.Id, package.Id, code);

                        try
                        {
                            File.Delete(updateDir + "\\" + Path.GetFileName(update.PatchScript));
                            foreach (var file in update.RequiredFiles)
                            {
                                File.Delete(updateDir + "\\" + Path.GetFileName(file));
                            }
                        }
                        catch { }

                        if (update.RequiresReboot != "yes")
                        {
                            continue;
                        }
                        ProcessHelper.Reboot();
                        return(false);
                    }
                    catch
                    {
                        update.ExitCode = 9999;
                        AddRegistryUpdate(update);
                        await ReportToServer(keys["hospitalserver"].ToString(), update.Id, package.Id, 9999);
                    }
                }
            }
            if (updates.All(u => u.ExitCode != 0))
            {
                foreach (var update in updates)
                {
                    AddRegistryUpdate(update);
                    await ReportToServer(keys["hospitalserver"].ToString(), update.Id, update.PackageId, update.ExitCode);
                }
            }
            if (updates.Any(u => u.RequiresReboot == "batch" && u.ExitCode == 0))
            {
                ReportProgress("Restarting...");
                await Task.Delay(1500);

                ProcessHelper.Reboot();
                return(false);
            }

            if (updates.Any(u => u.ExitCode != 0) && updates.Any(u => u.ExitCode == 0))
            {
                ReportProgress("Rebooting to retry updates that failed...");
                await Task.Delay(1500);

                ProcessHelper.Reboot();
                return(false);
            }
            if (await LockdownManager.IsFrozen() == false && freeze)
            {
                if (updates.All(u => u.ExitCode == 0) || updates.All(u => u.ExitCode != 0))
                {
                    ReportProgress("Rebooting to freeze");
                    await Task.Delay(1500);

                    LockdownManager.Freeze();
                }
                App.ShutdownSafe(false);
                return(false);
            }
            return(true);
        }
        public ShaderCompilerResult Compile(ShaderCode shaderCode, ShaderCompilerArguments arguments)
        {
            var version = Version.Parse(arguments.GetString(CommonParameters.VersionParameterName));

            var isVersion21OrLater = version >= new Version(2, 1);
            var isVersion22OrLater = version >= new Version(2, 2);

            var asic          = arguments.GetString("Asic");
            var directXMode   = arguments.GetString("DirectXMode");
            var entryPoint    = arguments.GetString("EntryPoint");
            var targetProfile = arguments.GetString("TargetProfile");
            var shaderStage   = arguments.GetString(CommonParameters.GlslShaderStage.Name);

            using (var tempFile = TempFile.FromShaderCode(shaderCode))
            {
                var outputAnalysisPath = $"{tempFile.FilePath}.analysis";
                var ilPath             = $"{tempFile.FilePath}.il";
                var isaPath            = $"{tempFile.FilePath}.isa";
                var liveRegPath        = $"{tempFile.FilePath}.livereg";
                var cfgPath            = $"{tempFile.FilePath}.cfg";

                var args = $"--asic \"{asic}\" --il \"{ilPath}\" --line-numbers --isa \"{isaPath}\" --parse-isa --livereg \"{liveRegPath}\" --cfg \"{cfgPath}\"";

                switch (shaderCode.Language)
                {
                case LanguageNames.Hlsl:
                    switch (directXMode)
                    {
                    case "dx11":
                        args += isVersion22OrLater ? $" -s dx11" : " -s hlsl";
                        args += $" --profile {targetProfile} --function {entryPoint}";
                        args += $" \"{tempFile.FilePath}\"";
                        break;

                    case "dx12":
                        if (!isVersion22OrLater)
                        {
                            throw new InvalidOperationException("DX12 mode is only supported on RGA 2.2 and above");
                        }
                        args += " -s dx12";
                        var stage = targetProfile.Substring(0, 2);
                        args += $" --{stage}-model {targetProfile} --{stage}-entry {entryPoint}";
                        args += $" --all-hlsl \"{tempFile.FilePath}\"";
                        break;
                    }

                    break;

                case LanguageNames.Glsl:
                    switch (arguments.GetString("GlslTarget"))
                    {
                    case TargetOpenGL:
                        args += $" -s opengl --{shaderStage}";
                        break;

                    case TargetVulkan:
                        args += $" -s {(isVersion21OrLater ? "vk-offline" : "vulkan")} --{shaderStage}";
                        break;
                    }
                    args += $" \"{tempFile.FilePath}\"";
                    break;

                case LanguageNames.SpirvAssembly:
                    args += $" -s {(isVersion21OrLater ? "vk-spv-txt-offline" : "vulkan-spv-text")} --{shaderStage}";
                    args += $" \"{tempFile.FilePath}\"";
                    break;
                }

                var rgaPath = CommonParameters.GetBinaryPath("rga", arguments, "rga.exe");
                var result  = ProcessHelper.Run(
                    rgaPath,
                    args,
                    out var stdOutput,
                    out var stdError);

                var actualOutputPathPrefix = Path.GetDirectoryName(tempFile.FilePath);

                string GetActualOutputPath(string extension)
                {
                    if (extension == "analysis" && shaderCode.Language == LanguageNames.Hlsl)
                    {
                        return(Path.Combine(
                                   Path.GetDirectoryName(tempFile.FilePath),
                                   $"{entryPoint}_{Path.GetFileName(tempFile.FilePath)}.analysis"));
                    }

                    switch (shaderCode.Language)
                    {
                    case LanguageNames.Hlsl:
                        if (directXMode == "dx12")
                        {
                            switch (targetProfile.Substring(0, 2))
                            {
                            case "cs":
                                switch (extension)
                                {
                                case "isa":
                                    shaderStage = "comp";
                                    break;

                                default:
                                    shaderStage = "compute";
                                    break;
                                }
                                break;
                            }
                            goto default;
                        }
                        return(Path.Combine(
                                   actualOutputPathPrefix,
                                   $"{asic}_{entryPoint}_{Path.GetFileName(tempFile.FilePath)}.{extension}"));

                    default:
                        if (isVersion21OrLater)
                        {
                            return(Path.Combine(
                                       actualOutputPathPrefix,
                                       $"{asic}_{Path.GetFileName(tempFile.FilePath)}_{shaderStage}.{extension}"));
                        }
                        else
                        {
                            return(Path.Combine(
                                       actualOutputPathPrefix,
                                       $"{asic}_{shaderStage}_{Path.GetFileName(tempFile.FilePath)}.{extension}"));
                        }
                    }
                }

                outputAnalysisPath = GetActualOutputPath("analysis");
                ilPath             = GetActualOutputPath("il");
                isaPath            = GetActualOutputPath("isa");
                var isaCsvPath = GetActualOutputPath("csv");
                liveRegPath = GetActualOutputPath("livereg");
                cfgPath     = GetActualOutputPath("cfg");

                var outputAnalysis = FileHelper.ReadAllTextIfExists(outputAnalysisPath);
                var il             = FileHelper.ReadAllTextIfExists(ilPath);
                var isa            = FileHelper.ReadAllTextIfExists(isaPath);
                var isaCsv         = FileHelper.ReadAllTextIfExists(isaCsvPath);
                var liveReg        = FileHelper.ReadAllTextIfExists(liveRegPath);
                var cfg            = FileHelper.ReadAllTextIfExists(cfgPath);

                FileHelper.DeleteIfExists(outputAnalysisPath);
                FileHelper.DeleteIfExists(ilPath);
                FileHelper.DeleteIfExists(isaPath);
                FileHelper.DeleteIfExists(isaCsvPath);
                FileHelper.DeleteIfExists(liveRegPath);
                FileHelper.DeleteIfExists(cfgPath);

                var selectedOutputIndex = !result || stdOutput.Contains("\nError: ") || stdOutput.Contains("... failed.")
                    ? 5
                    : (int?)null;

                var isaBreakdownJson = GetIsaBreakdownJson(isaCsv);

                return(new ShaderCompilerResult(
                           selectedOutputIndex == null,
                           null,
                           selectedOutputIndex,
                           new ShaderCompilerOutput("ISA Disassembly", null, isa),
                           new ShaderCompilerOutput("ISA Breakdown", "jsontable", isaBreakdownJson),
                           new ShaderCompilerOutput("IL Disassembly", null, il),
                           //new ShaderCompilerOutput("Analysis", null, outputAnalysis),
                           new ShaderCompilerOutput("Live register analysis", null, liveReg),
                           new ShaderCompilerOutput("Control flow graph", "graphviz", cfg),
                           new ShaderCompilerOutput("Build output", null, stdOutput)));
            }
        }
Esempio n. 32
0
        protected override void Execute(GVFSEnlistment enlistment)
        {
            string diagnosticsRoot = Path.Combine(enlistment.DotGVFSRoot, "diagnostics");

            if (!Directory.Exists(diagnosticsRoot))
            {
                Directory.CreateDirectory(diagnosticsRoot);
            }

            string archiveFolderPath = Path.Combine(diagnosticsRoot, "gvfs_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));

            Directory.CreateDirectory(archiveFolderPath);

            using (FileStream diagnosticLogFile = new FileStream(Path.Combine(archiveFolderPath, "diagnostics.log"), FileMode.CreateNew))
                using (this.diagnosticLogFileWriter = new StreamWriter(diagnosticLogFile))
                {
                    this.WriteMessage("Collecting diagnostic info into temp folder " + archiveFolderPath);

                    this.WriteMessage(string.Empty);
                    this.WriteMessage("gvfs version " + ProcessHelper.GetCurrentProcessVersion());
                    this.WriteMessage(GitProcess.Version(enlistment).Output);
                    this.WriteMessage(GitProcess.GetInstalledGitBinPath());
                    this.WriteMessage(string.Empty);
                    this.WriteMessage("Enlistment root: " + enlistment.EnlistmentRoot);
                    this.WriteMessage("Repo URL: " + enlistment.RepoUrl);
                    this.WriteMessage("Objects URL: " + enlistment.ObjectsEndpointUrl);
                    this.WriteMessage(string.Empty);

                    this.WriteMessage("Copying .gvfs folder...");
                    this.CopyAllFiles(enlistment.EnlistmentRoot, archiveFolderPath, GVFSConstants.DotGVFSPath, copySubFolders: false);

                    this.WriteMessage("Copying GVFlt logs...");
                    this.FlushGvFltLogBuffers();
                    string system32LogFilesPath = Environment.ExpandEnvironmentVariables(System32LogFilesRoot);
                    this.CopyAllFiles(system32LogFilesPath, archiveFolderPath, GVFltLogFolderName, copySubFolders: false);

                    this.WriteMessage("Checking on GVFS...");
                    this.RunAndRecordGVFSVerb <LogVerb>(archiveFolderPath, "gvfs_log.txt");
                    ReturnCode statusResult = this.RunAndRecordGVFSVerb <StatusVerb>(archiveFolderPath, "gvfs_status.txt");

                    if (statusResult == ReturnCode.Success)
                    {
                        this.WriteMessage("GVFS is mounted. Unmounting so we can read files that GVFS has locked...");
                        this.RunAndRecordGVFSVerb <UnmountVerb>(archiveFolderPath, "gvfs_unmount.txt");
                    }
                    else
                    {
                        this.WriteMessage("GVFS was not mounted.");
                    }

                    this.WriteMessage("Checking Defender exclusion...");
                    this.WriteAntivirusExclusions(enlistment.EnlistmentRoot, archiveFolderPath, "DefenderExclusionInfo.txt");

                    this.WriteMessage("Copying .git folder...");
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Hooks.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Info.Root, copySubFolders: false);
                    this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Logs.Root, copySubFolders: true);

                    this.CopyEsentDatabase <Guid, GVFltCallbacks.BackgroundGitUpdate>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFSPath),
                        GVFSConstants.DatabaseNames.BackgroundGitUpdates);
                    this.CopyEsentDatabase <string, bool>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFSPath),
                        GVFSConstants.DatabaseNames.DoNotProject);
                    this.CopyEsentDatabase <string, long>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFSPath),
                        GVFSConstants.DatabaseNames.BlobSizes);
                    this.CopyEsentDatabase <string, string>(
                        enlistment.DotGVFSRoot,
                        Path.Combine(archiveFolderPath, GVFSConstants.DotGVFSPath),
                        GVFSConstants.DatabaseNames.RepoMetadata);

                    this.WriteMessage(string.Empty);
                    this.WriteMessage("Remounting GVFS...");
                    ReturnCode mountResult = this.RunAndRecordGVFSVerb <MountVerb>(archiveFolderPath, "gvfs_mount.txt");
                    if (mountResult == ReturnCode.Success)
                    {
                        this.WriteMessage("Mount succeeded");
                    }
                    else
                    {
                        this.WriteMessage("Failed to remount. The reason for failure was captured.");
                    }

                    this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGVFSPath), "logs", copySubFolders: false);
                }

            string zipFilePath = archiveFolderPath + ".zip";

            ZipFile.CreateFromDirectory(archiveFolderPath, zipFilePath);
            PhysicalFileSystem.RecursiveDelete(archiveFolderPath);

            this.Output.WriteLine();
            this.Output.WriteLine("Diagnostics complete. All of the gathered info, as well as all of the output above, is captured in");
            this.Output.WriteLine(zipFilePath);
            this.Output.WriteLine();
            this.Output.WriteLine("If you are experiencing an issue, please email the GVFS team with your repro steps and include this zip file.");
        }
Esempio n. 33
0
        private void OnGUI()
        {
            // 内容
            GUILayout.BeginVertical("box", GUILayout.Width(400), GUILayout.Height(250));
            {
                GUILayout.Space(5);
                GUILayout.BeginHorizontal();
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("SCP同步工具");
                    GUILayout.FlexibleSpace();
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(5);

                // IP地址输入框
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label("服务器ip:");
                    string currentIP = GUILayout.TextField(scpWindowData.serverIP, GUILayout.Width(250));
                    if (currentIP != scpWindowData.serverIP)
                    {
                        scpWindowData.serverIP = currentIP;
                        Save();
                    }
                }
                GUILayout.EndHorizontal();

                // 用户名输入框
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label("用户名:");
                    string currentUsername = GUILayout.TextField(scpWindowData.username, GUILayout.Width(250));
                    if (scpWindowData.username != currentUsername)
                    {
                        scpWindowData.username = currentUsername;
                        Save();
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.Space(20);

                // 同步热更程序
                GUILayout.BeginVertical("box", GUILayout.Width(400), GUILayout.Height(50));
                {
                    // 服务器程序地址
                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.Label("服务器程序地址:");
                        string currentProgramPath = GUILayout.TextField(scpWindowData.serverProgramPath, GUILayout.Width(250));
                        if (scpWindowData.serverProgramPath != currentProgramPath)
                        {
                            scpWindowData.serverProgramPath = currentProgramPath;
                            Save();
                        }
                    }
                    GUILayout.EndHorizontal();

                    GUILayout.Space(20);

                    if (GUILayout.Button("同步程序"))
                    {
                        Debug.Log("同步程序");
                        string localProgramPath = Application.dataPath.Replace("Unity/Assets", $"Bin/publish");
                        if (Directory.Exists(localProgramPath) == false)
                        {
                            Debug.LogError($"不存在路径: {localProgramPath}, 请检查是否 dotnet push ?");
                            return;
                        }

                        string arguments = $"-r {localProgramPath} {scpWindowData.username}@{scpWindowData.serverIP}:{scpWindowData.serverProgramPath}";

                        Debug.Log($"同步服务器程序, 命令: scp {arguments}");
                        ProcessHelper.Run("scp", arguments);
                    }
                }
                GUILayout.EndVertical();

                GUILayout.Space(20);

                // 同步热更资源
                GUILayout.BeginVertical("box", GUILayout.Width(400), GUILayout.Height(50));
                {
                    // 服务器资源地址
                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.Label("服务器资源地址:");
                        string currentBundlePath = GUILayout.TextField(scpWindowData.serverBundlePath, GUILayout.Width(250));
                        if (scpWindowData.serverBundlePath != currentBundlePath)
                        {
                            scpWindowData.serverBundlePath = currentBundlePath;
                            Save();
                        }
                    }
                    GUILayout.EndHorizontal();

                    GUILayout.Space(10);

                    // 平台类型
                    PlatformType currentPlatform = (PlatformType)EditorGUILayout.EnumPopup(scpWindowData.platformType);
                    if (scpWindowData.platformType != currentPlatform)
                    {
                        scpWindowData.platformType = currentPlatform;
                        Save();
                    }

                    GUILayout.Space(10);

                    if (GUILayout.Button("同步资源"))
                    {
                        if (scpWindowData.platformType == PlatformType.None)
                        {
                            Debug.LogError("请选择平台, 当前为: None");
                        }
                        else
                        {
                            // Release下的热更目录
                            string platformName    = Enum.GetName(typeof(PlatformType), scpWindowData.platformType);
                            string localBundlePath = Application.dataPath.Replace("Unity/Assets", $"Release/{platformName}");
                            if (Directory.Exists(localBundlePath) == false)
                            {
                                Debug.LogError($"不存在路径: {localBundlePath}, 请检查是否打包此平台的AssetBundle");
                                return;
                            }

                            string arguments = $"-r {localBundlePath} {scpWindowData.username}@{scpWindowData.serverIP}:{scpWindowData.serverBundlePath}";

                            Debug.Log($"同步服务器资源, 命令: scp {arguments}");
                            ProcessHelper.Run("scp", arguments);
                        }
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndVertical();
        }
Esempio n. 34
0
 /// <summary>
 /// Launch the WinMerge
 /// </summary>
 /// <param name="filePath">The differences file</param>
 public void LaunchApplication(string filePath)
 {
     ProcessHelper.Shell(filePath, string.Empty, ProcessWindowStyle.Normal, false);
 }
        public void Stop()
        {
            var ph = new ProcessHelper();

            ph.TerminateProcess(process);
        }
Esempio n. 36
0
        public HttpRequestor(ITracer tracer, RetryConfig retryConfig, GitAuthentication authentication)
        {
            this.client = new HttpClient(new HttpClientHandler()
            {
                UseDefaultCredentials = true
            });
            this.client.Timeout = retryConfig.Timeout;
            this.RetryConfig    = retryConfig;
            this.authentication = authentication;

            this.Tracer = tracer;

            this.userAgentHeader = new ProductInfoHeaderValue(ProcessHelper.GetEntryClassName(), ProcessHelper.GetCurrentProcessVersion());
        }
Esempio n. 37
0
 private static ProcessResult CallPowershellCommand(string command)
 {
     return(ProcessHelper.Run("powershell.exe", "-NonInteractive -NoProfile -Command \"& { " + command + " }\""));
 }
Esempio n. 38
0
        public async Task <ExitCode> ExecuteAsync(
            ILogger logger,
            IReadOnlyCollection <IVariable> buildVariables,
            CancellationToken cancellationToken)
        {
            var sourceRoot =
                new DirectoryInfo(buildVariables.Require(WellKnownVariables.SourceRoot).ThrowIfEmptyValue().Value);

            logger.Write($"Looking for paket.exe in source root {sourceRoot.FullName}");

            PathLookupSpecification pathLookupSpecification = DefaultPaths.DefaultPathLookupSpecification.WithIgnoredFileNameParts(new List <string>());

            FileInfo paketExe = null;

            List <string> packageSpecifications =
                sourceRoot.GetFilesRecursive(new List <string> {
                ".exe"
            }, pathLookupSpecification)
                .Where(file => file.Name.Equals("paket.exe", StringComparison.Ordinal))
                .Select(f => f.FullName)
                .ToList();

            if (!packageSpecifications.Any())
            {
                FileInfo normalSearch = sourceRoot.GetFiles("paket.exe", SearchOption.AllDirectories)
                                        .OrderBy(file => file.FullName.Length).FirstOrDefault();

                if (normalSearch != null)
                {
                    paketExe = normalSearch;
                }
                else
                {
                    logger.Write("Could not find paket.exe, skipping paket restore");
                    return(ExitCode.Success);
                }
            }

            if (paketExe == null)
            {
                IReadOnlyCollection <FileInfo> filtered =
                    packageSpecifications.Where(
                        packagePath =>
                        !pathLookupSpecification.IsFileBlackListed(
                            packagePath,
                            sourceRoot.FullName,
                            logger: logger).Item1)
                    .Select(file => new FileInfo(file))
                    .ToReadOnlyCollection();

                if (!filtered.Any())
                {
                    logger.Write(
                        $"Could not find paket.exe, filtered out: {string.Join(", ", packageSpecifications)}, skipping paket restore");
                    return(ExitCode.Success);
                }

                paketExe = filtered.First();
            }

            logger.Write($"Found paket.exe at '{paketExe.FullName}'");

            string copyFromPath = buildVariables.GetVariableValueOrDefault("Arbor.X.Build.Tools.Paket.CopyExeFromPath", string.Empty);

            if (!string.IsNullOrWhiteSpace(copyFromPath))
            {
                if (File.Exists(copyFromPath))
                {
                    File.Copy(copyFromPath, paketExe.FullName, overwrite: true);
                    logger.Write($"Copied paket.exe to {paketExe.FullName}");
                }
                else
                {
                    logger.Write($"The specified paket.exe path '{copyFromPath}' does not exist");
                }
            }
            else
            {
                logger.Write($"Found no paket.exe to copy");
            }

            Directory.SetCurrentDirectory(sourceRoot.FullName);

            ExitCode exitCode = await ProcessHelper.ExecuteAsync(
                paketExe.FullName,
                new List <string> {
                "restore"
            },
                logger,
                cancellationToken : cancellationToken);

            return(exitCode);
        }
Esempio n. 39
0
 public void Accept(ProcessHelper helper)
 {
     helper.SetColor(this);
 }
        public void TestProcessNfieldOrPs_ObjectCannotBeMapped_NotCallsNfieldAction()
        {
            int count = 0;

            var mockedMapper = new Mock<IPSObjectMapper>();
            var input = new PSObject();
            ProcessHelper target = new ProcessHelper(mockedMapper.Object);

            target.ProcessNfieldOrPs<Interviewer>(input,
                    (item) => { ++count; });

            Assert.Equal(0, count);
        }