Skip to content

Instantly share code, notes, and snippets.

@TimGeyssens
Created August 21, 2020 07:33
Show Gist options
  • Save TimGeyssens/c1b287d91c76650c77efa9c657eb758b to your computer and use it in GitHub Desktop.
Save TimGeyssens/c1b287d91c76650c77efa9c657eb758b to your computer and use it in GitHub Desktop.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySite.Models.PropEditors;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
namespace MySite.Custom
{
public class MatrixValueConverter : IPropertyValueConverter
{
public bool IsConverter(IPublishedPropertyType propertyType)
{
return propertyType.EditorAlias.Equals("Custom.PropEditor");
}
public Type GetPropertyValueType(IPublishedPropertyType propertyType)
{
return typeof(Matrix);
}
public PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
{
return PropertyCacheLevel.Element;
}
public object ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return null;
var sourceString = source.ToString();
if (sourceString.DetectIsJson())
{
try
{
var obj = JsonConvert.DeserializeObject<string[][]>(sourceString);
var matrix = new Matrix();
var rows = obj.Select(r => new Row { Cols = r.ToList()});
matrix.Rows = rows;
return matrix;
}
catch (Exception ex)
{
return null;
}
}
return null;
}
public bool? IsValue(object value, PropertyValueLevel level)
{
switch (level)
{
case PropertyValueLevel.Source:
return value != null;
default:
throw new NotSupportedException($"Invalid level: {level}.");
}
}
public object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
{
if (inter == null)
return null;
if (propertyType.Alias != null)
{
Matrix data;
if (inter is Matrix)
{
data = (Matrix)inter;
if (data != null)
return data;
}
}
return inter;
}
public object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment