Programmatically Get Personalization Datasource Items of a Sitecore Item

In the previous blog post, Programmatically Get Datasource Items of a Sitecore Item we learned how to get the datasource items from the rendering references. This does not include the items that have been added through personalization and rules. By adding the following methods to our previous post, we can get those items.

[code language=”csharp”]
public static List<Item> GetPersonalizationDataSourceItems(this Item i)
{
List<Item> list = new List<Item>();
foreach (RenderingReference reference in i.GetRenderingReferences())
{
list.AddRange(reference.GetPersonalizationDataSourceItem());
}
return list;
}

private static List<Item> GetPersonalizationDataSourceItem(this RenderingReference reference)
{
List<Item> list = new List<Item>();
if (reference != null && reference.Settings.Rules != null && reference.Settings.Rules.Count > 0)
{
foreach (var r in reference.Settings.Rules.Rules)
{
foreach (var a in r.Actions)
{
var setDataSourceAction = a as Sitecore.Rules.ConditionalRenderings.SetDataSourceAction<Sitecore.Rules.ConditionalRenderings.ConditionalRenderingsRuleContext>;
if (setDataSourceAction != null)
{
Item dataSourceItem = GetDataSourceItem(setDataSourceAction.DataSource, reference.Database);
if (dataSourceItem != null)
{
list.Add(dataSourceItem);
}
}
}
}
}
return list;
}
[/code]

This code loops through the rules of your personalized component and if the action is Sitecore.Rules.ConditionalRenderings.SetDataSourceAction, then we know that this will be one of the personalization items. Next we can write some nice code like this:

[code language=”csharp”]
foreach (Item personalizationItem in Sitecore.Context.Item.GetPersonalizationDataSourceItems())
{
// do something
}
[/code]

Please see the next blog post in this series: Programmatically Get Multi Variate Test Datasource Items of a Sitecore Item