KennyG
Jan 18, 2021
  1644
(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
Optimizely Forms: You cannot submit this form because an administrator has turned off data storage.

Do not let this error message scare you, the solution is quite simple!

Tomas Hensrud Gulla | Oct 4, 2024 | Syndicated blog

Add your own tools to the Optimizely CMS 12 admin menu

The menus in Optimizely CMS can be extended using a MenuProvider, and using the path parameter you decide what menu you want to add additional menu...

Tomas Hensrud Gulla | Oct 3, 2024 | Syndicated blog

Integrating Optimizely DAM with Your Website

This article is the second in a series about integrating Optimizely DAM with websites. It discusses how to install the necessary package and code t...

Andrew Markham | Sep 28, 2024 | Syndicated blog

Opticon 2024 - highlights

I went to Opticon in Stockholm and here are my brief highlights based on the demos, presentations and roadmaps  Optimizely CMS SaaS will start to...

Daniel Ovaska | Sep 27, 2024

Required fields support in Optimizely Graph

It's been possible to have "required" properties (value must be entered) in the CMS for a long time. The required metadata haven't been reflected i...

Jonas Bergqvist | Sep 25, 2024

How to write a bespoke notification management system

Websites can be the perfect vehicle for notifying customers of important information quickly, whether it’s the latest offer, an operational message...

Nicole Drath | Sep 25, 2024