KennyG
Jan 18, 2021
  1689
(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
Copy Optimizely SaaS CMS Settings to ENV Format Via Bookmarklet

Do you work with multiple Optimizely SaaS CMS instances? Use a bookmarklet to automatically copy them to your clipboard, ready to paste into your e...

Daniel Isaacs | Dec 22, 2024 | Syndicated blog

Increase timeout for long running SQL queries using SQL addon

Learn how to increase the timeout for long running SQL queries using the SQL addon.

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Overriding the help text for the Name property in Optimizely CMS

I recently received a question about how to override the Help text for the built-in Name property in Optimizely CMS, so I decided to document my...

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Resize Images on the Fly with Optimizely DXP's New CDN Feature

With the latest release, you can now resize images on demand using the Content Delivery Network (CDN). This means no more storing multiple versions...

Satata Satez | Dec 19, 2024