Skip to content

Instantly share code, notes, and snippets.

@AThraen
Last active March 7, 2025 12:31
Show Gist options
  • Select an option

  • Save AThraen/f3a6d6e91e9d3b07c3dd13aa1253751e to your computer and use it in GitHub Desktop.

Select an option

Save AThraen/f3a6d6e91e9d3b07c3dd13aa1253751e to your computer and use it in GitHub Desktop.
Optimizely CMS - Extension methods for Listing content used on a page and visitor groups used in content
using EPiServer;
using EPiServer.Core;
using EPiServer.Personalization.VisitorGroups;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodeArt.Optimizely.Extensions
{
public static class UsefulExtensions.cs
{
///<summary>
/// Lists all content (typically blocks) used in content areas and xhtmlstrings on a content item, recursively (blocks in blocks, etc)
///</summary>
public static IEnumerable<IContent> FetchReferencedContentRecursively(this IContentRepository repo, IContent c)
{
yield return c;
foreach (var p in c.Property)
{
if (p.Value == null) continue;
if (p.PropertyValueType == typeof(ContentArea))
{
var ca = p.Value as ContentArea;
if (ca == null) continue;
foreach (var f in ca.Items)
{
foreach (var y in repo.FetchReferencedContentRecursively(repo.Get<IContent>(f.ContentLink)))
yield return y;
}
}
else if (p.PropertyValueType == typeof(XhtmlString))
{
var ca = p.Value as XhtmlString;
if (ca == null) continue;
foreach (var f in ca.Fragments.Where(fr => fr is EPiServer.Core.Html.StringParsing.ContentFragment))
{
var j = f as EPiServer.Core.Html.StringParsing.ContentFragment;
foreach (var y in repo.FetchReferencedContentRecursively(repo.Get<IContent>(j.ContentLink)))
yield return y;
}
}
}
}
/// <summary>
/// Analyzes which visitor groups are used in an IContent and returns a list of those groups.
/// </summary>
public static IEnumerable<VisitorGroup> ExtractVisitorGroups(this IVisitorGroupRepository vgRepo,IContent c)
{
foreach (var p in c.Property)
{
if (p.Value == null) continue;
if (p.PropertyValueType == typeof(ContentArea))
{
var ca = p.Value as ContentArea;
if (ca == null) continue;
foreach (var f in ca.Items.Where(l => l.AllowedRoles != null && l.AllowedRoles.Any()))
{
//Match! This page uses the visitor groups in l.AllowedRoles. Record.
foreach (var r in f.AllowedRoles)
{
yield return vgRepo.Load(Guid.Parse(r));
}
}
}
else if (p.PropertyValueType == typeof(XhtmlString))
{
var ca = p.Value as XhtmlString;
if (ca == null) continue;
foreach (var f in ca.Fragments.Where(fr => fr is EPiServer.Core.Html.StringParsing.PersonalizedContentFragment))
{
var j = f as EPiServer.Core.Html.StringParsing.PersonalizedContentFragment;
var roles = j.GetRoles();
foreach (var r in roles)
{
yield return vgRepo.Load(Guid.Parse(r));
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment