コード例 #1
0
        public void login_should_authentificate_user_when_user_is_valid()
        {
            var user = _fixture.Create <ApplicationUser>();

            user.Roles = new List <UserRole>()
            {
                new UserRole()
                {
                    RoleName = RoleName.Coordinator
                }
            };
            var loginViewModel = new ViewModels.Account.Login()
            {
                Username = user.UserName,
                Password = user.Password
            };
            var valideUser = new MayBe <ApplicationUser>(user);

            accountService.ValidateUser(loginViewModel.Username, loginViewModel.Password).Returns(valideUser);
            accountService.isCoordonator(user).Returns(true);
            accountService.isBetweenAccesibleDates().Returns(true);

            accountController.Login(loginViewModel);

            httpContext.Received().AuthenticationSignIn(Arg.Any <ClaimsIdentity>());
        }
コード例 #2
0
        public void LoginACoordinator(ApplicationUser user, Login loginViewModel)
        {
            //Arrange
            var valideUser = new MayBe <ApplicationUser>(user);

            _accountService.ValidateUser(loginViewModel.Identifier, loginViewModel.Password).Returns(valideUser);
        }
コード例 #3
0
        bool ICustomizationService.ShowCustomizationMenu(object target)
        {
            if (_decorator == null)
            {
                return(false);
            }
            var barControl = target as BarControl;

            if (barControl != null && MayBe.Return(barControl.Bar, x => x.AllowCustomizationMenu, () => false))
            {
                return(_decorator.CustomizationHelper.ShowToolbarsCustomizationMenu(barControl));
            }
            var customizationButton = target as BarQuickCustomizationButton;

            if (customizationButton != null)
            {
                if (_decorator.CustomizationHelper.IsCustomizationMode)
                {
                    return(false);
                }
                return(_decorator.CustomizationHelper.ShowCustomizationMenu(MayBe.With(LayoutHelper.FindParentObject <BarControl>(customizationButton), x => x.Bar), customizationButton));
            }
            var linkControl = target as BarItemLinkControl;

            if (linkControl != null)
            {
                return(_decorator.CustomizationHelper.ShowItemCustomizationMenu(linkControl));
            }
            return(false);
        }
コード例 #4
0
        public void logout_should_logout_an_authentificated_user()
        {
            var user = _fixture.Create <ApplicationUser>();

            user.Roles = new List <UserRole>()
            {
                new UserRole()
                {
                    RoleName = RoleName.Coordinator
                }
            };
            var loginViewModel = new ViewModels.Account.Login()
            {
                Username = user.UserName,
                Password = user.Password
            };
            var valideUser = new MayBe <ApplicationUser>(user);

            accountService.ValidateUser(loginViewModel.Username, loginViewModel.Password).Returns(valideUser);

            accountController.Login(loginViewModel);
            accountController.Logout();

            httpContext.Received().AuthenticationSignOut();
        }
コード例 #5
0
 public static MayBe <UnificationResult> And(
     this MayBe <UnificationResult> @this,
     MayBe <UnificationResult> another)
 =>
 from first in @this
 from second in another
 select first.Concat(second).GroupBy(i => i.Key).AsImmutable() switch
 {
コード例 #6
0
        public DeploymentExecutionDefinition(
            string packageId,
            string targetDirectoryPath,
            MayBe <SemanticVersion> semanticVersion,
            string nuGetConfigFile    = null,
            string nuGetPackageSource = null,
            string iisSiteName        = null,
            bool isPreRelease         = false,
            bool force = false,
            string environmentConfig   = null,
            string publishSettingsFile = null,
            Dictionary <string, string[]> parameters = null,
            string excludedFilePatterns   = null,
            bool requireEnvironmentConfig = false,
            string webConfigTransformFile = null,
            string publishType            = null,
            string ftpPath                = null,
            string nugetExePath           = null,
            string packageListPrefix      = null,
            bool?packageListPrefixEnabled = null)
        {
            SemanticVersion = semanticVersion ?? MayBe <SemanticVersion> .Nothing;
            if (string.IsNullOrWhiteSpace(packageId))
            {
                throw new ArgumentNullException(nameof(packageId));
            }

            ExcludedFilePatterns = excludedFilePatterns?.Split(';').ToImmutableArray() ?? ImmutableArray <string> .Empty;

            PackageId           = packageId;
            TargetDirectoryPath = targetDirectoryPath;
            NuGetConfigFile     = nuGetConfigFile;
            NuGetPackageSource  = nuGetPackageSource;
            IisSiteName         = iisSiteName;
            IsPreRelease        = SemanticVersion?.IsPrerelease ?? isPreRelease;
            Force                    = force;
            EnvironmentConfig        = environmentConfig;
            PublishSettingsFile      = publishSettingsFile;
            RequireEnvironmentConfig = requireEnvironmentConfig;
            WebConfigTransformFile   = webConfigTransformFile;
            Parameters               = parameters?.ToDictionary(pair => pair.Key,
                                                                pair => new StringValues(pair.Value ?? Array.Empty <string>()))
                                       .ToImmutableDictionary() ??
                                       ImmutableDictionary <string, StringValues> .Empty;

            _       = PublishType.TryParseOrDefault(publishType, out PublishType publishTypeValue);
            _       = FtpPath.TryParse(ftpPath, FileSystemType.Directory, out FtpPath path);
            FtpPath = path;

            PublishType = publishTypeValue;

            ExcludedFilePatternsCombined = excludedFilePatterns;

            NuGetExePath             = nugetExePath;
            PackageListPrefix        = packageListPrefix;
            PackageListPrefixEnabled = packageListPrefixEnabled;
        }
コード例 #7
0
        public void login_post_should_render_default_view_when_user_is_not_valid()
        {
            var loginViewModel = _fixture.Create <ViewModels.Account.Login>();
            var invalidUser    = new MayBe <ApplicationUser>();

            accountService.ValidateUser(loginViewModel.Username, loginViewModel.Password).Returns(invalidUser);

            var result   = accountController.Login(loginViewModel) as ViewResult;
            var viewName = result.ViewName;

            viewName.Should().Be("");
        }
コード例 #8
0
        public void login_post_should_render_default_view_when_user_is_not_valid()
        {
            //Arrange
             var loginViewModel = _fixture.Create<LoginViewModel>();
             var invalidUser = new MayBe<MiamUser>();
             _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(invalidUser);

             //Action
             var result = _accountController.Login(loginViewModel) as ViewResult;
             var viewName = result.ViewName;

             //Assert
             viewName.Should().Be("");
        }
コード例 #9
0
        public static string Join <T>(Func <T, T, string> getSeparator, IEnumerable <T> sequence)
        {
            var       result          = new StringBuilder();
            MayBe <T> previousElement = None;

            foreach (var element in sequence)
            {
                result.Append(previousElement.Map(pe => getSeparator(pe, element)).OrElse(string.Empty));
                result.Append(element?.ToString() ?? string.Empty);
                previousElement = Some(element);
            }

            return(result.ToString());
        }
コード例 #10
0
        public void login_post_should_render_default_view_when_user_is_not_valid()
        {
            //Arrange
            var loginViewModel = _fixture.Create <LoginViewModel>();
            var invalidUser    = new MayBe <MiamUser>();

            _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(invalidUser);

            //Action
            var result   = _accountController.Login(loginViewModel) as ViewResult;
            var viewName = result.ViewName;

            //Assert
            viewName.Should().Be("");
        }
コード例 #11
0
        void ICustomizationService.RestoreCustomizationForm()
        {
            if (_decorator == null || !_decorator.CustomizationHelper.IsCustomizationMode || !_customizationFormHidden)
            {
                return;
            }
            _customizationFormHidden = false;

            // MayBe.Do(_decorator.CustomizationHelper.CustomizationForm, x => x.IsOpen = true);
            var helper = _decorator.CustomizationHelper as CustomBarManagerCustomizationHelper;

            if (helper != null)
            {
                MayBe.Do(helper.CustomizationForm, x => x.IsOpen = true);
            }
        }
コード例 #12
0
        public decimal ThanhTien_ThPh()
        {
            decimal kq = 0;

            var mayBe = MayBe.DocTheoId(View.IdThanhPhamChon);

            if (View.IdKhuonBeChon <= 0)
            {
                return(0);//Không thể không có khuôn
            }
            var khuonBe = KhuonBe.DocTheoId(View.IdKhuonBeChon);
            //Lưu ý số lượng tính giá
            var giaBe = new GiaBe(View.SoLuong, mayBe, khuonBe, this.TyLeMarkUp());

            kq = giaBe.ThanhTienSales();

            return(kq);
        }
コード例 #13
0
 void ICustomizationService.HideCustomizationMenu(object target)
 {
     if (_decorator == null)
     {
         return;
     }
     if (target == null)
     {
         _decorator.CustomizationHelper.HideCustomizationMenus();
     }
     else
     {
         var barControl = target as BarControl;
         if (barControl != null && MayBe.Return(barControl.Bar, x => x.AllowCustomizationMenu, () => false))
         {
             _decorator.CustomizationHelper.HideToolbarsCustomizationMenu(barControl);
         }
         else
         {
             var customizationButton = target as BarQuickCustomizationButton;
             if (customizationButton != null)
             {
                 if (_decorator.CustomizationHelper.IsCustomizationMode)
                 {
                     _decorator.CustomizationHelper.HideCustomizationMenu();
                 }
                 else
                 {
                     LayoutHelper.FindParentObject <BarControl>(customizationButton);
                     _decorator.CustomizationHelper.HideCustomizationMenu(customizationButton);
                 }
             }
             else
             {
                 var barItemLinkControl = target as BarItemLinkControl;
                 if (barItemLinkControl == null)
                 {
                     return;
                 }
                 _decorator.CustomizationHelper.HideItemCustomizationMenu(barItemLinkControl);
             }
         }
     }
 }
コード例 #14
0
        public void login_should_redirect_to_home_index_when_user_is_valid()
        {
            var user           = _fixture.Create <ApplicationUser>();
            var loginViewModel = new ViewModels.Account.Login()
            {
                Username = user.UserName,
                Password = user.Password
            };
            var valideUser = new MayBe <ApplicationUser>(user);

            accountService.ValidateUser(loginViewModel.Username, loginViewModel.Password).Returns(valideUser);
            accountService.isCoordonator(user).Returns(true);
            accountService.isBetweenAccesibleDates().Returns(true);

            var routeResult = accountController.Login(loginViewModel) as RedirectToRouteResult;
            var routeAction = routeResult.RouteValues["Action"];

            routeAction.Should().Be(MVC.Home.Views.ViewNames.Index);
        }
コード例 #15
0
        public void login_should_authentificate_user_when_user_is_valid()
        {
            //Arrange
            var user = _fixture.Create<MiamUser>();
            var loginViewModel = new LoginViewModel()
                                 {
                                    Email = user.Email,
                                    Password = user.Password
                                 };

            var valideUser = new MayBe<MiamUser>(user);
            _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(valideUser);

            //Action
            _accountController.Login(loginViewModel);

            //Assert
            _httpContext.Received().AuthenticationSignIn(Arg.Any<ClaimsIdentity>());
        }
コード例 #16
0
        public void login_should_authentificate_user_when_user_is_valid()
        {
            //Arrange
            var user           = _fixture.Create <MiamUser>();
            var loginViewModel = new LoginViewModel()
            {
                Email    = user.Email,
                Password = user.Password
            };

            var valideUser = new MayBe <MiamUser>(user);

            _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(valideUser);

            //Action
            _accountController.Login(loginViewModel);


            //Assert
            _httpContext.Received().AuthenticationSignIn(Arg.Any <ClaimsIdentity>());
        }
コード例 #17
0
        public void login_should_redirect_to_home_index_when_user_is_valid()
        {
            //Arrange
            var user           = _fixture.Create <MiamUser>();
            var loginViewModel = new LoginViewModel()
            {
                Email    = user.Email,
                Password = user.Password
            };

            var valideUser = new MayBe <MiamUser>(user);

            _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(valideUser);

            //Action
            var routeResult = _accountController.Login(loginViewModel) as RedirectToRouteResult;
            var routeAction = routeResult.RouteValues["Action"];

            //Assert
            routeAction.Should().Be(MVC.Home.Views.ViewNames.Index);
        }
コード例 #18
0
        public int userlogin()
        {
            var user = _fixture.Create <ApplicationUser>();

            user.Roles = new List <UserRole>()
            {
                new UserRole()
                {
                    RoleName = RoleName.Coordinator
                }
            };
            var loginViewModel = new ViewModels.Account.Login()
            {
                Username = user.UserName,
                Password = user.Password
            };
            var valideUser = new MayBe <ApplicationUser>(user);

            accountService.ValidateUser(loginViewModel.Username, loginViewModel.Password).Returns(valideUser);
            httpContextService.GetUserId().Returns(user.Id);
            accountController.Login(loginViewModel);

            return(user.Id);
        }
コード例 #19
0
        public void LoginAnEmployee(ApplicationUser user, Login loginViewModel)
        {
            var valideUser = new MayBe <ApplicationUser>(user);

            _accountService.ValidateUser(loginViewModel.Identifier, loginViewModel.Password).Returns(valideUser);
        }
コード例 #20
0
        public void login_should_redirect_to_home_index_when_user_is_valid()
        {
            //Arrange
            var user = _fixture.Create<MiamUser>();
            var loginViewModel = new LoginViewModel()
            {
                Email = user.Email,
                Password = user.Password
            };

            var valideUser = new MayBe<MiamUser>(user);
            _userAccountService.ValidateUser(loginViewModel.Email, loginViewModel.Password).Returns(valideUser);

            //Action
            var routeResult = _accountController.Login(loginViewModel) as RedirectToRouteResult;
            var routeAction = routeResult.RouteValues["Action"];

            //Assert
            routeAction.Should().Be(MVC.Home.Views.ViewNames.Index);
        }
コード例 #21
0
        private async Task <EnvironmentPackageResult> AddEnvironmentPackageAsync(
            DeploymentExecutionDefinition deploymentExecutionDefinition,
            DirectoryInfo tempDirectoryInfo,
            List <FileMatch> possibleXmlTransformations,
            List <FileMatch> replaceFiles,
            List <DirectoryInfo> tempDirectoriesToClean,
            SemanticVersion version,
            CancellationToken cancellationToken = default)
        {
            _logger.Debug("Fetching environment configuration {EnvironmentConfig}",
                          deploymentExecutionDefinition.EnvironmentConfig);

            SemanticVersion expectedVersion   = version;
            string          expectedPackageId =
                $"{deploymentExecutionDefinition.PackageId}.{DeploymentConstants.EnvironmentLiteral}.{deploymentExecutionDefinition.EnvironmentConfig}";

            ImmutableArray <SemanticVersion> allVersions = await _nugetPackageInstaller.GetAllVersionsAsync(
                new NuGetPackageId(expectedPackageId),
                allowPreRelease : expectedVersion.IsPrerelease,
                nuGetSource : deploymentExecutionDefinition.NuGetPackageSource,
                nugetConfig : deploymentExecutionDefinition.NuGetConfigFile,
                nugetExePath : deploymentExecutionDefinition.NuGetExePath,
                timeoutInSeconds : 35,
                adaptiveEnabled : deploymentExecutionDefinition.PackageListPrefixEnabled,
                prefix : deploymentExecutionDefinition.PackageListPrefixEnabled.HasValue && deploymentExecutionDefinition.PackageListPrefixEnabled.Value?deploymentExecutionDefinition.PackageListPrefix : ""
                );

            var matchingFoundEnvironmentPackage = allVersions
                                                  .Where(currentVersion => currentVersion == expectedVersion)
                                                  .ToList();

            if (matchingFoundEnvironmentPackage.Count > 1)
            {
                _logger.Error("Found multiple environment packages matching '{ExpectedMatch}', {Found}",
                              expectedVersion.ToNormalizedString(),
                              string.Join(", ", matchingFoundEnvironmentPackage.Select(currentVersion => $"'{currentVersion.ToNormalizedString()}'")));
                return(new EnvironmentPackageResult(false));
            }

            const string environmentConfigPrefix = "EF_";

            if (matchingFoundEnvironmentPackage.Any())
            {
                var tempInstallDirectory =
                    new DirectoryInfo(
                        Path.Combine(
                            tempDirectoryInfo.FullName,
                            $"{environmentConfigPrefix}tmp",
                            deploymentExecutionDefinition.EnvironmentConfig));

                var deploymentDefinition =
                    new DeploymentExecutionDefinition(
                        expectedPackageId,
                        tempInstallDirectory.FullName,
                        expectedVersion,
                        nugetExePath: deploymentExecutionDefinition.NuGetExePath,
                        nuGetPackageSource: deploymentExecutionDefinition.NuGetPackageSource,
                        nuGetConfigFile: deploymentExecutionDefinition.NuGetConfigFile);

                var tempOutputDirectory =
                    new DirectoryInfo(
                        Path.Combine(
                            tempDirectoryInfo.FullName,
                            $"{environmentConfigPrefix}out",
                            deploymentExecutionDefinition.EnvironmentConfig));

                MayBe <InstalledPackage> installedEnvironmentPackage =
                    await
                    _packageInstaller.InstallPackageAsync(
                        deploymentDefinition,
                        tempOutputDirectory,
                        false,
                        null,
                        cancellationToken).ConfigureAwait(false);

                if (!installedEnvironmentPackage.HasValue)
                {
                    _logger.Error(
                        "No environment NuGet package was installed for deployment definition {DeploymentDefinition}",
                        deploymentDefinition);

                    return(new EnvironmentPackageResult(false));
                }

                var configContentDirectory =
                    new DirectoryInfo(
                        Path.Combine(tempOutputDirectory.FullName, expectedPackageId, "content"));

                if (!configContentDirectory.Exists)
                {
                    _logger.Debug("The content directory for the environment package does not exist");
                }
                else
                {
                    ImmutableArray <EnvironmentFile> environmentFiles = GetEnvironmentFiles(
                        configContentDirectory,
                        deploymentExecutionDefinition);

                    if (environmentFiles.Any())
                    {
                        foreach (EnvironmentFile item in environmentFiles)
                        {
                            FindMatches(item, possibleXmlTransformations, configContentDirectory, replaceFiles);
                        }
                    }
                    else
                    {
                        IEnumerable <string> fileNamesToConcat =
                            configContentDirectory.GetFiles().Select(file => $"'{file.Name}'");

                        string foundFiles = string.Join(", ", fileNamesToConcat);

                        _logger.Debug("Could not find any action files in package, all files {FoundFiles}",
                                      foundFiles);
                    }
                }

                _logger.Verbose("Deleting transformation package temp directory '{TempOutputDirectory}'",
                                tempOutputDirectory);

                tempDirectoriesToClean.Add(tempOutputDirectory);
            }
            else
            {
                if (deploymentExecutionDefinition.RequireEnvironmentConfig)
                {
                    _logger.Error(
                        "Environment config was set to {EnvironmentConfig} but no package was found with id {ExpectedPackageId} and version {Version}, deployment definition require the environment config",
                        deploymentExecutionDefinition.EnvironmentConfig,
                        expectedPackageId,
                        expectedVersion.ToNormalizedString());

                    return(new EnvironmentPackageResult(false));
                }

                _logger.Debug(
                    "Environment config was set to {EnvironmentConfig} but no package was found with id {ExpectedPackageId} and version {Version}",
                    deploymentExecutionDefinition.EnvironmentConfig,
                    expectedPackageId,
                    expectedVersion.ToNormalizedString());
            }

            var foundPackage = matchingFoundEnvironmentPackage.SingleOrDefault();

            return(new EnvironmentPackageResult(true, foundPackage));
        }
コード例 #22
0
        private async Task <ExitCode> InternalDeployAsync(
            ImmutableArray <DeploymentExecutionDefinition> deploymentExecutionDefinitions,
            SemanticVersion explicitVersion,
            CancellationToken cancellationToken = default)
        {
            var tempDirectoriesToClean = new List <DirectoryInfo>();
            var tempFilesToClean       = new List <string>();

            try
            {
                _logger.Verbose("Executing deployment execution definitions [{Length}]: {Executions}",
                                deploymentExecutionDefinitions.Length,
                                string.Join($"{Environment.NewLine}\t", deploymentExecutionDefinitions.Select(_ => $"'{_}'")));

                foreach (DeploymentExecutionDefinition deploymentExecutionDefinition in deploymentExecutionDefinitions)
                {
                    if (string.IsNullOrWhiteSpace(deploymentExecutionDefinition.TargetDirectoryPath) &&
                        string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile))
                    {
                        throw new InvalidOperationException($"{nameof(deploymentExecutionDefinition.TargetDirectoryPath)} and {nameof(deploymentExecutionDefinition.PublishSettingsFile)} are both not set");
                    }

                    string asJson = JsonConvert.SerializeObject(deploymentExecutionDefinition, Formatting.Indented);
                    _logger.Information("Executing deployment execution definition: '{DeploymentExecutionDefinition}'",
                                        asJson);

                    const string TempPrefix = "MD-";

                    string uniqueSuffix = DateTime.Now.ToString("MMddHHmmssfff", CultureInfo.InvariantCulture);

                    string tempPath = Path.Combine(
                        Path.GetTempPath(),
                        $"{TempPrefix}{uniqueSuffix}{Guid.NewGuid().ToString().Substring(0, 6)}");

                    var           tempWorkingDirectory        = new DirectoryInfo(tempPath);
                    DirectoryInfo packageInstallTempDirectory = tempWorkingDirectory;

                    tempDirectoriesToClean.Add(packageInstallTempDirectory);

                    MayBe <InstalledPackage> installedMainPackage =
                        await _packageInstaller.InstallPackageAsync(
                            deploymentExecutionDefinition,
                            packageInstallTempDirectory,
                            false,
                            explicitVersion,
                            cancellationToken).ConfigureAwait(false);

                    if (!installedMainPackage.HasValue)
                    {
                        _logger.Error(
                            "Could not install package defined in deployment execution definition {DeploymentExecutionDefinition}",
                            deploymentExecutionDefinition);
                        return(ExitCode.Failure);
                    }

                    InstalledPackage installedPackage = installedMainPackage.Value;

                    _logger.Information(
                        "Successfully installed NuGet package '{PackageId}' version '{Version}' to path '{NugetPackageFullPath}'",
                        installedPackage.PackageId,
                        installedPackage.Version.ToNormalizedString(),
                        installedPackage.NugetPackageFullPath);

                    tempWorkingDirectory.Refresh();

                    DirectoryInfo[] packagesDirectory = tempWorkingDirectory.GetDirectories();

                    DirectoryInfo packageDirectory =
                        packagesDirectory.Single(directory =>
                                                 directory.Name.Equals(installedPackage.PackageId, StringComparison.OrdinalIgnoreCase));

                    SemanticVersion version = explicitVersion ?? GetSemanticVersionFromDefinition(
                        deploymentExecutionDefinition,
                        packageDirectory,
                        installedPackage.Version);

                    _logger.Verbose("Package version is {Version}", version.ToNormalizedString());

                    var possibleXmlTransformations = new List <FileMatch>();
                    var replaceFiles = new List <FileMatch>();

                    var environmentPackageResult = new EnvironmentPackageResult(true);

                    var contentDirectory =
                        new DirectoryInfo(Path.Combine(packageDirectory.FullName, "Content"));

                    if (!contentDirectory.Exists)
                    {
                        _logger.Error("Content directory '{FullName}' does not exist", contentDirectory.FullName);
                        return(ExitCode.Failure);
                    }

                    FileInfo contentFilesJson = packageDirectory.GetFiles("contentFiles.json").SingleOrDefault();

                    if (contentFilesJson?.Exists == true)
                    {
                        ExitCode exitCode = VerifyFiles(contentFilesJson.FullName, contentDirectory);

                        if (!exitCode.IsSuccess)
                        {
                            return(exitCode);
                        }
                    }
                    else
                    {
                        _logger.Debug("No file contentFiles.json was found in package directory {PackageDirectory}",
                                      packageDirectory.FullName);
                    }

                    if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.EnvironmentConfig))
                    {
                        _logger.Information(
                            "Fetching environment packages for package {Package} and environment {Environment}",
                            deploymentExecutionDefinition.PackageId, deploymentExecutionDefinition.EnvironmentConfig);

                        environmentPackageResult = await AddEnvironmentPackageAsync(deploymentExecutionDefinition,
                                                                                    packageInstallTempDirectory,
                                                                                    possibleXmlTransformations,
                                                                                    replaceFiles,
                                                                                    tempDirectoriesToClean,
                                                                                    version,
                                                                                    cancellationToken).ConfigureAwait(false);

                        if (!environmentPackageResult.IsSuccess)
                        {
                            return(ExitCode.Failure);
                        }

                        if (environmentPackageResult.Version != null)
                        {
                            _logger.Information("Installed environment package version {Version}",
                                                environmentPackageResult.Version.ToNormalizedString());
                        }
                        else
                        {
                            _logger.Information("No environment package was installed");
                        }
                    }
                    else
                    {
                        _logger.Debug("Definition has no environment configuration specified");
                    }

                    if (possibleXmlTransformations.Any())
                    {
                        _logger.Debug("Possible Xml transformation files {V}",
                                      string.Join(", ",
                                                  possibleXmlTransformations.Select(fileMatch =>
                                                                                    $"'{fileMatch.TargetName}' replaced by --> '{fileMatch.ActionFile.FullName}'")));
                    }

                    var xmlTransformedFiles = new List <string>();

                    foreach (FileMatch possibleXmlTransformation in possibleXmlTransformations)
                    {
                        TransformationResult result = _xmlTransformer.TransformMatch(possibleXmlTransformation,
                                                                                     contentDirectory);

                        if (!result.IsSuccess)
                        {
                            return(ExitCode.Failure);
                        }

                        xmlTransformedFiles.AddRange(result.TransformedFiles);
                    }

                    if (replaceFiles.Any())
                    {
                        _logger.Debug("Possible replacing files {Files}",
                                      string.Join(", ",
                                                  replaceFiles.Select(fileMatch =>
                                                                      $"'{fileMatch.TargetName}' replaced by --> '{fileMatch.ActionFile.FullName}'")));
                    }

                    var replacedFiles = new List <string>();

                    foreach (FileMatch replacement in replaceFiles)
                    {
                        ReplaceResult result = ReplaceFileIfMatchingFiles(replacement, contentDirectory);

                        if (!result.IsSuccess)
                        {
                            return(ExitCode.Failure);
                        }

                        replacedFiles.AddRange(result.ReplacedFiles);
                    }

                    if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.WebConfigTransformFile))
                    {
                        DeploymentTransformation.Transform(deploymentExecutionDefinition, contentDirectory, _logger);
                    }

                    string uniqueTargetTempSuffix =
                        DateTime.Now.ToString("MMddHHmmssfff", CultureInfo.InvariantCulture);

                    string uniqueTargetTempPath = Path.Combine(
                        Path.GetTempPath(),
                        $"{TempPrefix}t{uniqueTargetTempSuffix}{Guid.NewGuid().ToString().Substring(0, 6)}");

                    var targetTempDirectoryInfo =
                        new DirectoryInfo(uniqueTargetTempPath);

                    if (!targetTempDirectoryInfo.Exists)
                    {
                        _logger.Debug("Creating temp target directory '{FullName}'",
                                      packageInstallTempDirectory.FullName);
                        targetTempDirectoryInfo.Create();
                    }

                    string wwwrootPath = Path.Combine(contentDirectory.FullName, "wwwroot");

                    var wwwRootDirectory = new DirectoryInfo(wwwrootPath);

                    DirectoryInfo applicationMetadataTargetDirectory =
                        wwwRootDirectory.Exists ? wwwRootDirectory : contentDirectory;

                    string versionFile = ApplicationMetadataCreator.SetVersionFile(
                        installedMainPackage.Value,
                        applicationMetadataTargetDirectory,
                        deploymentExecutionDefinition,
                        xmlTransformedFiles,
                        replacedFiles,
                        environmentPackageResult,
                        _logger);

                    _logger.Information("Successfully wrote metadata file {Path}", versionFile);

                    _logger.Verbose("Copying content files to '{FullName}'", targetTempDirectoryInfo.FullName);

                    bool usePublishSettingsFile =
                        !string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile);

                    var targetAppOffline = new FileInfo(Path.Combine(targetTempDirectoryInfo.FullName,
                                                                     DeploymentConstants.AppOfflineHtm));

                    var ruleConfiguration = RuleConfiguration.Get(deploymentExecutionDefinition,
                                                                  DeployerConfiguration,
                                                                  _logger);

                    if (ruleConfiguration.AppOfflineEnabled && usePublishSettingsFile)
                    {
                        string sourceAppOffline =
                            Path.Combine(contentDirectory.FullName, DeploymentConstants.AppOfflineHtm);

                        if (!File.Exists(sourceAppOffline) && !targetAppOffline.Exists)
                        {
                            using var _ = File.Create(targetAppOffline.FullName);

                            _logger.Debug("Created offline file '{File}'", targetAppOffline.FullName);

                            if (DeployerConfiguration.DefaultWaitTimeAfterAppOffline > TimeSpan.Zero)
                            {
                                await Task.Delay(DeployerConfiguration.DefaultWaitTimeAfterAppOffline,
                                                 cancellationToken)
                                .ConfigureAwait(false);
                            }

                            tempFilesToClean.Add(targetAppOffline.FullName);
                        }
                    }

                    RecursiveIO.RecursiveCopy(contentDirectory,
                                              targetTempDirectoryInfo,
                                              _logger,
                                              deploymentExecutionDefinition.ExcludedFilePatterns);

                    tempDirectoriesToClean.Add(targetTempDirectoryInfo);

                    _logger.Debug("Copied content files from '{ContentDirectory}' to '{FullName}'",
                                  contentDirectory,
                                  targetTempDirectoryInfo.FullName);
                    tempDirectoriesToClean.Add(packageInstallTempDirectory);

                    bool hasPublishSettingsFile =
                        !string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile) &&
                        File.Exists(deploymentExecutionDefinition.PublishSettingsFile);

                    if (hasPublishSettingsFile)
                    {
                        _logger.Debug("The publish settings file '{PublishSettingsFile}' exists",
                                      deploymentExecutionDefinition.PublishSettingsFile);
                    }
                    else
                    {
                        _logger.Debug("The deployment definition has no publish setting file");
                    }

                    if (deploymentExecutionDefinition.PublishType == PublishType.WebDeploy)
                    {
                        _webDeployHelper.DeploymentTraceEventHandler += (sender, args) =>
                        {
                            if (string.IsNullOrWhiteSpace(args.Message))
                            {
                                return;
                            }

                            if (args.EventLevel == TraceLevel.Verbose)
                            {
                                _logger.Verbose("{Message}", args.Message);
                                return;
                            }

                            _logger.Information("{Message}", args.Message);
                        };
                    }

                    bool hasIisSiteName = deploymentExecutionDefinition.IisSiteName.HasValue();
                    IDeploymentChangeSummary summary;

                    try
                    {
                        IIisManager?manager = default;

                        if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.IisSiteName))
                        {
                            manager = _iisManager(deploymentExecutionDefinition);
                        }

                        if (hasIisSiteName && manager is {})
                        {
                            bool stopped = manager.StopSiteIfApplicable();

                            if (!stopped)
                            {
                                _logger.Error(
                                    "Could not stop IIS site for deployment execution definition {DeploymentExecutionDefinition}",
                                    deploymentExecutionDefinition);
                                return(ExitCode.Failure);
                            }
                        }

                        try
                        {
                            if (deploymentExecutionDefinition.PublishType == PublishType.WebDeploy)
                            {
                                _logger.Information("Deploying {Target} with WebDeploy",
                                                    deploymentExecutionDefinition.TargetDirectoryPath);
                                summary = await _webDeployHelper.DeployContentToOneSiteAsync(
                                    targetTempDirectoryInfo.FullName,
                                    deploymentExecutionDefinition.PublishSettingsFile,
                                    DeployerConfiguration.DefaultWaitTimeAfterAppOffline,
                                    doNotDelete : ruleConfiguration.DoNotDeleteEnabled,
                                    appOfflineEnabled : ruleConfiguration.AppOfflineEnabled,
                                    useChecksum : ruleConfiguration.UseChecksumEnabled,
                                    whatIf : ruleConfiguration.WhatIfEnabled,
                                    traceLevel : TraceLevel.Verbose,
                                    appDataSkipDirectiveEnabled : ruleConfiguration.AppDataSkipDirectiveEnabled,
                                    applicationInsightsProfiler2SkipDirectiveEnabled :
                                    ruleConfiguration.ApplicationInsightsProfiler2SkipDirectiveEnabled,
                                    logAction : message => _logger.Debug("{Message}", message),
                                    targetPath : hasPublishSettingsFile
                                    ?string.Empty
                                    : deploymentExecutionDefinition.TargetDirectoryPath
                                    ).ConfigureAwait(false);
                            }
                            else if (deploymentExecutionDefinition.PublishType.IsAnyFtpType)
                            {
                                var basePath = deploymentExecutionDefinition.FtpPath;

                                bool isSecure = deploymentExecutionDefinition.PublishType == PublishType.Ftps;

                                var ftpSettings = new FtpSettings(basePath, isSecure);

                                _logger.Information("Deploying {Target} with {PublishType}",
                                                    deploymentExecutionDefinition.FtpPath?.Path,
                                                    deploymentExecutionDefinition.PublishType);
                                string publishSettingsFile = deploymentExecutionDefinition.PublishSettingsFile;

                                if (string.IsNullOrWhiteSpace(publishSettingsFile))
                                {
                                    _logger.Error(
                                        "Deployment target type is set to {Type} but no publish file is set",
                                        deploymentExecutionDefinition.PublishTypeValue);
                                    return(ExitCode.Failure);
                                }

                                using IFtpHandler ftpHandler = await _ftpHandlerFactory.CreateWithPublishSettings(
                                          publishSettingsFile,
                                          ftpSettings,
                                          _logger, cancellationToken);

                                _logger.Verbose("Created FTP handler, starting publish");

                                summary = await ftpHandler.PublishAsync(
                                    ruleConfiguration,
                                    targetTempDirectoryInfo,
                                    cancellationToken);
                            }
                            else
                            {
                                throw new InvalidOperationException(
                                          $"Publish type {deploymentExecutionDefinition.PublishType} is not supported");
                            }
                        }
                        catch (Exception ex) when(!ex.IsFatal())
                        {
                            _logger.Error(ex,
                                          "Could not deploy site {DeploymentExecutionDefinition}",
                                          deploymentExecutionDefinition);

                            return(ExitCode.Failure);
                        }
                        finally
                        {
                            manager?.Dispose();
                        }
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        _logger.Error(ex,
                                      "Could not handle start/stop for iis site {Site}",
                                      deploymentExecutionDefinition.IisSiteName);

                        return(ExitCode.Failure);
                    }

                    _logger.Information("Summary: {Summary}", summary.ToDisplayValue());
                }
コード例 #23
0
 public List <MayBe> ThanhPhamS()
 {
     return(MayBe.DocTatCa());
 }