SaaS CMS has officially launched! Learn more now.

KennyG
Jan 18, 2021
  1600
(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 SaaS CMS Concepts and Terminologies

Whether you're a new user of Optimizely CMS or a veteran who have been through the evolution of it, the SaaS CMS is bringing some new concepts and...

Patrick Lam | Jul 15, 2024

How to have a link plugin with extra link id attribute in TinyMce

Introduce Optimizely CMS Editing is using TinyMce for editing rich-text content. We need to use this control a lot in CMS site for kind of WYSWYG...

Binh Nguyen Thi | Jul 13, 2024

Create your first demo site with Optimizely SaaS/Visual Builder

Hello everyone, We are very excited about the launch of our SaaS CMS and the new Visual Builder that comes with it. Since it is the first time you'...

Patrick Lam | Jul 11, 2024

Integrate a CMP workflow step with CMS

As you might know Optimizely has an integration where you can create and edit pages in the CMS directly from the CMP. One of the benefits of this i...

Marcus Hoffmann | Jul 10, 2024