Skip to content

Instantly share code, notes, and snippets.

@tater9104
Last active January 16, 2023 00:55
Show Gist options
  • Save tater9104/2268310 to your computer and use it in GitHub Desktop.
Save tater9104/2268310 to your computer and use it in GitHub Desktop.
A list of a few extension methods that I often use when working with massive.
public static class MassiveExtensions
{
// Extension method that coverts an concrete object to a dynamic object. When using massive, this is helpful
// to auto-convert concrete objects while skipping over key fields that would otherwise throw an
// error (such as ID's)
public static dynamic ToExpando(this object o, params string[] propertiesToIgnore)
{
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{
var nv = (NameValueCollection)o;
nv.Cast<string>().Where(x => !propertiesToIgnore.Contains(x))
.Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
}
else
{
var props = o.GetType().GetProperties();
foreach (var item in props)
{
if (!propertiesToIgnore.Contains(item.Name))
{
d.Add(item.Name, item.GetValue(o, null));
}
}
}
return result;
}
// Maps the properties of a dynamic object to a concrete class. When using this, you will need to cast the
// dynamic object to a ExpandoObject explicitly.
public static T ToConcrete<T>(this ExpandoObject dynObject)
{
T instance = Activator.CreateInstance<T>();
var dict = dynObject as IDictionary<string, object>;
PropertyInfo[] targetProperties = instance.GetType().GetProperties();
//If the provided object is null, return null.
if (dict == null) return default(T);
foreach (PropertyInfo property in targetProperties)
{
object propVal;
if (dict.TryGetValue(property.Name, out propVal))
{
if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
{
if (propVal == null) property.SetValue(instance, new DateTime?(), null);
else property.SetValue(instance, DateTime.Parse(propVal.ToString()), null);
}
else
{
property.SetValue(instance, propVal, null);
}
}
}
return instance;
}
// Maps the properties of an IEnumberable<dynamic> to a List<T> of a concrete class. When using this, you will need to cast
// the dynamic object to IEnumberable<dynamic> explicity.
public static List<T> ToConcrete<T>(this IEnumerable<dynamic> dynObjects)
{
var returnList = new List<T>();
foreach (ExpandoObject item in dynObjects)
{
returnList.Add(item.ToConcrete<T>());
}
return returnList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment