using System;
using System.Text;
using System.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Dynamic;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Collections;
namespace EasyDevCore.Common
{
///
/// Helper for convert string to/from type
///
public static class ConvertHelper
{
///
/// Hexes to byte.
///
/// The hex string.
///
public static byte[] HexToByte(this string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
///
/// Changes the type.
///
/// The value.
/// Type of the conversion.
///
public static object ChangeType(this object value, Type conversionType)
{
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null || value == DBNull.Value)
{
return null;
}
else
{
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
}
if (typeof(Enum).IsAssignableFrom(conversionType))
{
return Enum.GetName(value.GetType(), value);
}
return Convert.ChangeType(value, conversionType);
}
///
/// To the dynamic.
///
/// The value.
///
public static dynamic ToDynamic(this object value)
{
return TypeDescriptor.GetProperties(value.GetType()).OfType().Aggregate(new ExpandoObject() as IDictionary,
(a, p) => { a.Add(p.Name, p.GetValue(value)); return a; });
}
///
/// Extension method that turns a dictionary of string and object to an ExpandoObject
///
public static ExpandoObject ToExpando(this IDictionary dictionary)
{
var expando = new ExpandoObject();
var expandoDic = expando as IDictionary;
// go through the items in the dictionary and copy over the key value pairs)
foreach (var kvp in dictionary)
{
// if the value can also be turned into an ExpandoObject, then do it!
if (kvp.Value is IDictionary)
{
var expandoValue = ((IDictionary)kvp.Value).ToExpando();
expandoDic.Add(kvp.Key, expandoValue);
}
else if (kvp.Value is ICollection)
{
// iterate through the collection and convert any strin-object dictionaries
// along the way into expando objects
var itemList = new List