Programmatically Get Multi Variate Test Datasource Items of a Sitecore Item

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

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

private static List<Item> GetMultiVariateTestDataSourceItems(this RenderingReference reference)
{
List<Item> list = new List<Item>();
if (reference != null && !string.IsNullOrEmpty(reference.Settings.MultiVariateTest))
{
using (new SecurityDisabler())
{
var mvVariateTestForLang = Sitecore.Analytics.Testing.TestingUtils.TestingUtil.MultiVariateTesting.GetVariableItem(reference);
//var mvVariateTestForLang = reference.Settings.GetMultiVariateTestForLanguage(Sitecore.Context.Language); // < Sitecore 7.5
Sitecore.Data.Items.Item variableItem = null;

if (mvVariateTestForLang != null)
{
variableItem = mvVariateTestForLang.InnerItem;
//variableItem = reference.Database.GetItem(mvVariateTestForLang); // < Sitecore 7.5
}

if (variableItem != null)
{
foreach (Item mvChild in variableItem.Children)
{
var mvDataSourceItem = mvChild.GetInternalLinkFieldItem("Datasource");
if (mvDataSourceItem != null)
{
list.Add(mvDataSourceItem);
}
}
}
}
}
return list;
}

public static Item GetInternalLinkFieldItem(this Item i, string internalLinkFieldName)
{
if (i != null)
{
InternalLinkField ilf = i.Fields[internalLinkFieldName];
if (ilf != null && ilf.TargetItem != null)
{
return ilf.TargetItem;
}
}
return null;
}
[/code]

This code shown is for Sitecore 7.5 and above while the commented out lines are for versions of Sitecore below 7.5. Now that we have these extension methods, we are able to write some nice code like this:

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

2 thoughts on “Programmatically Get Multi Variate Test Datasource Items of a Sitecore Item

Add yours

Leave a Reply

Powered by WordPress.com.

Up ↑

%d bloggers like this: