CodeLiturgy.Dashboard/BlueWest/Core/Tests/MappingExtensions.cs

66 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using BlueWest.Core.Tests;
using BlueWest.DataAgent;
namespace BlueWest.Core
{
public static class MappingExtensions
{
private static Type _currentType = null;
private static bool IsMatchingProperty(ref Type type, string propertyName)
{
var typeProperties = type.GetProperties();
foreach (var propertyInfo in typeProperties)
{
if (propertyInfo.Name == propertyName) return true;
}
return false;
}
private static dynamic DictionaryToObject(IDictionary<String, Object> dictionary)
{
var expandoObj = new ExpandoObject();
var expandoObjCollection = (ICollection<KeyValuePair<String, Object>>)expandoObj;
foreach (var keyValuePair in dictionary)
{
expandoObjCollection.Add(keyValuePair);
}
dynamic eoDynamic = expandoObj;
return eoDynamic;
}
private static T DictionaryToObject<T>(IDictionary<String, Object> dictionary) where T : class
{
var dicToObj = DictionaryToObject(dictionary);
return dicToObj as T;
}
public static T ToDto<T>(this object obj) where T: class
{
var objDic = obj.ToDictionary();
var t = typeof(T);
var dataInstance = Activator.CreateInstance<T>();
foreach (var property in t.GetProperties())
{
if (objDic.ContainsKey(property.Name))
{
property.SetValue(dataInstance, objDic[property.Name]);
}
}
return dataInstance;
}
}
}