Example #1
0
        private void StoreFromListItem <T>(T entity, ListItem item)
        {
            Type entityType = typeof(T);

            foreach (var property in entityType.GetProperties())
            {
                string fieldname   = null;
                object sourceValue = null;
                Type   sourceType  = null;
                Type   targetType  = null;
                try
                {
                    if (!property.CanWrite)
                    {
                        continue;
                    }
                    if (property.GetCustomAttribute <IgnoreOnSelectAttribute>() != null)
                    {
                        continue;
                    }
                    fieldname = EntityHelper.GetInternalNameFromProperty(property);
                    if (item.FieldValues.ContainsKey(fieldname) && item.FieldValues[fieldname] != null)
                    {
                        sourceValue = item.FieldValues[fieldname];
                        targetType  = property.PropertyType;
                        sourceType  = sourceValue.GetType();

                        object propertyValue = EntityHelper.GetPropertyFromItemValue(property, item.FieldValues[fieldname]);
                        if (property.PropertyType.IsAssignableFrom(propertyValue.GetType()))
                        {
                            property.SetValue(entity, propertyValue);
                        }
                        else
                        {
                            property.SetValue(entity, Convert.ChangeType(propertyValue, property.PropertyType));
                        }
                    }
                    else if (fieldname == "Id")
                    {
                        property.SetValue(entity, item.Id);
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = $"Could not store data from field '{fieldname}' ";
                    _log.Error(errorMessage, ex);
                    var exception = new Exception(errorMessage, ex);
                    exception.Data.Add("Field", fieldname);
                    exception.Data.Add("SourceValue", sourceValue);
                    exception.Data.Add("SourceType", sourceType);
                    exception.Data.Add("TargetType", targetType);
                }
            }
        }