Exemplo n.º 1
0
        /// <summary>
        /// Gets property mappings for a specified type from a DataTable.
        /// </summary>
        /// <typeparam name="T">The type of object to map.</typeparam>
        /// <param name="dataTable">The DataTable to map from.</param>
        /// <param name="settings">The settings to use while mapping.</param>
        /// <returns>A list of the mappings.</returns>
        public ExtendedPropertyInfo[] GetPropertyMappings <T>(DataTable dataTable, DataTableParserSettings settings)
        {
            Guard.ArgumentNotNull(dataTable);
            Guard.ArgumentNotNull(settings);

            var mappedProperties = new List <ExtendedPropertyInfo>();

            var typeProperties = GetPropertiesForType <T>(settings.InheritMappings);

            // For non-overwriting mappings the execution order is important.
            switch (settings.MappingMatchOrder)
            {
            case MappingMatchOrder.PropertyNameFirst:
                PropertyResolver.GenerateMappingsFromProperties(mappedProperties, dataTable, settings, typeProperties);
                AttributeResolver.GenerateMappingsFromAttributes(mappedProperties, dataTable, settings, typeProperties);
                break;

            case MappingMatchOrder.AttributeValueFirst:
                AttributeResolver.GenerateMappingsFromAttributes(mappedProperties, dataTable, settings, typeProperties);
                PropertyResolver.GenerateMappingsFromProperties(mappedProperties, dataTable, settings, typeProperties);
                break;

            case MappingMatchOrder.IgnorePropertyNames:
                AttributeResolver.GenerateMappingsFromAttributes(mappedProperties, dataTable, settings, typeProperties);
                break;

            case MappingMatchOrder.IgnoreAttributes:
                PropertyResolver.GenerateMappingsFromProperties(mappedProperties, dataTable, settings, typeProperties);
                break;
            }

            CheckForErrors <T>(settings, mappedProperties, typeProperties);

            return(mappedProperties.ToArray());
        }
Exemplo n.º 2
0
        public virtual IList <T> ToObjects <T>(DataRow[] dataRows,
                                               IDataTypeConverter dataTypeConverter,
                                               ExtendedPropertyInfo[] mappings,
                                               DataTableParserSettings settings)
        {
            Guard.ArgumentNotNull(dataRows);
            Guard.ArgumentNotNull(dataTypeConverter);
            Guard.ArgumentNotNull(mappings);
            Guard.ArgumentNotNull(settings);

            var dbNullConverter = GetDbNullConverter(settings);

            var objectList = new T[dataRows.Length];

            for (int rowIndex = 0; rowIndex < dataRows.Length; rowIndex++)
            {
                var returnObject = ObjectInstantiator <T> .CreateNew();

                foreach (var mapping in mappings)
                {
                    object value = dataTypeConverter.FieldToObject(dataRows[rowIndex][mapping.ColumnIndex],
                                                                   mapping.PropertyInfo.PropertyType,
                                                                   settings,
                                                                   dbNullConverter);

                    mapping.PropertyInfo.SetValue(returnObject, value);
                }

                objectList[rowIndex] = returnObject;
            }

            return(objectList);
        }
Exemplo n.º 3
0
 private ConversionManager GetConverter(DataTableParserSettings dataTableParserSettings)
 {
     return(new ConversionManager(dataTableParserSettings,
                                  mappingResolver,
                                  GetResolver(),
                                  dataTypeConverter));
 }
Exemplo n.º 4
0
        public virtual void GenerateMappingsFromProperties(IList <ExtendedPropertyInfo> mappedProperties,
                                                           DataTable dataTable,
                                                           DataTableParserSettings settings,
                                                           PropertyInfo[] properties)
        {
            bool isFirstMapper = mappedProperties.Count == 0;

            foreach (PropertyInfo property in properties)
            {
                // If we must avoid overwrites we do so here.
                if (!isFirstMapper && !settings.SubsequentMappingsShouldOverwrite)
                {
                    if (mappedProperties.Count(p => p.PropertyInfo.Name == property.Name) > 0)
                    {
                        continue;
                    }
                }

                bool mappingFound = false;

                if (dataTable.Columns.Contains(property.Name))
                {
                    mappedProperties.Add(new ExtendedPropertyInfo(fieldName: property.Name, propertyInfo: property, columnIndex: dataTable.Columns.IndexOf(property.Name)));
                    mappingFound = true;
                }

                // Special case handling for Id columns/properties.
                if (!mappingFound && property.Name.ToLowerInvariant().Contains(Id))
                {
                    GenerateIdSpecificPropertyMappings(mappedProperties, dataTable, property);
                }
            }
        }
Exemplo n.º 5
0
 public object FieldToObject(object field, Type type, DataTableParserSettings settings, DbNullConverter dbNullConverter)
 {
     if (type.IsValueType)
     {
         return(Activator.CreateInstance(type));
     }
     return(null);
 }
Exemplo n.º 6
0
        public static DataTableConverter Create(DataTableParserSettings settings)
        {
            var parser = new DataTableConverter {
                DataTableParserSettings = settings
            };

            return(parser);
        }
        protected virtual object ValueTypeFieldToObject(object field, Type type, DataTableParserSettings settings)
        {
            try
            {
                if (type == typeof(int))
                {
                    return(FieldToInt(field));
                }
                else if (type == typeof(Guid))
                {
                    return(FieldToGuid(field));
                }
                else if (type == typeof(DateTime))
                {
                    return(FieldToDateTime(field));
                }
                else if (type == typeof(bool))
                {
                    return(FieldToBool(field));
                }
                else if (type == typeof(char))
                {
                    return(FieldToChar(field));
                }
                else if (type == typeof(decimal))
                {
                    return(FieldToDecimal(field));
                }
                else if (type == typeof(float))
                {
                    return(FieldToFloat(field));
                }
                else if (type == typeof(uint))
                {
                    int value = (int)FieldToInt(field);

                    if (value < 0)
                    {
                        value = value * -1;
                    }
                    return(value);
                }
                else if (type == typeof(double))
                {
                    return(FieldToDouble(field));
                }
                else if (type == typeof(long))
                {
                    return(FieldToLong(field));
                }

                throw new NotImplementedException(string.Format("No conversion for field with value: {0} to type: {1}", field.ToString(), type.Name));
            }
            catch (InvalidCastException ex)
            {
                throw new NotImplementedException(string.Format("No conversion for field with value: {0} to type: {1}", field.ToString(), type.Name), ex);
            }
        }
Exemplo n.º 8
0
        public void GetPropertyMappings_TwoPropertiesOneMatching_ThrowsMissingMappingException()
        {
            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns("PropertyOne");

            DataTableParserSettings dtps = new DataTableParserSettings {
                MissingMappingHandling = MissingMappingHandling.Error
            };

            Assert.Throws(typeof(MissingMappingException <SimpleNoIdNoAttributes>), () => defaultMappingResolver.GetPropertyMappings <SimpleNoIdNoAttributes>(dt, dtps));
        }
Exemplo n.º 9
0
 public ConversionManager(DataTableParserSettings dataTableParserSettings,
                          IMappingResolver mappingResolver,
                          IDataTableResolver dataTableResolver,
                          IDataTypeConverter dataTypeConverter)
 {
     this.dataTableParserSettings = dataTableParserSettings;
     this.mappingResolver         = mappingResolver;
     this.dataTableResolver       = dataTableResolver;
     this.dataTypeConverter       = dataTypeConverter;
 }
Exemplo n.º 10
0
        public void GetPropertyMappings_TwoPropertiesOneMatching_MissingMappingHandlingIgnores()
        {
            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns("PropertyOne");

            DataTableParserSettings dtps = new DataTableParserSettings {
                MissingMappingHandling = MissingMappingHandling.Ignore
            };

            var results = defaultMappingResolver.GetPropertyMappings <SimpleNoIdNoAttributes>(dt, dtps);

            Assert.True(results.Length == 1);
        }
Exemplo n.º 11
0
        public void GetPropertyMappings_TwoAttributesWithOneMatchingColumnErrorOnMissingMapping_ThrowsMissingMappingException()
        {
            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns("prop1", "PropertyTwo");

            DataTableParserSettings dtps = new DataTableParserSettings
            {
                MissingMappingHandling = MissingMappingHandling.Error,
                MappingMatchOrder      = MappingMatchOrder.IgnorePropertyNames
            };

            Assert.Throws(typeof(MissingMappingException <SimpleClassWithAttributes>), () => defaultMappingResolver.GetPropertyMappings <SimpleClassWithAttributes>(dt, dtps));
        }
Exemplo n.º 12
0
        public void GetPropertyMappings_ClassWithInheritedProperties_OnlyReturnsImmediateProperties()
        {
            string[] columns = { "ParentIntProperty", "ParentStringProperty", "ChildIntProperty", "ChildStringProperty" };

            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns(columns);

            DataTableParserSettings dtps = new DataTableParserSettings {
                InheritMappings = false
            };

            var results = defaultMappingResolver.GetPropertyMappings <ChildNoAttributes>(dt, dtps);

            Assert.True(results.Length == 2);
        }
Exemplo n.º 13
0
        public void GetPropertyMappings_ClassWithTwoLevelsOfInheritance_ReturnsAllResults()
        {
            string[] columns = { "ParentIntProperty", "ParentStringProperty", "ChildIntProperty", "ChildStringProperty", "LeafIntProperty" };

            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns(columns);

            DataTableParserSettings dtps = new DataTableParserSettings {
                InheritMappings = true
            };

            var results = defaultMappingResolver.GetPropertyMappings <LeafClassNoAttributes>(dt, dtps);

            Assert.True(results.Length == 5);
        }
Exemplo n.º 14
0
        public void GetPropertyMappings_TwoAttributesWithOneMatchingColumnAndPropertyMatch_ReturnsResults()
        {
            DataTable dt = DataTableFactory.GenerateEmptyDataTableWithStringColumns("prop1", "PropertyTwo");

            DataTableParserSettings dtps = new DataTableParserSettings
            {
                MissingMappingHandling = MissingMappingHandling.Error,
                MappingMatchOrder      = MappingMatchOrder.PropertyNameFirst
            };

            var results = defaultMappingResolver.GetPropertyMappings <SimpleClassWithAttributes>(dt, dtps);

            Assert.True(results.Length == 2);
        }
Exemplo n.º 15
0
        private static void CheckForErrors <T>(DataTableParserSettings settings,
                                               List <ExtendedPropertyInfo> mappedProperties,
                                               PropertyInfo[] typeProperties)
        {
            // Error in mapping handling, checks for missing mappings.
            if (settings.MissingMappingHandling == MissingMappingHandling.Error &&
                mappedProperties.Count < typeProperties.Length)
            {
                throw new MissingMappingException <T>();
            }

            // Checks for duplicate mappings in the list.
            if (!settings.AllowDuplicateMappings &&
                mappedProperties.Select(p => p.ColumnIndex).Distinct().Count() != mappedProperties.Count)
            {
                throw new DuplicateMappingException <T>();
            }
        }
Exemplo n.º 16
0
        public virtual object FieldToObject(object field,
                                            Type type,
                                            DataTableParserSettings settings,
                                            DbNullConverter dbNullConverter)
        {
            if (field == DBNull.Value || field == null)
            {
                return(dbNullConverter.DbNullToObject(type));
            }

            if (type == stringType)
            {
                return(field.ToString());
            }

            if (!type.IsValueType && type != stringType)
            {
                throw new NotImplementedException("No Conversion exists for class of type: " + type.Name);
            }

            return(ValueTypeFieldToObject(field, type, settings));
        }
Exemplo n.º 17
0
        public virtual void GenerateMappingsFromAttributes(List <ExtendedPropertyInfo> mappedProperties,
                                                           DataTable dataTable,
                                                           DataTableParserSettings settings,
                                                           PropertyInfo[] properties)
        {
            bool isFirstMapper = mappedProperties.Count == 0;

            foreach (PropertyInfo property in properties)
            {
                // If we must avoid overwrites we do so here.
                if (!isFirstMapper &&
                    !settings.SubsequentMappingsShouldOverwrite &&
                    mappedProperties.Count(p => p.PropertyInfo.Name == property.Name) > 0)
                {
                    continue;
                }

                // Use the static method in order to inspect inherited properties.
                Attribute[] attributes = Attribute.GetCustomAttributes(property, typeof(ColumnMapping), settings.InheritMappings);

                if (attributes.Length == 0)
                {
                    continue;
                }

                // Find the matching attribute if it exists, null if not.
                ColumnMapping matchedAttribute = FindMappedAttribute(attributes, dataTable.Columns);

                if (matchedAttribute != null)
                {
                    mappedProperties.Add(new ExtendedPropertyInfo(
                                             fieldName: matchedAttribute.Name,
                                             propertyInfo: property,
                                             columnIndex: dataTable.Columns.IndexOf(matchedAttribute.Name)));
                }
            }
        }
Exemplo n.º 18
0
 public ExtendedPropertyInfo[] GetPropertyMappings <T>(DataTable dataTable, DataTableParserSettings settings)
 {
     return(new ExtendedPropertyInfo[] { });
 }
Exemplo n.º 19
0
 public DbNullConverter(DataTableParserSettings settings)
 {
     this.settings = settings;
 }
Exemplo n.º 20
0
        public IList <T> ToObjects <T>(DataRow[] dataRows, IDataTypeConverter dataTypeConverter, ExtendedPropertyInfo[] mappings, DataTableParserSettings settings)
        {
            Guard.ArgumentNotNull(dataRows);
            Guard.ArgumentNotNull(dataTypeConverter);
            Guard.ArgumentNotNull(mappings);
            Guard.ArgumentNotNull(settings);

            List <T> objectList      = new List <T>(capacity: dataRows.Length);
            var      dbNullConverter = new DbNullConverter(settings);

            IEnumerable <DelegateColumnMapping <T> > delegates = GetDelegatesForType <T>(mappings);

            for (int rowIndex = 0; rowIndex < dataRows.Length; rowIndex++)
            {
                T returnObject = ObjectInstantiator <T> .CreateNew();

                foreach (var setterDelegate in delegates)
                {
                    object value = dataTypeConverter.FieldToObject(dataRows[rowIndex][setterDelegate.ExtendedPropertyInfo.ColumnIndex], setterDelegate.ExtendedPropertyInfo.PropertyInfo.PropertyType, settings, dbNullConverter);

                    setterDelegate.SetterDelegate(returnObject, value);
                }

                objectList.Add(returnObject);
            }

            return(objectList);
        }
Exemplo n.º 21
0
 protected virtual DbNullConverter GetDbNullConverter(DataTableParserSettings settings)
 {
     return(new DbNullConverter(settings));
 }
Exemplo n.º 22
0
 public IList <T> ToObjects <T>(DataRow[] dataRows, IDataTypeConverter dataTypeConverter, ExtendedPropertyInfo[] mappings, DataTableParserSettings settings)
 {
     return(new List <T>());
 }
Exemplo n.º 23
0
 public virtual IList <T> ConvertToObjectList <T>(DataTable table, DataTableParserSettings dataTableParserSettings)
 {
     return(ToObjectsInternal <T>(table, dataTableParserSettings));
 }
Exemplo n.º 24
0
 public static IList <T> Convert <T>(DataTable table, DataTableParserSettings settings)
 {
     return(new DataTableConverter().ConvertToObjectList <T>(table, settings));
 }
Exemplo n.º 25
0
 private ConversionManager GetConversionManagerWithCustomSettings(DataTableParserSettings settings)
 {
     return(new ConversionManager(settings, defaultMappingResolver, defaultDataTableResolver, defaultDataTypeConverter));
 }
Exemplo n.º 26
0
        public IList <T> ToObjects <T>(DataRow[] dataRows, IDataTypeConverter dataTypeConverter, ExtendedPropertyInfo[] mappings, DataTableParserSettings settings)
        {
            Guard.ArgumentNotNull(dataRows);
            Guard.ArgumentNotNull(dataTypeConverter);
            Guard.ArgumentNotNull(mappings);
            Guard.ArgumentNotNull(settings);

            ConcurrentBag <T> objectList = new ConcurrentBag <T>();
            var dbNullConverter          = new DbNullConverter(settings);

            Parallel.For(0, dataRows.Length, (rowIndex) =>
            {
                T returnObject = ObjectInstantiator <T> .CreateNew();

                foreach (var mapping in mappings)
                {
                    object value = dataTypeConverter.FieldToObject(dataRows[rowIndex][mapping.ColumnIndex], mapping.PropertyInfo.PropertyType, settings, dbNullConverter);
                    mapping.PropertyInfo.SetValue(returnObject, value);
                }

                objectList.Add(returnObject);
            });

            return(objectList.ToList());
        }
Exemplo n.º 27
0
 protected virtual IList <T> ToObjectsInternal <T>(DataTable table, DataTableParserSettings dataTableParserSettings)
 {
     return(GetConverter(dataTableParserSettings).ConvertToType <T>(table));
 }