Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Case-insentive property setter
Message
From
25/03/2007 15:16:57
 
 
To
All
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Title:
Case-insentive property setter
Environment versions
Environment:
VB 8.0
Miscellaneous
Thread ID:
01208319
Message ID:
01208319
Views:
52
I use modified Rockford Lhotka excellent SetPropertyValue()
from DataMapper class to load objects from database.
My entity object property names are mixed case.
DataReader returns lower-case only column names.
So SetPropertyValue() cannot map columns to property names.

How to change this code so that it does not depend on the propertyName case ?
/// <summary>
/// Sets an object's property with the specified value,
/// coercing that value to the appropriate type if possible.
/// </summary>
/// <param name="target">Object containing the property to set.</param>
/// <param name="propertyName">Name of the property to set.</param>
/// <param name="value">Value to set into the property.</param>
public static void SetPropertyValue(
   object target, string propertyName, object value)
 {
   PropertyInfo propertyInfo =
        target.GetType().GetProperty(propertyName);
   if (value == null)
        propertyInfo.SetValue(target, value, null);
   else
      {
        Type pType =
          Utilities.GetPropertyType(propertyInfo.PropertyType);
        Type vType =
          Utilities.GetPropertyType(value.GetType());
        if (pType.Equals(vType))
        {
          // types match, just copy value
          propertyInfo.SetValue(target, value, null);
        }
        else
        {
          // types don't match, try to coerce
          if (pType.Equals(typeof(Guid)))
            propertyInfo.SetValue(
              target, new Guid(value.ToString()), null);
          else if (pType.IsEnum && vType.Equals(typeof(string)))
            propertyInfo.SetValue(target, Enum.Parse(pType, value.ToString()), null);
					else if (pType.IsEnum && vType.Equals(typeof(decimal)))
						propertyInfo.SetValue(target, 
							Enum.Parse(pType, value.ToString()), null);

					else
            propertyInfo.SetValue(
              target, Convert.ChangeType(value, pType), null);
        }
      }
    }
  }
}
Andrus
Next
Reply
Map
View

Click here to load this message in the networking platform