Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

KennyG
Jan 18, 2021
  1554
(0 votes)

Self-adjusting the SiteDefinition after automated Copydown

Needing to keep the data in your DXP environments in sync? Automate it!

We have a PowerShell script that runs in our Azure DevOps instance that will copy the database and BLOBs down from PROD to the lower environments using the Deployment API. This can be run on a regular schedule.

$key = "$(ClientKey)"
$secret = "$(ClientSecret)"
$projectid = "$(ProjectId)"

if (-not (Get-Module -Name EpiCloud -ListAvailable)) {
    Install-Module EpiCloud -Scope CurrentUser -Force
}
Connect-EpiCloud -ClientKey $key -ClientSecret $secret  -ProjectId $projectid
Start-EpiDeployment -SourceEnvironment Production -TargetEnvironment Preproduction -IncludeBlob -IncludeDb -ShowProgress
Write-Host "Content Sync Finished"

The problem was that we needed to go in and correct the site definition for the current environment once this had completed. 

Luckily the SiteDefinitionRepository gives us what we need. 

First thing we store a setting for each environment in the proper web.config. These can be set using web.config transforms.

<add key="env" value="INTE" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />

Then just to keep things tidy we store the environment URLs in a Constants file.

    public class EnvironmentUrls
    {
        public const string DEV = "http://localhost:xxx/";
        public const string INTE = "https://integ.xxx.com/";
        public const string PREP = "https://prep.xxx.com/";
        public const string PROD = "https://www.xxx.com/";
    }

Next, we add an initialization module that checks the environment app setting to determine which environment the code is running in and self-adjust.

We get the current environment from the web.config.

string environment = System.Web.Configuration.WebConfigurationManager.AppSettings["env"];

We use the SiteDefinitionRepository to find what is currently set.

            var siteDefinitionRepository = ServiceLocator.Current.GetInstance<ISiteDefinitionRepository>();
            var currentDefinition = SiteDefinition.Current;
            string currentSiteUrl = currentDefinition.SiteUrl.ToString();

If they don't match we create a writeable clone of the definition, loop through the Hosts setting the correct Url as Primary, reset all others to Undefined, and Save.

(Site URLs for each environment are already present in the Manage Websites section in PROD so they are available here after the DB copydown.) 

            if (!environmentUrl.Equals(currentSiteUrl))
            {
                var newDefinition = currentDefinition.CreateWritableClone();
                newDefinition.SiteUrl = new Uri(environmentUrl);
                foreach (var host in newDefinition.Hosts)
                {
                    if (host.Url != null && environmentUrl.Equals(host.Url.ToString()))
                    {
                        host.Type = HostDefinitionType.Primary;
                    }
                    else if (host.Url != null && host.Type == HostDefinitionType.Primary)
                    {
                        host.Type = HostDefinitionType.Undefined;
                    }
                }
                siteDefinitionRepository.Save(newDefinition);
            }

Here is the complete code.

using System;
using System.Linq;
using Website.Constants;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace Website.Business.Initialization
{
    [InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class CopyDownInitialization : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            string environment = System.Web.Configuration.WebConfigurationManager.AppSettings["env"];
            switch (environment)
            {
                case "DEV":
                    ConfirmSiteConfig(EnvironmentUrls.DEV);
                    break;
                case "INTE":
                    ConfirmSiteConfig(EnvironmentUrls.INTE);
                    break;
                case "PREP":
                    ConfirmSiteConfig(EnvironmentUrls.PREP);
                    break;
                default:
                    break;
            }
        }
        private void ConfirmSiteConfig(string environmentUrl)
        {
            var siteDefinitionRepository = ServiceLocator.Current.GetInstance<ISiteDefinitionRepository>();
            var currentDefinition = SiteDefinition.Current;
            string currentSiteUrl = currentDefinition.SiteUrl.ToString();
            if (!environmentUrl.Equals(currentSiteUrl))
            {
                var newDefinition = currentDefinition.CreateWritableClone();
                newDefinition.SiteUrl = new Uri(environmentUrl);
                foreach (var host in newDefinition.Hosts)
                {
                    if (host.Url != null && environmentUrl.Equals(host.Url.ToString()))
                    {
                        host.Type = HostDefinitionType.Primary;
                    }
                    else if (host.Url != null && host.Type == HostDefinitionType.Primary)
                    {
                        host.Type = HostDefinitionType.Undefined;
                    }
                }
                siteDefinitionRepository.Save(newDefinition);
            }
        }
        public void Uninitialize(InitializationEngine context)
        {
        }
    }
}

Next, I would love to find a way to automate flushing the Cloudflare cache after the copydown!

Jan 18, 2021

Comments

Please login to comment.
Latest blogs
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog