Files
raven/server/AyaNova/util/ImportUtil.cs

69 lines
2.5 KiB
C#

using System;
using System.Reflection;
using System.Collections.Generic;
namespace AyaNova.Util
{
internal static class ImportUtil
{
/// <summary>
/// Copies the data of one object to another. The target object 'pulls' properties of the first.
/// Any matching properties are written to the target.
///
/// The object copy is a shallow copy only. Any nested types will be copied as
/// whole values rather than individual property assignments (ie. via assignment)
/// </summary>
/// <param name="source">The source object to copy from</param>
/// <param name="target">The object to copy to</param>
/// <param name="propertiesToUpdate">A list of properties that should be copied</param>
public static void Update(object source, object target, List<string> propertiesToUpdate)
{
MemberInfo[] miT = target.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (MemberInfo Field in miT)
{
string name = Field.Name;
// Skip over any property exceptions
if (!propertiesToUpdate.Contains(name))
continue;
if (Field.MemberType == MemberTypes.Field)
{
FieldInfo SourceField = source.GetType().GetField(name);
if (SourceField == null)
continue;
object SourceValue = SourceField.GetValue(source);
((FieldInfo)Field).SetValue(target, SourceValue);
}
else if (Field.MemberType == MemberTypes.Property)
{
PropertyInfo piTarget = Field as PropertyInfo;
PropertyInfo SourceField = source.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (SourceField == null)
continue;
if (piTarget.CanWrite && SourceField.CanRead)
{
object SourceValue = SourceField.GetValue(source, null);
piTarget.SetValue(target, SourceValue, null);
}
}
}
}
public static string GetImportTag()
{
return "zz-import-" + DateTime.Now.ToString("yyyyMMddHHmmss");
}
}//eoc
}//eons