public void SetValue(object target, object sourcedata)
        {
            object targetData = null;

            try
            {
                if (IsClass)
                {
                    targetData = Activator.CreateInstance(_type, new object[] { sourcedata });
                }
                else
                {
                    if (sourcedata != null && sourcedata.GetType() == _type)
                    {
                        targetData = sourcedata;
                    }
                    else if (_type.IsEnum)
                    {
                        if (_enumTypeDescriptor != null)
                        {
                            //If the SourceData is null and an NullValues is defined via MapNullValueAttribute, use it!
                            if ((sourcedata == null) && (NullValue != null))
                            {
                                targetData = NullValue;
                            }
                            else
                            {
                                targetData = _enumTypeDescriptor.MapFrom(sourcedata);
                            }
                        }
                    }
                    else
                    {
                        targetData = Convert.ChangeType(sourcedata, _type);
                    }
                }

                if (_propInfo != null && _propInfo.CanWrite)
                {
                    _propInfo.SetValue(target, targetData, null);
                }
                else if (_fieldInfo != null)
                {
                    _fieldInfo.SetValue(target, targetData);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("Error reading value {0}({1}) into {2} for {3}", sourcedata,
                                           (sourcedata != null) ? sourcedata.GetType().Name : "null", _type.Name, _propertyName);
                //throw new MappingException(msg, ex);
                throw new Exception(msg, ex);
            }
        }
Example #2
0
        public static object ToEnum(object sourceValue, Type type)
        {
            EnumDescriptor enumTypeDescriptor = EnumDescriptorFactory.CreateEnumDescriptor(type) as EnumDescriptor;

            return((Enum)enumTypeDescriptor.MapFrom(sourceValue));
        }