Created
July 3, 2018 20:39
-
-
Save jraps20/f69d33a29dc681b8157c8c2b32fc3f26 to your computer and use it in GitHub Desktop.
Delete Sitecore items from remote databases when delete occurs in master.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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