Example #1
0
        private void Configure(TypeMapRegistry typeMapRegistry, TypeMap typeMap)
        {
            foreach (var action in _allTypeMapActions)
            {
                var expression = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);

                action(typeMap, expression);

                expression.Configure(this, typeMap);
            }

            foreach (var action in _allPropertyMapActions)
            {
                foreach (var propertyMap in typeMap.GetPropertyMaps())
                {
                    var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestMember, typeMap.SourceType);

                    action(propertyMap, memberExpression);

                    memberExpression.Configure(typeMap);
                }
            }

            ApplyBaseMaps(typeMapRegistry, typeMap, typeMap);
            ApplyDerivedMaps(typeMapRegistry, typeMap, typeMap);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ChecklistFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="childMappings">
        /// The child mappings.
        /// </param>
        /// <param name="dynamicTypeManager">
        /// The dynamic type manager.
        /// </param>
        public ChecklistFieldMapping(
            PropertyInfo property,
            MappingExpression valueExpression,
            IEnumerable<IProcessFieldMapping> childMappings,
            IDynamicTypeManager dynamicTypeManager)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            var checklistAttribute = property.GetCustomAttribute<ChecklistFieldAttribute>();
            if (checklistAttribute == null)
                throw new ArgumentException("The specified property is not a checklist field.");

            if (childMappings == null)
                throw new ArgumentNullException("childMappings");

            var childMappingsArray = childMappings.ToArray();
            if (childMappingsArray.All(m => !m.IsKey))
                throw new ArgumentException("At least one key field should be specified.");

            if (dynamicTypeManager == null)
                throw new ArgumentNullException("dynamicTypeManager");

            _property = property;
            _valueExpression = valueExpression;
            _childMappings = childMappingsArray;
            _dynamicTypeManager = dynamicTypeManager;
            _answerProcessName = checklistAttribute.AnswerProcessName;
        }
Example #3
0
        public void Custom_Mapping_Valid()
        {
            // arrange
            var model = new Model2
            {
                EmailAddress = "*****@*****.**",
                Number       = 21,
                Category     = "dev"
            };

            var expression = new MappingExpression <Model2>();

            expression
            .ForMember(m => m.Category, cat => !string.IsNullOrWhiteSpace(cat))
            .ForMember(m => m.EmailAddress, email => email.Contains("@"))
            .ForMember(m => m.Number, num => num >= 18);

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Should().NotBeNull();
            result.Success.Should().BeTrue();
            result.Errors.Count.Should().Be(0);
        }
Example #4
0
        private void Configure(TypeMap typeMap, IConfigurationProvider configurationProvider)
        {
            foreach (var action in AllTypeMapActions)
            {
                var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList);

                action(typeMap, expression);

                expression.Configure(typeMap);
            }

            foreach (var action in AllPropertyMapActions)
            {
                foreach (var propertyMap in typeMap.PropertyMaps)
                {
                    var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestinationMember, typeMap.SourceType);

                    action(propertyMap, memberExpression);

                    memberExpression.Configure(typeMap);
                }
            }

            ApplyBaseMaps(typeMap, typeMap, configurationProvider);
            ApplyDerivedMaps(typeMap, typeMap, configurationProvider);
            ApplyMemberMaps(typeMap, configurationProvider);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MultiCrossReferenceFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="childMappings">
        /// The child mappings.
        /// </param>
        /// <param name="dynamicTypeManager">
        /// The dynamic type manager.
        /// </param>
        /// <param name="runtimeDatabase">
        /// The runtime database.
        /// </param>
        public MultiCrossReferenceFieldMapping(
            PropertyInfo property,
            MappingExpression valueExpression,
            IEnumerable<IProcessFieldMapping> childMappings,
            IDynamicTypeManager dynamicTypeManager,
            IRuntimeDatabase runtimeDatabase)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            var crAttribute = property.GetCustomAttribute<CrossRefFieldAttribute>();
            if (crAttribute == null || !crAttribute.AllowMultiple)
                throw new ArgumentException("The specified property is not a multi cross reference field.");

            if (childMappings == null)
                throw new ArgumentNullException("childMappings");

            var childMappingsArray = childMappings.ToArray();
            if (childMappingsArray.All(m => !m.IsKey))
                throw new ArgumentException("At least one key field should be specified.");

            if (dynamicTypeManager == null)
                throw new ArgumentNullException("dynamicTypeManager");

            if (runtimeDatabase == null)
                throw new ArgumentNullException("runtimeDatabase");

            _property = property;
            _valueExpression = valueExpression;
            _childMappings = childMappingsArray;
            _dynamicTypeManager = dynamicTypeManager;
            _runtimeDatabase = runtimeDatabase;
            _referencedProcessName = crAttribute.ReferenceTableName;
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="nameExpression">
        /// The name expression.
        /// </param>
        /// <param name="contentExpression">
        /// The content expression.
        /// </param>
        /// <param name="locationExpression">
        /// The location expression.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        /// <param name="fileManager">
        /// The file manager.
        /// </param>
        public FileFieldMapping(
            PropertyInfo property,
            MappingExpression nameExpression,
            MappingExpression contentExpression,
            MappingExpression locationExpression,
            ITypeConverter typeConverter,
            IFileManager fileManager)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            if (!typeof(IFileProcess).IsAssignableFrom(property.PropertyType))
                throw new ArgumentException("The specified property is not a file field.");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            if (fileManager == null)
                throw new ArgumentNullException("fileManager");

            _property = property;
            _nameExpression = nameExpression;
            _contentExpression = contentExpression;
            _locationExpression = locationExpression;
            _typeConverter = typeConverter;
            _fileManager = fileManager;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SingleCrossReferenceFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="isKey">
        /// Specifies whether this is a key mapping.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        /// <param name="dynamicTypeManager">
        /// The dynamic type manager.
        /// </param>
        /// <param name="runtimeDatabase">
        /// The runtime database.
        /// </param>
        /// <param name="childMappings">
        /// The child mappings.
        /// </param>
        public SingleCrossReferenceFieldMapping(
            PropertyInfo property,
            MappingExpression valueExpression,
            bool isKey,
            ITypeConverter typeConverter,
            IDynamicTypeManager dynamicTypeManager,
            IRuntimeDatabase runtimeDatabase,
            IEnumerable<IProcessFieldMapping> childMappings)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            var crAttribute = property.GetCustomAttribute<CrossRefFieldAttribute>();
            if (crAttribute == null || crAttribute.AllowMultiple || !typeof(int?).IsAssignableFrom(property.PropertyType))
                throw new ArgumentException("The specified property is not a single cross reference field.");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            if (dynamicTypeManager == null)
                throw new ArgumentNullException("dynamicTypeManager");

            if (runtimeDatabase == null)
                throw new ArgumentNullException("runtimeDatabase");

            _property = property;
            _valueExpression = valueExpression;
            _isKey = isKey;
            _typeConverter = typeConverter;
            _dynamicTypeManager = dynamicTypeManager;
            _runtimeDatabase = runtimeDatabase;
            _childMappings = (childMappings ?? Enumerable.Empty<IProcessFieldMapping>()).ToArray();
            _referencedProcessName = crAttribute.ReferenceTableName;
        }
Example #8
0
        public IMappingExpression <TSource, TDestination> ConfigureMap(MemberList memberList)
        {
            var typeMapConfiguration = new MappingExpression <TSource, TDestination>(memberList);

            InlineConfiguration = typeMapConfiguration;

            return(typeMapConfiguration);
        }
Example #9
0
        public TDest Map <TSource, TDest>(TSource source, TDest destination)
        {
            EnsureMappingConfigured <TSource, TDest>();

            MappingExpression <TSource, TDest> .Apply(source, destination);

            return(destination);
        }
Example #10
0
        private IMappingExpression <TSource, TDestination> CreateMappingExpression <TSource, TDestination>(MemberList memberList)
        {
            var mappingExp = new MappingExpression <TSource, TDestination>(memberList);

            _typeMapConfigs.Add(mappingExp);

            return(mappingExp);
        }
Example #11
0
        private IMappingExpression <TSource, TDestination> CreateMappingExpression <TSource, TDestination>(TypeMap typeMap)
        {
            var mappingExp = new MappingExpression <TSource, TDestination>(typeMap, ServiceCtor, this);
            var type       = (typeMap.ConfiguredMemberList == MemberList.Destination)
                ? typeof(TDestination)
                : typeof(TSource);

            return(Ignore(mappingExp, type));
        }
Example #12
0
        public TDest Map <TSource, TDest>(TSource source) where TDest : new()
        {
            EnsureMappingConfigured <TSource, TDest>();

            var destination = new TDest();

            MappingExpression <TSource, TDest> .Apply(source, destination);

            return(destination);
        }
        /// <summary>
        /// Creates a map with the specified mapper & metadata
        /// </summary>
        /// <typeparam name="TS"></typeparam>
        /// <typeparam name="TT"></typeparam>
        /// <param name="engine"></param>
        /// <param name="mapper"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static IMappingExpression <TS, TT> CreateMap <TS, TT>(this AbstractFluentMappingEngine engine, ITypeMapper <TS, TT> mapper, TypeMapperMetadata metadata)
        {
            engine.AddMap(mapper, metadata);

            //create enumerable type map for the types automatically if they aren't already IEnumerable
            engine.CreateEnumerableMap <TS, TT>();

            var expression = new MappingExpression <TS, TT>(mapper.MappingContext);

            return(expression);
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleValueCalculator"/> class.
        /// </summary>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="valueType">
        /// The value type.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        public SimpleValueCalculator(MappingExpression valueExpression, Type valueType, ITypeConverter typeConverter)
        {
            if (valueType == null)
                throw new ArgumentNullException("valueType");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            _valueExpression = valueExpression;
            _valueType = valueType;
            _typeConverter = typeConverter;
        }
Example #15
0
        public IMappingBuilder <TSource, TDest> ForMember <TProp>(Expression <Func <TDest, TProp> > destProp, Expression <Func <TSource, TProp> > sourceProp)
        {
            EnsureIsMemberExpression(destProp.Body);
            EnsureIsMemberExpression(sourceProp.Body);

            MappingExpression <TSource, TDest>
            .ReplaceMappingSource(
                (MemberExpression)destProp.Body,
                (MemberExpression)sourceProp.Body);

            return(this);
        }
        /// <summary>
        /// Creates a new mapper with the specified mapper and default metadata with the permitInheritance flag
        /// </summary>
        /// <typeparam name="TS"></typeparam>
        /// <typeparam name="TT"></typeparam>
        /// <param name="engine"></param>
        /// <param name="mapper"></param>
        /// <param name="permitInheritance"></param>
        /// <returns></returns>
        public static IMappingExpression <TS, TT> CreateMap <TS, TT>(this AbstractFluentMappingEngine engine, ITypeMapper <TS, TT> mapper, bool permitInheritance)
        {
            var metadata = new TypeMapperMetadata(typeof(TS), typeof(TT), permitInheritance);

            engine.AddMap(mapper, metadata);

            //create enumerable type map for the types automatically if they aren't already IEnumerable
            engine.CreateEnumerableMap <TS, TT>();

            var expression = new MappingExpression <TS, TT>(mapper.MappingContext);

            return(expression);
        }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArrayValueCalculator"/> class.
        /// </summary>
        /// <param name="elementType">
        /// The element type.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="elementCalculator">
        /// The element calculator.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        public ArrayValueCalculator(Type elementType, MappingExpression valueExpression, IValueCalculator elementCalculator, ITypeConverter typeConverter)
        {
            if (elementType == null)
                throw new ArgumentNullException("elementType");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            _typeConverter = typeConverter;
            _elementType = elementType;
            _valueExpression = valueExpression;
            _elementCalculator = elementCalculator;
        }
Example #18
0
        public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList)
        {
            var map = new MappingExpression(new TypePair(sourceType, destinationType), memberList);

            _typeMapConfigs.Add(map);

            if (sourceType.IsGenericTypeDefinition() || destinationType.IsGenericTypeDefinition())
            {
                _openTypeMapConfigs.Add(map);
            }

            return(map);
        }
Example #19
0
        public TypeMap CreateConventionTypeMap(TypePair types, IConfigurationProvider configurationProvider)
        {
            var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this);

            typeMap.IsConventionMap = true;

            var config = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList);

            config.Configure(typeMap);

            Configure(typeMap, configurationProvider);

            return(typeMap);
        }
Example #20
0
        public IMappingBuilder <TSource, TDest> ForMember <TProp>(Expression <Func <TDest, TProp> > destProp, Action <MappingOptions> optionsSetup)
        {
            EnsureIsMemberExpression(destProp.Body);

            var options = new MappingOptions();

            optionsSetup(options);

            if (options.IsPropIgnored)
            {
                MappingExpression <TSource, TDest> .RemoveMapping((MemberExpression)destProp.Body);
            }

            return(this);
        }
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SampleFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="childMappings">
        /// The child mappings.
        /// </param>
        public SampleFieldMapping(
            PropertyInfo property,
            MappingExpression valueExpression,
            IEnumerable<ISampleValueMapping> childMappings)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            if (childMappings == null)
                throw new ArgumentNullException("childMappings");

            _property = property;
            _valueExpression = valueExpression;
            _childMappings = childMappings.ToArray();
        }
Example #22
0
        public void MinValue_greater_Value_Returns_True()
        {
            // arrange
            var model = new Model2 {
                Number = 11
            };
            var expression = new MappingExpression <Model2>();

            expression.ForMember(m => m.Number, (n, exp) => exp.MinValue(n, 10, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeTrue();
        }
Example #23
0
        TypeMap IProfileConfiguration.ConfigureConventionTypeMap(TypeMapRegistry typeMapRegistry, TypePair types)
        {
            if (!TypeConfigurations.Any(c => c.IsMatch(types)))
            {
                return(null);
            }

            var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this, MemberList.Destination);

            var config = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);

            config.Configure(this, typeMap);

            Configure(typeMapRegistry, typeMap);

            return(typeMap);
        }
Example #24
0
        public void IsEmailAddress_With_Valid_Email_Return_True()
        {
            var model = new ModelSimple {
                Name = "*****@*****.**"
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.IsEmailAddress(n, "{0} != email '{1}'"));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeTrue();
        }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SampleValueMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="isKey">
        /// The is key.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        public SampleValueMapping(PropertyInfo property, MappingExpression valueExpression, bool isKey, ITypeConverter typeConverter)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            if (valueExpression == null)
                throw new ArgumentNullException("valueExpression");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            _typeConverter = typeConverter;

            _property = property;
            _isKey = isKey;
            _valueExpression = valueExpression;
        }
Example #26
0
        public void NotNullOrEmpty_NonEmpty_String_Is_Valid()
        {
            // arrange
            var model = new ModelSimple {
                Name = "a"
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.NotNullOrEmpty(n, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeTrue();
        }
Example #27
0
        public void MinLength_Validator_ExpressionGreaterValue_is_valid()
        {
            // arrange
            var model = new ModelSimple
            {
                Name = "123",
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.MinLength(n, 2, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeTrue();
        }
Example #28
0
        public void NotNullOrEmpty_Empty_String_Is_Not_Valid_Override_Message()
        {
            // arrange
            var model = new ModelSimple();

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.NotNullOrEmpty(n, "Test {0} Test"));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Errors.Should().ContainKey("Name");
            var nameErrors = result.Errors["Name"];

            nameErrors.Count.Should().Be(1);
            nameErrors.Should().Contain(e => e == "Test Name Test");
        }
Example #29
0
        public void MinValue_Too_small_Value_Returns_False_custom_error()
        {
            // arrange
            var model = new Model2 {
                Number = 10
            };
            var expression = new MappingExpression <Model2>();

            expression.ForMember(m => m.Number, (n, exp) => exp.MinValue(n, 11, "Test {0} should be more than {1} {2}"));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("Number");
            var nameErrors = result.Errors["Number"];

            nameErrors.Count.Should().Be(1);
            nameErrors.Should().Contain(e => e == "Test 11 should be more than Number 10");
        }
Example #30
0
        public void MinValue_Too_small_Value_Returns_False()
        {
            // arrange
            var model = new Model2 {
                Number = 10
            };
            var expression = new MappingExpression <Model2>();

            expression.ForMember(m => m.Number, (n, exp) => exp.MinValue(n, 11, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("Number");
            var errors = result.Errors["Number"];

            errors.Count.Should().Be(1);
            errors.Should().Contain(e => e == "Number should be at least 11");
        }
Example #31
0
        public void MaxLength_Validator_Equal_Length_Expression_valid()
        {
            // arrange
            // arrange
            var model = new ModelSimple
            {
                Name = "123",
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.MaxLength(n, 3, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeTrue();
            result.Errors.Count.Should().Be(0);
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleFieldMapping"/> class.
        /// </summary>
        /// <param name="property">
        /// The property.
        /// </param>
        /// <param name="valueExpression">
        /// The value expression.
        /// </param>
        /// <param name="isKey">
        /// Specifies whether this is a key mapping.
        /// </param>
        /// <param name="typeConverter">
        /// The type converter.
        /// </param>
        public SimpleFieldMapping(PropertyInfo property, MappingExpression valueExpression, bool isKey, ITypeConverter typeConverter)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            if (valueExpression == null)
                throw new ArgumentNullException("valueExpression");

            if (typeConverter == null)
                throw new ArgumentNullException("typeConverter");

            _typeConverter = typeConverter;
            _property = property;
            _valueExpression = valueExpression;
            _isKey = isKey;
            _allowLocalizedData = Property.GetCustomAttribute<AllowLocalizedDataAttribute>() != null;

            if (AllowLocalizedData)
            {
                _supportedLocalizations = new List<ILocalizationInfo>(Property.DeclaringType.GetCustomAttributes<LocalizationInfoAttribute>());
            }
        }
Example #33
0
        public void IsEmailAddress_Invalid_Email_Error_Custom_Error()
        {
            // arrange
            var model = new ModelSimple {
                Name = "a.com"
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.IsEmailAddress(n, "{0} != email '{1}'"));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Success.Should().BeFalse();
            result.Errors.Should().ContainKey("Name");
            var nameErrors = result.Errors["Name"];

            nameErrors.Count.Should().Be(1);
            nameErrors.Should().Contain(e => e == "Name != email 'a.com'");
        }
Example #34
0
        public void MinLength_Validator_Expression_Invalid_custom_error()
        {
            // arrange
            var model = new ModelSimple
            {
                Name = "Jon Hawkins",
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.MinLength(n, 4444, "{0} - {1} - {2}"));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Errors.Should().ContainKey("Name");
            var nameErrors = result.Errors["Name"];

            nameErrors.Count.Should().Be(1);
            nameErrors.Should().Contain(e => e == "4444 - Name - Jon Hawkins");
        }
Example #35
0
        public void MaxLength_Validator_Expression_Invalid()
        {
            // arrange
            // arrange
            var model = new ModelSimple
            {
                Name = "Jon Hawkins",
            };

            var expression = new MappingExpression <ModelSimple>();

            expression
            .ForMember(m => m.Name, (n, exp) => exp.MaxLength(n, 3, null));

            // act
            var result = expression.Validate(model, _settings);

            // assert
            result.Errors.Should().ContainKey("Name");
            var nameErrors = result.Errors["Name"];

            nameErrors.Count.Should().Be(1);
            nameErrors.Should().Contain(e => e == "Name should not be longer than 3");
        }
Example #36
0
        private void Configure(TypeMapRegistry typeMapRegistry, TypeMap typeMap)
        {
            foreach (var action in AllTypeMapActions)
            {
                var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList);

                action(typeMap, expression);

                expression.Configure(typeMap);
            }

            foreach (var action in AllPropertyMapActions)
            {
                foreach (var propertyMap in typeMap.GetPropertyMaps())
                {
                    var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestinationProperty, typeMap.SourceType);

                    action(propertyMap, memberExpression);

                    memberExpression.Configure(typeMap);
                }
            }

            ApplyBaseMaps(typeMapRegistry, typeMap, typeMap);
            ApplyDerivedMaps(typeMapRegistry, typeMap, typeMap);
        }
Example #37
0
        private void Seal(IConfiguration configuration)
        {
            ServiceCtor = configuration.ServiceCtor;
            AllowNullDestinationValues = configuration.AllowNullDestinationValues;
            AllowNullCollections       = configuration.AllowNullCollections;

            var derivedMaps     = new List <Tuple <TypePair, TypeMap> >();
            var redirectedTypes = new List <Tuple <TypePair, TypePair> >();

            foreach (var profile in configuration.Profiles.Cast <IProfileConfiguration>())
            {
                profile.Register(TypeMapRegistry);
            }

            foreach (var action in configuration.AllTypeMapActions)
            {
                foreach (var typeMap in TypeMapRegistry.TypeMaps)
                {
                    var expression = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);

                    action(typeMap, expression);

                    expression.Configure(typeMap.Profile, typeMap);
                }
            }

            foreach (var action in configuration.AllPropertyMapActions)
            {
                foreach (var typeMap in TypeMapRegistry.TypeMaps)
                {
                    foreach (var propertyMap in typeMap.GetPropertyMaps())
                    {
                        var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestMember, typeMap.SourceType);

                        action(propertyMap, memberExpression);

                        memberExpression.Configure(typeMap);
                    }
                }
            }

            foreach (var profile in configuration.Profiles.Cast <IProfileConfiguration>())
            {
                profile.Configure(TypeMapRegistry);
            }

            foreach (var typeMap in TypeMapRegistry.TypeMaps)
            {
                _typeMapPlanCache[typeMap.TypePair] = typeMap;

                if (typeMap.DestinationTypeOverride != null)
                {
                    redirectedTypes.Add(Tuple.Create(typeMap.TypePair, new TypePair(typeMap.SourceType, typeMap.DestinationTypeOverride)));
                }
                if (typeMap.SourceType.IsNullableType())
                {
                    var nonNullableTypes = new TypePair(Nullable.GetUnderlyingType(typeMap.SourceType), typeMap.DestinationType);
                    redirectedTypes.Add(Tuple.Create(nonNullableTypes, typeMap.TypePair));
                }
                derivedMaps.AddRange(GetDerivedTypeMaps(typeMap).Select(derivedMap => Tuple.Create(new TypePair(derivedMap.SourceType, typeMap.DestinationType), derivedMap)));
            }
            foreach (var redirectedType in redirectedTypes)
            {
                var derivedMap = FindTypeMapFor(redirectedType.Item2);
                if (derivedMap != null)
                {
                    _typeMapPlanCache[redirectedType.Item1] = derivedMap;
                }
            }
            foreach (var derivedMap in derivedMaps.Where(derivedMap => !_typeMapPlanCache.ContainsKey(derivedMap.Item1)))
            {
                _typeMapPlanCache[derivedMap.Item1] = derivedMap.Item2;
            }

            foreach (var typeMap in TypeMapRegistry.TypeMaps)
            {
                typeMap.Seal(TypeMapRegistry, this);
            }
        }
Example #38
0
        private IMappingExpression CreateMappingExpression(TypeMap typeMap, Type destinationType)
        {
            var mappingExp = new MappingExpression(typeMap, ServiceCtor, this);

            return((IMappingExpression)Ignore(mappingExp, destinationType));
        }
Example #39
0
 public MappingBuilder()
 {
     MappingExpression <TSource, TDest> .Create();
 }
Example #40
0
        public TypeMap ConfigureConventionTypeMap(TypeMapRegistry typeMapRegistry, TypePair types)
        {
            if (!TypeConfigurations.Any(c => c.IsMatch(types)))
                return null;

            var typeMap = _typeMapFactory.CreateTypeMap(types.SourceType, types.DestinationType, this, MemberList.Destination);

            var config = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList);

            config.Configure(typeMap);

            Configure(typeMapRegistry, typeMap);

            return typeMap;
        }
        private static MappingInfo GetMappingInfo(SpreadsheetDocument doc, IEnumerable <EvaluationSource> externalSources)
        {
            var    templateFieldExpressions = new List <MappingExpression>();
            var    worksheet       = GetFirstWorkSheet(doc);
            var    stringTablePart = GetOrCreatePart <SharedStringTablePart>(doc);
            var    stylesPart      = GetOrCreatePart <WorkbookStylesPart>(doc);
            var    rowIndex        = 3U;
            string name;

            do
            {
                name = GetCellValue(GetCell(worksheet, $"A{rowIndex}"), stringTablePart);
                if (!string.IsNullOrEmpty(name))
                {
                    var formulaCell             = GetCell(worksheet, $"F{rowIndex}");
                    var formulaCellFormat       = GetCellFormat(formulaCell, stylesPart);
                    var templateFieldExpression = new MappingExpression()
                    {
                        Name          = name,
                        Parent        = GetCellValue(GetCell(worksheet, $"B{rowIndex}"), stringTablePart),
                        IsCollection  = GetCellValueAsBoolean(GetCell(worksheet, $"C{rowIndex}"), stringTablePart),
                        Content       = GetCellValue(GetCell(worksheet, $"D{rowIndex}"), stringTablePart),
                        Expression    = GetCellFormula(formulaCell),
                        Cell          = $"F{rowIndex}",
                        NumFormatId   = formulaCellFormat.Item1,
                        NumFormatCode = formulaCellFormat.Item2
                    };
                    templateFieldExpressions.Add(templateFieldExpression);
                    ++rowIndex;
                }
            } while (!string.IsNullOrEmpty(name));

            templateFieldExpressions = ReorderExpressionsWithCalcChain(doc.WorkbookPart, templateFieldExpressions);

            var sources = new List <EvaluationSource>();

            if (externalSources != null)
            {
                sources.AddRange(externalSources);
            }
            rowIndex = 3U;
            do
            {
                name = GetCellValue(GetCell(worksheet, $"M{rowIndex}"), stringTablePart);
                if (!string.IsNullOrEmpty(name))
                {
                    var existing = sources.FirstOrDefault(o => string.Equals(name, o.Name, StringComparison.InvariantCultureIgnoreCase));
                    if (existing != null)
                    {
                        existing.Cell = $"N{rowIndex}";
                    }
                    else
                    {
                        var payload = GetCellValue(GetCell(worksheet, $"N{rowIndex}"), stringTablePart);
                        sources.Add(new EvaluationSource()
                        {
                            Name    = name,
                            Cell    = $"N{rowIndex}",
                            Payload = JObject.Parse(payload)
                        });
                    }
                    ++rowIndex;
                }
            } while (!string.IsNullOrEmpty(name));
            return(new MappingInfo()
            {
                Expressions = templateFieldExpressions,
                Sources = sources
            });
        }