Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections;
using System.Collections.Generic;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Events;
using Sitecore.Publishing;
using Sitecore.SecurityModel;
namespace Sitecore.Sandbox.Handlers
{
public class AutoPublisherHandler
{
/// <summary>
/// OnItemDeleted handler.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void OnItemDeleted(object sender, EventArgs args)
{
//This handler publishes the parent of the deleted item with his descendants of a deleted item.
if (Context.IsBackgroundThread) return;
try
{
//extract the deleted item, and then extract his parent
var idParent = Event.ExtractParameter(args, 1) as ID;
var parent = Database.GetDatabase("master").GetItem(idParent);
var dataItem = parent;
//fetch the target databases
foreach (Database database in GetTargets(dataItem))
{
//publish the parrent for each database
var options = new PublishOptions(dataItem.Database, database, PublishMode.SingleItem, dataItem.Language, DateTime.Now)
{RootItem = dataItem, Deep = true};
new Publisher(options).PublishAsync();
}
}
catch (Exception ex)
{
Log.Error(ex.Message, this);
}
}
/// <summary>
/// Gets the targets.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The targets.</returns>
private IEnumerable<Database> GetTargets(Item item)
{
using (new SecurityDisabler())
{
Item targets = item.Database.Items["/sitecore/system/publishing targets"];
if (targets != null)
{
var list = new ArrayList();
foreach (Item target in targets.Children)
{
string name = target["Target database"];
if (name.Length > 0)
{
Database database = Factory.GetDatabase(name, false);
if (database != null)
{
list.Add(database);
}
else
{
Log.Warn("Unknown database in AutoPublisherHandler: " + name, this);
}
}
}
return (list.ToArray(typeof (Database)) as Database[]);
}
}
return new Database[0];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment