Skip to content

Instantly share code, notes, and snippets.

@torleifhalseth
Last active August 29, 2015 14:21
Show Gist options
  • Save torleifhalseth/9c3045fb89ce923d76d0 to your computer and use it in GitHub Desktop.
Save torleifhalseth/9c3045fb89ce923d76d0 to your computer and use it in GitHub Desktop.
Provides a unified way of converting picked relation nodes as a specified type.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using nuPickers;
using Our.Umbraco.Ditto;
namespace MyProject.TypeConverters
{
/// <summary>
/// Provides a unified way of converting picked relation nodes as a specified type.
/// </summary>
/// <typeparam name="T">The <see cref="Type" /> of the object to return.</typeparam>
public class RelationConverter<T> : TypeConverter where T : class
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="type">The type.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type type)
{
return type == typeof(Picker);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param>
/// <param name="value">The <see cref="T:System.Object" /> to convert.</param>
/// <returns>
/// An <see cref="T:System.Object" /> that represents the converted value.
/// </returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null) return null;
var picker = (Picker)value;
var nodes = picker.AsPublishedContent().ToList();
if (!nodes.Any()) return null;
var objects = nodes.Select(x => x.As<T>()).ToList();
return objects;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment