Object Auditing using reflection - c#

its me again! :)
I've been tasked with creating a system to auditing out internal objects, my first iteration was no flexible and very slow so I'm hoping to rewrite it and really make it work how it should.
Performance for this needs to be as perfect as possible, the auditing code is probably going to be run on every object in our system when they are saved..
This code below is what I've done so far - I've profiled it using the visual studio tools and I think I've remove quite a few possible performance hits along the way..
What I really want from you guys is to review this and suggest any possible improvements, Its also worth nothing that CreateObjectFromHistory method doesn't need to be as performant as the rest, its barely going to ever get called.
Also - they keyvaluepair saving is out of my hands.
Any help would be brilliant..
Cheers :)
//Wall o-code coming up..
public static void AuditObject(ITraceable obj)
{
if (obj == null)
return;
IEnumerable<PropertyInfo> properties = GetPropertyInfo(obj);
List<SerializeableKeyValuePair<string, object>> kvpList =
new List<SerializeableKeyValuePair<string, object>>();
foreach (PropertyInfo property in properties)
{
SerializeableKeyValuePair<string, object> thisValue = new SerializeableKeyValuePair<string, object>();
thisValue.Key = property.Name;
thisValue.Value = GetPropertyValue(obj, property);
if (thisValue.Value != null)
kvpList.Add(thisValue);
}
TestObject o = CreateObjectFromHistory<TestObject>(kvpList);
}
public static T CreateObjectFromHistory<T>(List<SerializeableKeyValuePair<string, object>> history)
where T : class, ITraceable
{
T historicalObject = Activator.CreateInstance<T>();
Dictionary<string, PropertyInfo> propertys = GetPropertysAsDictionary(historicalObject);
foreach (SerializeableKeyValuePair<string, object> kvp in history)
{
if (!propertys.ContainsKey(kvp.Key))
continue;
PropertyInfo prop = propertys[kvp.Key];
if (prop == null)
continue;
var value = CoerceValue(prop.PropertyType, kvp.Value);
prop.SetValue(historicalObject, value, null);
}
return historicalObject;
}
private static object CoerceValue(Type type, object value)
{
if (type == typeof(string))
return value as string;
return null;
}
private static object GetPropertyValue(ITraceable obj, PropertyInfo property)
{
if (property.PropertyType == typeof(string))
return GetProperyValueByType<string>(property.GetValue(obj, null));
else if (property.PropertyType == typeof(DateTime))
return GetProperyValueByType<DateTime>(property.GetValue(obj, null));
return null;
}
private static IEnumerable<PropertyInfo> GetPropertyInfo(ITraceable obj)
{
List<PropertyInfo> properties;
Type objType = obj.GetType();
if (PropertyDictionary.TryGetValue(objType, out properties) == false)
{
properties = obj.GetType().GetProperties(BindingFlags.Public |
BindingFlags.Instance).ToList();
properties.RemoveAll(p => IgnoreProperty(p.GetCustomAttributes(typeof(DoNoTraceAttribute), false)));
PropertyDictionary.Add(objType, properties);
}
return properties;
}
private static Dictionary<string, PropertyInfo> GetPropertysAsDictionary(ITraceable obj)
{
return GetPropertyInfo(obj).ToDictionary(pro => pro.Name);
}
private static object GetProperyValueByType<T>(object value)
{
T actualType = (T)value;
if (actualType.Equals(default(T)))
return default(T);
//this will need further implementation
return (T)value;
}
private static bool IgnoreProperty(IEnumerable<object> p)
{
return p.AsParallel().OfType<DoNoTraceAttribute>().Any();
}
Updated Code;
private static IEnumerable<PropertyInfo> GetPropertyInfo(ITraceable obj)
{
List<PropertyInfo> properties;
Type objType = obj.GetType();
if (PropertyDictionary.TryGetValue(objType, out properties) == false)
{
properties = obj.GetType().GetProperties(BindingFlags.Public |
BindingFlags.Instance).ToList();
properties.RemoveAll(p => Attribute.IsDefined(p, typeof(DoNoTraceAttribute)));
PropertyDictionary.Add(objType, properties);
}
return properties;
}
Do this look better ?

If you use PropertyInfo.GetValue() at runtime, the performance will always be slow. To get good performance (especially for looking at lots of objects) you will need to look at something like ILGenerator or Expression - or you could just use something like FastMember and access the values via prop.Name. I really do not think IgnoreProperty is implemented well - you should just look at Attribute.IsDefined here; no need for LINQ, no need for Parallel, and no need to materialize the attributes.

Related

Reflection: If PropertyInfo implements ICollection [duplicate]

Below is some code I use to get the initial state of all public properties in a class for IsDirty checking.
What's the easiest way to see if a property is IEnumerable?
Cheers,
Berryl
protected virtual Dictionary<string, object> _GetPropertyValues()
{
return _getPublicPropertiesWithSetters()
.ToDictionary(pi => pi.Name, pi => pi.GetValue(this, null));
}
private IEnumerable<PropertyInfo> _getPublicPropertiesWithSetters()
{
return GetType().GetProperties().Where(pi => pi.CanWrite);
}
UPDATE
What I wound up doing was adding a few library extensions as follows
public static bool IsNonStringEnumerable(this PropertyInfo pi) {
return pi != null && pi.PropertyType.IsNonStringEnumerable();
}
public static bool IsNonStringEnumerable(this object instance) {
return instance != null && instance.GetType().IsNonStringEnumerable();
}
public static bool IsNonStringEnumerable(this Type type) {
if (type == null || type == typeof(string))
return false;
return typeof(IEnumerable).IsAssignableFrom(type);
}
if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && prop.PropertyType != typeof(string))
I agree with Fyodor Soikin but the fact that is Enumerable does not mean that is only a Collection since string is also Enumerable and returns the characters one by one...
So i suggest using
if (typeof(ICollection<>).IsAssignableFrom(pi.PropertyType))
Try
private bool IsEnumerable(PropertyInfo pi)
{
return pi.PropertyType.IsSubclassOf(typeof(IEnumerable));
}
You can also use "pattern matching". This works for both List<T> and IEnumerable<T>.
private void OutputPropertyValues(object obj)
{
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
if (property.GetValue(obj, null) is ICollection items)
{
_output.WriteLine($" {property.Name}:");
foreach (var item in items)
{
_output.WriteLine($" {item}");
}
}
else
{
_output.WriteLine($" {property.Name}: {property.GetValue(obj, null)}");
}
}
}

Convert anonymous type with nested dictionaries to human-readable string for testing purposes [duplicate]

I want to take an anonymous object as argument to a method, and then iterate over its properties to add each property/value to a a dynamic ExpandoObject.
So what I need is to go from
new { Prop1 = "first value", Prop2 = SomeObjectInstance, Prop3 = 1234 }
to knowing names and values of each property, and being able to add them to the ExpandoObject.
How do I accomplish this?
Side note: This will be done in many of my unit tests (I'm using it to refactor away a lot of junk in the setup), so performance is to some extent relevant. I don't know enough about reflection to say for sure, but from what I've understood it's pretty performance heavy, so if it's possible I'd rather avoid it...
Follow-up question:
As I said, I'm taking this anonymous object as an argument to a method. What datatype should I use in the method's signature? Will all properties be available if I use object?
foreach(var prop in myVar.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(myVar,null));
}
Reflect on the anonymous object to get its property names and values, then take advantage of an ExpandoObject actually being a dictionary to populate it. Here's an example, expressed as a unit test:
[TestMethod]
public void ShouldBeAbleToConvertAnAnonymousObjectToAnExpandoObject()
{
var additionalViewData = new {id = "myControlId", css = "hide well"};
dynamic result = new ExpandoObject();
var dict = (IDictionary<string, object>)result;
foreach (PropertyInfo propertyInfo in additionalViewData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
dict[propertyInfo.Name] = propertyInfo.GetValue(additionalViewData, null);
}
Assert.AreEqual(result.id, "myControlId");
Assert.AreEqual(result.css, "hide well");
}
An alternative approach is to use DynamicObject instead of ExpandoObject, and that way you only have the overhead of doing the reflection if you actually try to access a property from the other object.
public class DynamicForwarder : DynamicObject
{
private object _target;
public DynamicForwarder(object target)
{
_target = target;
}
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
var prop = _target.GetType().GetProperty(binder.Name);
if (prop == null)
{
result = null;
return false;
}
result = prop.GetValue(_target, null);
return true;
}
}
Now it only does the reflection when you actually try to access the property via a dynamic get. On the downside, if you repeatedly access the same property, it has to do the reflection each time. So you could cache the result:
public class DynamicForwarder : DynamicObject
{
private object _target;
private Dictionary<string, object> _cache = new Dictionary<string, object>();
public DynamicForwarder(object target)
{
_target = target;
}
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
// check the cache first
if (_cache.TryGetValue(binder.Name, out result))
return true;
var prop = _target.GetType().GetProperty(binder.Name);
if (prop == null)
{
result = null;
return false;
}
result = prop.GetValue(_target, null);
_cache.Add(binder.Name, result); // <-------- insert into cache
return true;
}
}
You could support storing a list of target objects to coalesce their properties, and support setting properties (with a similar override called TrySetMember) to allow you to dynamically set values in the cache dictionary.
Of course, the overhead of reflection is probably not going to be worth worrying about, but for large objects this could limit the impact of it. What is maybe more interesting is the extra flexibility it gives you.
This is an old question, but now you should be able to do this with the following code:
dynamic expObj = new ExpandoObject();
expObj.Name = "James Kirk";
expObj.Number = 34;
// print the dynamically added properties
// enumerating over it exposes the Properties and Values as a KeyValuePair
foreach (KeyValuePair<string, object> kvp in expObj){
Console.WriteLine("{0} = {1} : Type: {2}", kvp.Key, kvp.Value, kvp.Value.GetType());
}
The output would look like the following:
Name = James Kirk : Type: System.String
Number = 34 : Type:
System.Int32
you have to use reflection.... (code "borrowed" from this url)
using System.Reflection; // reflection namespace
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Console.WriteLine(propertyInfo.Name);
}
Use Reflection.Emit to create a generic method to fill an ExpandoObject.
OR use Expressions perhaps (I think this would only be possible in .NET 4 though).
Neither of these approaches uses reflection when invoking, only during setup of a delegate (which obviously needs to be cached).
Here is some Reflection.Emit code to fill a dictionary (I guess ExpandoObject is not far off);
static T CreateDelegate<T>(this DynamicMethod dm) where T : class
{
return dm.CreateDelegate(typeof(T)) as T;
}
static Dictionary<Type, Func<object, Dictionary<string, object>>> cache =
new Dictionary<Type, Func<object, Dictionary<string, object>>>();
static Dictionary<string, object> GetProperties(object o)
{
var t = o.GetType();
Func<object, Dictionary<string, object>> getter;
if (!cache.TryGetValue(t, out getter))
{
var rettype = typeof(Dictionary<string, object>);
var dm = new DynamicMethod(t.Name + ":GetProperties", rettype,
new Type[] { typeof(object) }, t);
var ilgen = dm.GetILGenerator();
var instance = ilgen.DeclareLocal(t);
var dict = ilgen.DeclareLocal(rettype);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Castclass, t);
ilgen.Emit(OpCodes.Stloc, instance);
ilgen.Emit(OpCodes.Newobj, rettype.GetConstructor(Type.EmptyTypes));
ilgen.Emit(OpCodes.Stloc, dict);
var add = rettype.GetMethod("Add");
foreach (var prop in t.GetProperties(
BindingFlags.Instance |
BindingFlags.Public))
{
ilgen.Emit(OpCodes.Ldloc, dict);
ilgen.Emit(OpCodes.Ldstr, prop.Name);
ilgen.Emit(OpCodes.Ldloc, instance);
ilgen.Emit(OpCodes.Ldfld, prop);
ilgen.Emit(OpCodes.Castclass, typeof(object));
ilgen.Emit(OpCodes.Callvirt, add);
}
ilgen.Emit(OpCodes.Ldloc, dict);
ilgen.Emit(OpCodes.Ret);
cache[t] = getter =
dm.CreateDelegate<Func<object, Dictionary<string, object>>>();
}
return getter(o);
}

loop through an object and find the not null properties

I have 2 instances of the same objects, o1, and o2. If I am doing things like
if (o1.property1 != null) o1.property1 = o2.property1
for all the properties in the object. What would be the most efficient way to loop through all properties in an Object and do that? I saw people using PropertyInfo to check nulll of the properties but it seems like they could only get through the PropertyInfo collection but not link the operation of the properties.
Thanks.
You can do this with reflection:
public void CopyNonNullProperties(object source, object target)
{
// You could potentially relax this, e.g. making sure that the
// target was a subtype of the source.
if (source.GetType() != target.GetType())
{
throw new ArgumentException("Objects must be of the same type");
}
foreach (var prop in source.GetType()
.GetProperties(BindingFlags.Instance |
BindingFlags.Public)
.Where(p => !p.GetIndexParameters().Any())
.Where(p => p.CanRead && p.CanWrite))
{
var value = prop.GetValue(source, null);
if (value != null)
{
prop.SetValue(target, value, null);
}
}
}
Judging from your example i think your looking for something like this:
static void CopyTo<T>(T from, T to)
{
foreach (PropertyInfo property in typeof(T).GetProperties())
{
if (!property.CanRead || !property.CanWrite || (property.GetIndexParameters().Length > 0))
continue;
object value = property.GetValue(to, null);
if (value != null)
property.SetValue(to, property.GetValue(from, null), null);
}
}
If you are going to use this many times, you could use a compiled expression for better performance:
public static class Mapper<T>
{
static Mapper()
{
var from = Expression.Parameter(typeof(T), "from");
var to = Expression.Parameter(typeof(T), "to");
var setExpressions = typeof(T)
.GetProperties()
.Where(property => property.CanRead && property.CanWrite && !property.GetIndexParameters().Any())
.Select(property =>
{
var getExpression = Expression.Call(from, property.GetGetMethod());
var setExpression = Expression.Call(to, property.GetSetMethod(), getExpression);
var equalExpression = Expression.Equal(Expression.Convert(getExpression, typeof(object)), Expression.Constant(null));
return Expression.IfThen(Expression.Not(equalExpression), setExpression);
});
Map = Expression.Lambda<Action<T, T>>(Expression.Block(setExpressions), from, to).Compile();
}
public static Action<T, T> Map { get; private set; }
}
And use it like this:
Mapper<Entity>.Map(e1, e2);

Possible to create an implicit cast for an anonymous type to a dictionary?

I wrote a method like this:
using AttrDict = System.Collections.Generic.Dictionary<string, object>;
using IAttrDict = System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>;
static string HtmlTag(string tagName, string content = null, IAttrDict attrs = null)
{
var sb = new StringBuilder("<");
sb.Append(tagName);
if(attrs != null)
foreach (var attr in attrs)
sb.AppendFormat(" {0}=\"{1}\"", attr.Key, attr.Value.ToString().EscapeQuotes());
if (content != null) sb.AppendFormat(">{0}</{1}>", content, tagName);
else sb.Append(" />");
return sb.ToString();
}
Which you can call like
HtmlTag("div", "hello world", new AttrDict{{"class","green"}});
Not too bad. But what if I wanted to allow users to pass an anonymous type in place of the dict? Like
HtmlTag("div", "hello world", new {#class="green"});
Even better! I could write the overload easily, but the problem is I'm going to have about 50 functions like this, I don't want to overload each one of them. I was hoping I could just write an implicit cast to do the work for me...
public class AttrDict : Dictionary<string, object>
{
public static implicit operator AttrDict(object obj)
{
// conversion from anonymous type to AttrDict here
}
}
But C# simply won't allow it:
user-defined conversions to or from a base class are not allowed
So what can I do?
You can't do what you want directly. Like the ASP.NET MVC helper methods, you should probably go the other way. attrs should just be of type object. Then within the body of the method, you can handle it as either an anonymous type or a dictionary depending on its runtime type.
You can create an extension-method that uses reflection to do the conversion you want. This would look something like:
public static class AttrDictX
{
public static AttrDict ToAttrDict(this object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
var ans = new AttrDict();
foreach (var prop in obj.GetType().GetProperties())
{
if (prop.CanRead)
ans.Add(prop.Name, prop.GetValue(obj, null));
}
return ans;
}
}
Then the call-site will either:
Contain a .ToAttrDict() call.
(or) Look unchanged if you can provide an overload to the HtmlTag method that takes an object instead and does the conversion internally.
The second option is particularly desirable if you don't like extensions on object, which some people (not me) consider bad practice.
My Solution
static string EscapeQuotes(this string str)
{
return str.Replace("\"", "\\\"");
}
static IAttrDict ToDictionary(this object obj)
{
return obj.GetType().GetProperties().Where(prop => prop.CanRead).ToDictionary(prop => prop.Name, prop => prop.GetValue(obj, null));
}
static string HtmlTag(string tagName, string content = null, object attrs = null)
{
IAttrDict attrDict = attrs != null ? attrs is IAttrDict ? (IAttrDict)attrs : attrs.ToDictionary() : null;
var sb = new StringBuilder("<");
sb.Append(tagName);
if(attrDict != null)
foreach (var attr in attrDict)
sb.AppendFormat(" {0}=\"{1}\"", attr.Key, attr.Value.ToString().EscapeQuotes());
if (content != null) sb.AppendFormat(">{0}</{1}>", content, tagName);
else sb.Append(" />");
return sb.ToString();
}

Get properties and values from unknown object

From the world of PHP I have decided to give C# a go. I've had a search but can't seem to find the answer of how to do the equivalent to this.
$object = new Object();
$vars = get_class_vars(get_class($object));
foreach($vars as $var)
{
doSomething($object->$var);
}
I basically have a List of an object. The object could be one of three different types and will have a set of public properties. I want to be able to get a list of the properties for the object, loop over them and then write them out to a file.
I'm thinking this has something to do with c# reflection but it's all new to me.
Any help would be greatly appreciated.
This should do it:
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(myObject, null);
// Do something with propValue
}
void Test(){
var obj = new{a="aaa", b="bbb"};
var val_a = obj.GetValObjDy("a"); //="aaa"
var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
Yes, Reflection would be the way to go. First, you would get the Type that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType method on Object. Because it is on the Object class, it's callable by every object in .NET, as all types derive from Object (well, technically, not everything, but that's not important here).
Once you have the Type instance, you can call the GetProperties method to get the PropertyInfo instances which represent the run-time informationa about the properties on the Type.
Note, you can use the overloads of GetProperties to help classify which properties you retrieve.
From there, you would just write the information out to a file.
Your code above, translated, would be:
// The instance, it can be of any type.
object o = <some object>;
// Get the type.
Type type = o.GetType();
// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
// Do something with the property info.
DoSomething(info);
}
Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods or GetFields methods respectively.
Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.
Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as or is operator to help determine which base class/interface you are working with at runtime).
However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.
well, in C# it's similar.
Here's one of the simplest examples (only for public properties):
var someObject = new { .../*properties*/... };
var propertyInfos = someObject.GetType().GetProperties();
foreach (PropertyInfo pInfo in propertyInfos)
{
string propertyName = pInfo.Name; //gets the name of the property
doSomething(pInfo.GetValue(someObject,null));
}
One line solution using Linq...
var obj = new {Property1 = 1, Property2 = 2};
var property1 = obj.GetType().GetProperties().First(o => o.Name == "Property1").GetValue(obj , null);
To get specific property value from property name
public class Bike{
public string Name {get;set;}
}
Bike b = new Bike {Name = "MyBike"};
to access property value of Name from string name of property
public object GetPropertyValue(string propertyName)
{
//returns value of property Name
return this.GetType().GetProperty(propertyName).GetValue(this, null);
}
You can use GetType - GetProperties - Linq Foreach:
obj.GetType().GetProperties().ToList().ForEach(p =>{
//p is each PropertyInfo
DoSomething(p);
});
Here's something I use to transform an IEnumerable<T> into a DataTable that contains columns representing T's properties, with one row for each item in the IEnumerable:
public static DataTable ToDataTable<T>(IEnumerable<T> items)
{
var table = CreateDataTableForPropertiesOfType<T>();
PropertyInfo[] piT = typeof(T).GetProperties();
foreach (var item in items)
{
var dr = table.NewRow();
for (int property = 0; property < table.Columns.Count; property++)
{
if (piT[property].CanRead)
{
var value = piT[property].GetValue(item, null);
if (piT[property].PropertyType.IsGenericType)
{
if (value == null)
{
dr[property] = DBNull.Value;
}
else
{
dr[property] = piT[property].GetValue(item, null);
}
}
else
{
dr[property] = piT[property].GetValue(item, null);
}
}
}
table.Rows.Add(dr);
}
return table;
}
public static DataTable CreateDataTableForPropertiesOfType<T>()
{
DataTable dt = new DataTable();
PropertyInfo[] piT = typeof(T).GetProperties();
foreach (PropertyInfo pi in piT)
{
Type propertyType = null;
if (pi.PropertyType.IsGenericType)
{
propertyType = pi.PropertyType.GetGenericArguments()[0];
}
else
{
propertyType = pi.PropertyType;
}
DataColumn dc = new DataColumn(pi.Name, propertyType);
if (pi.CanRead)
{
dt.Columns.Add(dc);
}
}
return dt;
}
This is "somewhat" overcomplicated, but it's actually quite good for seeing what the outcome is, as you can give it a List<T> of, for example:
public class Car
{
string Make { get; set; }
int YearOfManufacture {get; set; }
}
And you'll be returned a DataTable with the structure:
Make (string)
YearOfManufacture (int)
With one row per item in your List<Car>
This example trims all the string properties of an object.
public static void TrimModelProperties(Type type, object obj)
{
var propertyInfoArray = type.GetProperties(
BindingFlags.Public |
BindingFlags.Instance);
foreach (var propertyInfo in propertyInfoArray)
{
var propValue = propertyInfo.GetValue(obj, null);
if (propValue == null)
continue;
if (propValue.GetType().Name == "String")
propertyInfo.SetValue(
obj,
((string)propValue).Trim(),
null);
}
}
I haven't found this to work on, say Application objects. I have however had success with
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string rval = serializer.Serialize(myAppObj);
You can try this:
string[] arr = ((IEnumerable)obj).Cast<object>()
.Select(x => x.ToString())
.ToArray();
Once every array implements IEnumerable interface
public Dictionary<string, string> ToDictionary(object obj)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Type objectType = obj.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(objectType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(obj, null);
dictionary.Add(prop.Name, propValue.ToString());
}
return dictionary;
}
/// get set value field in object to object new (two object field like )
public static void SetValueObjectToObject (object sourceObj , object resultObj)
{
IList<PropertyInfo> props = new List<PropertyInfo>(sourceObj.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
//get value in sourceObj
object propValue = prop.GetValue(sourceObj, null);
//set value in resultObj
PropertyInfo propResult = resultObj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
if (propResult != null && propResult.CanWrite)
{
propResult.SetValue(resultObj, propValue, null);
}
}
catch (Exception ex)
{
// do something with Ex
}
}
}

Categories