Last active
November 12, 2018 13:48
-
-
Save sebastiantecsi/6ae037587e8a688e6820f1aead5e59de to your computer and use it in GitHub Desktop.
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
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