// Remove Personalization Rules in Bulk and Update Data-Source
// Default device from Sitecore
var deviceItem = db.GetItem("{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}");
DeviceItem device = new DeviceItem(deviceItem);
//Iterate through all the items
foreach (Item childItem in parent.Axes.GetDescendants())
{
if (childItem.Fields != null && childItem.Fields["__Renderings"] != null && childItem.Fields["__Renderings"].ToString() != string.Empty)
{
// Get the rendering where personalization is needed to be removed.
var renderings = childItem.Visualization.GetRenderings(device, true).Where(r => r.RenderingID == Sitecore.Data.ID.Parse(txtRenderingID.Text)).ToArray();
if (renderings.Count() == 0)
{
string log = "Item not updated: " + childItem.Paths.Path + ", Info: Rendering with ID " + txtRenderingID.Text + " not found in the item presentation!";
Sitecore.Diagnostics.Log.Info(log, this);
continue;
}
// Get the layout definitions and the device
Sitecore.Data.Fields.LayoutField layoutField = new Sitecore.Data.Fields.LayoutField(childItem.Fields[Sitecore.FieldIDs.LayoutField]);
if (!string.IsNullOrEmpty(layoutField.Value))
{
Sitecore.Layouts.LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(layoutField.Value);
Sitecore.Layouts.DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(device.ID.ToString());
var renderingItem = deviceDefinition.GetRendering(renderingID);
if (renderingItem != null)
{
// Remove all the personalization rules
renderingItem.Rules.RemoveAll();
// Update the renderings datasource value
renderingItem.Datasource = txtNewDataSourceID.Text;
// Save the layout changes
childItem.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
childItem.Editing.EndEdit();
}
}
}
}