Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example Episerver job for block property migration
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAccess;
using EPiServer.PlugIn;
using EPiServer.Scheduler;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using Website.Models.Blocks;
namespace Website.Business.Jobs
{
[ScheduledPlugIn(DisplayName = "[Migration] External hero panel overlay", SortIndex = 999999992)]
public class MigrateHeroPanelOverlayJob : ScheduledJobBase
{
private IContentRepository _cms;
private IContentVersionRepository _vers;
public override string Execute()
{
_cms = ServiceLocator.Current.GetInstance<IContentRepository>();
_vers = ServiceLocator.Current.GetInstance<IContentVersionRepository>();
var links = _cms.GetDescendents(ContentReference.RootPage)
.Union(_cms.GetDescendents(SiteDefinition.Current.GlobalAssetsRoot));
var foundCount = 0;
var updatedCount = 0;
var errors = new List<string>();
var found = new List<string>();
foreach (var link in links)
{
var langs = _vers.ListPublished(link).GroupBy(v => v.LanguageBranch).Select(g => g.First().LanguageBranch).ToList();
foreach (var lang in langs)
{
ContentData item;
try
{
item = _cms.Get<ContentData>(link, CultureInfo.GetCultureInfo(lang));
}
catch (Exception ex)
{
errors.Add($"[{link.ID}]: {ex.Message}");
continue;
}
if (item is HeroPanelBlock && ((HeroPanelBlock) item).HideOverlay && ((HeroPanelBlock) item).Overlay != "no-overlay")
{
++foundCount;
var writable = (HeroPanelBlock) item.CreateWritableClone();
found.Add($"[{writable.GetId()}] \"{writable.GetName()}\"");
try
{
writable.Overlay = "no-overlay";
}
catch (Exception ex)
{
errors.Add($"[{writable.GetId()}] \"{writable.GetName()}\": {ex.Message}");
continue;
}
_cms.Save((IContent) writable, SaveAction.Publish);
++updatedCount;
}
}
}
var result = $"{foundCount} blocks found, {updatedCount} updated.";
if (found.Any())
{
var br = "<br>";
var foundResult = new StringBuilder();
foundResult.Append("Found:" + br);
foreach (var fb in found)
{
foundResult.Append(fb + br);
}
result += " " + foundResult;
}
if (errors.Any())
{
var br = "<br>";
var errorResult = new StringBuilder();
errorResult.Append("Errors:" + br);
foreach (var error in errors)
{
errorResult.Append(error + br);
}
result += " " + errorResult;
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment