Comparing draft content to published content
We had a situation arise the other day where we needed to compare some values in a draft page against the currently published version. Based on some fields changing we knew we needed to reindex a list of related pages.
This all takes place in the IContentEvents PublishingContent event handler which has been wired up in an InitializationModule.
The trick here is to cast e.Content to get the current draft and to use e.ContentLink.ToReferenceWithoutVersion to get the published version so that you can compare.
Here is a code sample that checks for a change to the Name and logs it.
using System; using System.Linq; using EPiServer; using EPiServer.Core; using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.ServiceLocation; using EPiServer.Logging; [InitializableModule] [ModuleDependency(typeof(EPiServer.Web.InitializationModule))] public class PageDataUpdatedInitialization : IInitializableModule { private static readonly ILogger Logger = LogManager.GetLogger(); private InjectedcontentLoader; public void Initialize(InitializationEngine context) { var events = context.Locate.ContentEvents(); events.PublishingContent += this.PublishingContent; } private void PublishingContent(object sender, ContentEventArgs e) { var newPageData = e.Content as PageData; if (newPageData == null) return; var oldPageData = contentLoader.Service?.Get (e.ContentLink.ToReferenceWithoutVersion()); if (oldPageData == null) return; // check to see whether any updates were made to the specific value if (!ValueChanged(oldPageData, newPageData)) return; // if so, do something Logger.Debug("Value has changed from {0} to {1}", oldPageData.Name, newPageData.Name); } private static bool ValueChanged(PageData oldPageData, PageData newPageData) { var oldName = oldPageData.Name; var newName = newPageData.Name; if (newName != oldName) { return true; } return false; } public void Uninitialize(InitializationEngine context) { //Add uninitialization logic } }
just a couple of my humble cents here:
Also I would encourage you to take a look at brilliant way to handle Episerver events differently - http://marisks.net/2017/02/12/better-event-handling-in-episerver/
Thanks for the feedback Valdis!