Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete Sitecore items from remote databases when delete occurs in master.
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<events>
<event name="item:deleting">
<handler type="MyProject.MyNamespace.RemoteDeleteHandler, MyProject" method="OnItemDeleting" />
</event>
</events>
</sitecore>
</configuration>
public class RemoteDeleteHandler
{
protected void OnItemDeleting(object sender, EventArgs args)
{
if (!(Event.ExtractParameter(args, 0) is Item deletedItem))
return;
if (deletedItem.ID == (ID)null || deletedItem.ID == ID.Null)
return;
if (!string.Equals(deletedItem.Database.Name, "master", StringComparison.InvariantCultureIgnoreCase))
return;
var targetDatabases = GetTargetDatabases(deletedItem.Database);
DeleteRemoteItems(deletedItem, targetDatabases);
}
private static void DeleteRemoteItems(Item item, IEnumerable<Database> targetDatabases)
{
if (item.ParentID == (ID)null || item.ParentID == ID.Null)
return;
var deletedItemRemoteEvent = new DeletedItemRemoteEvent(item, item.ParentID);
foreach (var targetDatabase in targetDatabases)
{
var remoteItem = targetDatabase.GetItem(item.ID);
// item does not exist in target database
if (remoteItem == null)
continue;
remoteItem.Delete();
targetDatabase.RemoteEvents.Queue.QueueEvent(deletedItemRemoteEvent, true, true);
}
}
private static IEnumerable<Database> GetTargetDatabases(Database contextDatabase)
{
Assert.ArgumentNotNull(contextDatabase, nameof(contextDatabase));
var factoryDatabases = Factory.GetDatabases()
.Where(db => !string.Equals(db.Name, Sitecore.Constants.CoreDatabaseName, StringComparison.InvariantCultureIgnoreCase))
.Where(db => !string.Equals(db.Name, contextDatabase.Name, StringComparison.InvariantCultureIgnoreCase))
.Where(db => db.HasContentItem);
return factoryDatabases.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment