/// <summary> /// Maps all the keys/values in the data dictionary to the /// </summary> /// <param name="object">The object to map</param> /// <param name="data">The data to map to the object.</param> /// <param name="namefilter">Filter on the keys. e.g. "Location." will only map keys that contain "Location."</param> /// <param name="errors">Error list for collecting errors.</param> public static void MapTo(object obj, IDictionary data, string namefilter, IErrors errors) { // 1. Get all the public, instance, writable properties. Type type = obj.GetType(); var propMap = ReflectionUtils.GetPropertiesAsMap(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, false); // 2. Making keys/filter case insensitive. Location. = location. namefilter = namefilter.Trim().ToLower(); // 3. Iterate through all the keys. foreach (DictionaryEntry entry in data) { var keyname = entry.Key as string; keyname = keyname.Trim().ToLower(); PropertyInfo prop = null; // 4. key in data matches filter? if (keyname.Contains(namefilter)) { // Get "City" from "Location.City"; string propname = keyname.Substring(keyname.IndexOf(".") + 1); propname.Trim().ToLower(); // 5. propname exists in the data type? if (propMap.ContainsKey(propname)) { // 6. Finally map prop = propMap[propname]; object val = entry.Value; object valConverted = ReflectionTypeChecker.ConvertToSameType(prop, val); prop.SetValue(obj, valConverted, null); } } } }
/// <summary> /// Set the property using the value provided. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="prop"></param> /// <param name="item"></param> /// <param name="counterOrRefId"></param> /// <param name="errors"></param> /// <param name="val"></param> public static void SetProperty(PropertyInfo prop, object item, int counterOrRefId, IErrors errors, object val) { try { // Found prop. Can now map. if (prop != null) { object convertedVal = null; // Handle special conversions. e.g. $105 or 9am etc. if (_propertyTypeMappers.ContainsKey(prop.PropertyType) && val != null && val.GetType() == typeof(string)) { Func <string, object> converter = _propertyTypeMappers[prop.PropertyType]; convertedVal = converter((string)val); } else { convertedVal = ReflectionTypeChecker.ConvertToSameType(prop, val); } ReflectionUtils.SetProperty(item, prop, convertedVal, true); } } catch (Exception ex) { if (errors != null) { var err = string.Format("Unable to map property '{0}' for counter/refId '{1}'", prop.Name, counterOrRefId); err += Environment.NewLine + ex.Message; errors.Add(err); } } }