Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hermanussen/e0fabeb27b3acaa2539649199bc875b1 to your computer and use it in GitHub Desktop.
Save hermanussen/e0fabeb27b3acaa2539649199bc875b1 to your computer and use it in GitHub Desktop.
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using Sitecore.Collections;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Mvc.Helpers;
using UnitTestingDemo.Website.Domain;
namespace UnitTestingDemo.Website.Util
{
public static class SitecoreHelperExtensions
{
private static readonly Regex ConstNameReplace = new Regex("([A-Z]+[a-z]+)", RegexOptions.Compiled);
/// <summary>
/// Render a field by passing an expression that references a CDM class object property.
/// Using this method ensures typesafe access and preserves web edit functionality.
/// </summary>
/// <param name="sitecoreHelper"></param>
/// <param name="value">An expression that references a CDM class object property</param>
/// <param name="disableWebEdit"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static HtmlString Field(
this SitecoreHelper sitecoreHelper,
Expression<Func<object>> value,
bool disableWebEdit = false,
SafeDictionary<string> parameters = null)
{
if (parameters == null)
{
parameters = new SafeDictionary<string>();
}
var fieldParams = ParamsFor(value);
if (fieldParams == null || ! fieldParams.HasValue)
{
return null;
}
HtmlString result = sitecoreHelper.Field(fieldParams.FieldName, fieldParams.Item, new
{
DisableWebEdit = disableWebEdit, Parameters = parameters
});
return result;
}
private static FieldRendererParams ParamsFor(Expression<Func<object>> func)
{
// strip unary expression if needed, like boxing conversion for value types
Expression valueExpr = func.Body;
var unaryExpression = valueExpr as UnaryExpression;
if (unaryExpression != null)
{
valueExpr = unaryExpression.Operand;
}
var memberExpression = valueExpr as MemberExpression;
Assert.IsNotNull(memberExpression, "Please enter a valid member expression for CdmFieldRenderer that evalutes to a CDM property");
if (memberExpression != null && memberExpression.Expression != null)
{
// get the name of the property in the CDM class
string propertyName = memberExpression.Member.Name;
// get the itemwrapper by invoking the contained expression
Delegate compiledExpr = Expression.Lambda(memberExpression.Expression).Compile();
var itemWrapper = compiledExpr.DynamicInvoke() as IItemWrapper;
if (!string.IsNullOrEmpty(propertyName) && itemWrapper != null)
{
// attempt to determine the name of the constant that holds the field name
string constantName = ConstNameReplace.Replace(propertyName, m => (m.Value.Length > 3 ? m.Value : m.Value.ToLower()) + "_");
constantName = string.Format("FIELD_{0}", constantName).ToUpperInvariant();
if (constantName.LastIndexOf("_", StringComparison.Ordinal) > -1)
constantName = constantName.Remove(constantName.LastIndexOf("_", StringComparison.Ordinal), 1);
FieldInfo constant = itemWrapper.GetType().GetField(constantName, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
if (constant != null)
{
// set the correct values on the control, so the field can be rendered and is compatible with the page editor
return new FieldRendererParams
{
Item = itemWrapper.Item,
FieldName = constant.GetValue(null) as string
};
}
throw new Exception(string.Format("Unable to reflect field-property '{0}' for propertyname '{1}'", constantName, propertyName));
}
}
return new FieldRendererParams();
}
#region Nested type: FieldRendererParams
public class FieldRendererParams
{
public Item Item { get; set; }
public string FieldName { get; set; }
public bool HasValue
{
get
{
if (Item == null || string.IsNullOrEmpty(FieldName))
return false;
return !string.IsNullOrEmpty(Item[FieldName]);
}
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment