Ejemplo n.º 1
0
        public void Add_single_feature_with_reverse()
        {
            var featureA = new MappingExpressionFeatureA(1);
            var config   = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Source, Dest>()
                .SetFeature(featureA)
                .ReverseMap();
            });

            var typeMap = config.FindTypeMapFor <Source, Dest>();

            typeMap.Features.Count().ShouldBe(1);

            var typeMapReverse = config.FindTypeMapFor <Dest, Source>();

            typeMapReverse.Features.Count().ShouldBe(0);

            Validate <TypeMapFeatureA>(featureA);

            void Validate <TFeature>(MappingExpressionFeatureBase feature)
                where TFeature : TypeMapFeatureBase
            {
                feature.ConfigureTypeMaps.ShouldBeOfLength(1);
                feature.ReverseExecutedCount.ShouldBe(1);

                var typeMapFeature = typeMap.Features.Get <TFeature>();

                typeMapFeature.ShouldNotBeNull();
                typeMapFeature.Value.ShouldBe(feature.Value);
                typeMapFeature.SealedCount.ShouldBe(1);
            }
        }
Ejemplo n.º 2
0
        public void Adding_same_feature_multiple_times_should_replace_eachother()
        {
            var featureA = new MappingExpressionFeatureA(1);
            var featureB = new MappingExpressionFeatureB(1);
            var config   = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Source, Dest>()
                .AddOrUpdateFeature(new MappingExpressionFeatureA(3))
                .AddOrUpdateFeature(new MappingExpressionFeatureA(2))
                .AddOrUpdateFeature(featureA)
                .AddOrUpdateFeature(new MappingExpressionFeatureB(3))
                .AddOrUpdateFeature(new MappingExpressionFeatureB(2))
                .AddOrUpdateFeature(featureB)
                .ReverseMap();
            });


            var typeMap = config.FindTypeMapFor <Source, Dest>();

            typeMap.Features.Count().ShouldBe(2);

            var typeMapReverse = config.FindTypeMapFor <Dest, Source>();

            typeMapReverse.Features.Count().ShouldBe(2);

            Validate(featureA);
            Validate(featureB);

            void Validate(MappingExpressionFeatureBase feature)
            {
                feature.ConfigureTypeMaps.ShouldBeOfLength(1);
                feature.ReverseMaps.ShouldBeOfLength(1);
            }
        }
Ejemplo n.º 3
0
        static public void AssertConfigurationIsValid <TSource, TDestination>()
        {
            TypeMap map = MapperConfiguration.FindTypeMapFor <TSource, TDestination>();

            NUnit.Framework.Assert.IsNotNull(map, "Could not find type map from {0} to {1}", typeof(TSource), typeof(TDestination));
            MapperConfiguration.AssertConfigurationIsValid(map);
        }
Ejemplo n.º 4
0
        public void Adding_same_feature_should_replace_eachother()
        {
            var featureA = new MappingExpressionFeatureA(1);
            var featureB = new MappingExpressionFeatureB(2);
            var config   = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Source, Dest>()
                .SetFeature(new MappingExpressionFeatureA(3))
                .SetFeature(new MappingExpressionFeatureA(2))
                .SetFeature(featureA)
                .SetFeature(new MappingExpressionFeatureB(3))
                .SetFeature(new MappingExpressionFeatureB(2))
                .SetFeature(featureB)
                .ReverseMap();
            });


            var typeMap = config.FindTypeMapFor <Source, Dest>();

            typeMap.Features.Count().ShouldBe(2);

            var typeMapReverse = config.ResolveTypeMap(typeof(Dest), typeof(Source));

            typeMapReverse.Features.Count().ShouldBe(0);

            Validate(featureA);
            Validate(featureB);

            void Validate(MappingExpressionFeatureBase feature)
            {
                feature.ConfigureTypeMaps.ShouldBeOfLength(1);
                feature.ReverseExecutedCount.ShouldBe(1);
            }
        }
Ejemplo n.º 5
0
 public TwoWayMapper(Action <IMapperConfigurationExpression> automapperExpression)
     : base(automapperExpression)
 {
     if (MapperConfiguration.FindTypeMapFor <TModel, TEntity>() == null)
     {
         throw new Exception($"Missing type map for {typeof(TModel).Name} -> {typeof(TEntity).Name}");
     }
 }
Ejemplo n.º 6
0
        public void Add_multiple_features_with_reverse_overriden()
        {
            var featureA          = new MappingExpressionFeatureA(1);
            var featureB          = new MappingExpressionFeatureB(2);
            var overridenFeatureB = new MappingExpressionFeatureB(10);
            var config            = new MapperConfiguration(
                cfg =>
            {
                cfg.CreateMap <Source, Dest>()
                .SetFeature(featureA)
                .SetFeature(featureB)
                .ReverseMap()
                .SetFeature(overridenFeatureB);
            }
                );

            var typeMap = config.FindTypeMapFor <Source, Dest>();

            typeMap.Features.Count().ShouldBe(2);

            var typeMapReverse = config.FindTypeMapFor <Dest, Source>();

            typeMapReverse.Features.Count().ShouldBe(2);

            Validate <TypeMapFeatureA>(featureA, typeMap);
            Validate <TypeMapFeatureB>(featureB, typeMap);
            Validate <TypeMapFeatureA>(featureA, typeMapReverse, value: featureA.Value + 1);
            Validate <TypeMapFeatureB>(overridenFeatureB, typeMapReverse, 0);

            void Validate <TFeature>(
                MappingExpressionFeatureBase feature,
                TypeMap map,
                int reverseExecutedCount = 1,
                int?value = null
                ) where TFeature : TypeMapFeatureBase
            {
                feature.ConfigureTypeMaps.ShouldBeOfLength(1);
                feature.ReverseMaps.ShouldBeOfLength(reverseExecutedCount);

                var typeMapFeature = map.Features.Get <TFeature>();

                typeMapFeature.ShouldNotBeNull();
                typeMapFeature.Value.ShouldBe(value ?? feature.Value);
                typeMapFeature.SealedCount.ShouldBe(1);
            }
        }
Ejemplo n.º 7
0
        public void Should_set_inline_accordingly()
        {
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.Advanced.MaxExecutionPlanDepth = 2;
                cfg.CreateMap <Source, Destination>();
                cfg.CreateMap <Source1, Destination1>();
                cfg.CreateMap <Source2, Destination2>();
                cfg.CreateMap <Source3, Destination3>();
                cfg.CreateMap <Source4, Destination4>();
                cfg.CreateMap <Source5, Destination5>();
                cfg.CreateMap <Source6, Destination6>();
            });
            TypeMap map;

            map = configuration.FindTypeMapFor <Source, Destination>();
            map.GetPropertyMaps()[0].Inline.ShouldBeTrue();
            map = configuration.FindTypeMapFor <Source1, Destination1>();
            map.GetPropertyMaps()[0].Inline.ShouldBeTrue();
            map = configuration.FindTypeMapFor <Source2, Destination2>();
            map.GetPropertyMaps()[0].Inline.ShouldBeFalse();
            map = configuration.FindTypeMapFor <Source3, Destination3>();
            map.GetPropertyMaps()[0].Inline.ShouldBeTrue();
            map = configuration.FindTypeMapFor <Source4, Destination4>();
            map.GetPropertyMaps()[0].Inline.ShouldBeTrue();
            map = configuration.FindTypeMapFor <Source5, Destination5>();
            map.GetPropertyMaps()[0].Inline.ShouldBeFalse();
        }
        private static void AddAutoMapperClasses(this IServiceCollection services, IEnumerable <Assembly> assembliesToScan)
        {
            assembliesToScan = assembliesToScan as Assembly[] ?? assembliesToScan.ToArray();

            var allTypes = assembliesToScan.SelectMany(a => { try { return(a.ExportedTypes); } catch { return(new List <System.Type>()); } }).ToArray();

            var profiles =
                allTypes
                .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
                .Where(t => !t.GetTypeInfo().IsAbstract);
            var mapperConfigurationExpression = new MapperConfigurationExpression();

            //create maps based on existing profiles
            foreach (var profile in profiles)
            {
                mapperConfigurationExpression.AddProfile(profile);
            }
            var config = new MapperConfiguration(mapperConfigurationExpression);
            //create maps based on generic business services
            var businessServices =
                allTypes
                .Where(t => t.GetInterfaces().Contains(typeof(_IBusinessService)))
                .Where(t => !t.GetTypeInfo().IsAbstract);

            foreach (var businessService in businessServices)
            {
                foreach (Type SourceType in businessService.GetTypeInfo().BaseType.GenericTypeArguments)
                {
                    foreach (Type DestinationType in businessService.GetTypeInfo().BaseType.GenericTypeArguments)
                    {
                        if (config.FindTypeMapFor(SourceType, DestinationType) == null)
                        {
                            mapperConfigurationExpression.CreateProfile(SourceType.FullName.Replace('.', '_') + '_' + DestinationType.FullName.Replace('.', '_'), (profileConfig) =>
                            {
                                profileConfig.CreateMap(SourceType, DestinationType);
                            });
                        }
                        else
                        {
                        }
                    }
                }
            }
            //other configuration
            //mapperConfigurationExpression.CreateMissingTypeMaps = true;
            //mapperConfigurationExpression.ForAllMaps((a, b) => {
            //   foreach(prop)
            //});
            config = new MapperConfiguration(mapperConfigurationExpression);
            services.AddSingleton(sp => config.CreateMapper());
        }
Ejemplo n.º 9
0
        public static PropertyInfo[] GetUnmappedDestinationMembers <TSource, TDest>(MapperConfiguration config)
        {
            TypeMap typeMap    = config.FindTypeMapFor <TSource, TDest>();
            var     memberMaps = typeMap.MemberMaps.Where(m => !m.Ignored);

            Func <IMemberMap, string> extractDestinationMemberName = m =>
            {
                string name = m.DestinationName;
                return(name);
            };
            var mappedProperties   = memberMaps.Select(m => extractDestinationMemberName(m)).Where(n => n != null).ToArray();
            var unmappedProperties = typeof(TDest).GetProperties().Where(p => !mappedProperties.Contains(p.Name)).ToArray();

            return(unmappedProperties);
        }
Ejemplo n.º 10
0
        public static PropertyInfo[] GetUnmappedSourceMembers <TSource, TDest>(MapperConfiguration config)
        {
            TypeMap typeMap    = config.FindTypeMapFor <TSource, TDest>();
            var     memberMaps = typeMap.MemberMaps.Where(m => !m.Ignored);

            Func <IMemberMap, string> extractSourceMemberName = m =>
            {
                string name = m.SourceMember?.Name;
                if (name == null)
                {
                    name = ((MemberExpression)m.ValueResolverConfig?.SourceMember?.Body)?.Member.Name;
                }
                return(name);
            };
            var mappedProperties   = memberMaps.Select(m => extractSourceMemberName(m)).Where(n => n != null).ToArray();
            var unmappedProperties = typeof(TSource).GetProperties().Where(p => !mappedProperties.Contains(p.Name)).ToArray();

            return(unmappedProperties);
        }
Ejemplo n.º 11
0
        public void Add_multiple_features()
        {
            var featureA = new MappingExpressionFeatureA(1);
            var featureB = new MappingExpressionFeatureB(2);
            var config   = new MapperConfiguration(cfg =>
            {
                cfg.CreateMissingTypeMaps = true;
                cfg.CreateMap <Source, Dest>()
                .SetFeature(featureA)
                .SetFeature(featureB);
            });


            var typeMap = config.FindTypeMapFor <Source, Dest>();

            typeMap.Features.Count().ShouldBe(2);

            var typeMapReverse = config.ResolveTypeMap(typeof(Dest), typeof(Source));

            typeMapReverse.Features.Count().ShouldBe(0);

            Validate <TypeMapFeatureA>(featureA);
            Validate <TypeMapFeatureB>(featureB);

            void Validate <TFeature>(MappingExpressionFeatureBase feature)
                where TFeature : TypeMapFeatureBase
            {
                feature.ConfigureTypeMaps.ShouldBeOfLength(1);
                feature.ReverseExecutedCount.ShouldBe(0);

                var typeMapFeature = typeMap.Features.Get <TFeature>();

                typeMapFeature.ShouldNotBeNull();
                typeMapFeature.Value.ShouldBe(feature.Value);
                typeMapFeature.SealedCount.ShouldBe(1);
            }
        }
Ejemplo n.º 12
0
        public static object ConvertToVersion(object source, string apiVersion)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var type = source.GetType();
            var attr = GetKubernetesEntityAttribute(type);

            if (attr.ApiVersion == apiVersion)
            {
                return(source);
            }

            if (!KindVersionsMap.TryGetValue(attr.Kind, out var kindVersions))
            {
                throw new InvalidOperationException($"Version converter does not have any registered types for Kind `{attr.Kind}`");
            }

            if (!kindVersions.TryGetValue(apiVersion, out var targetType) || !kindVersions.TryGetValue(attr.ApiVersion, out var sourceType) || MapperConfiguration.FindTypeMapFor(sourceType, targetType) == null)
            {
                throw new InvalidOperationException($"There is no conversion mapping registered for Kind `{attr.Kind}` from ApiVersion {attr.ApiVersion} to {apiVersion}");
            }

            return(Mapper.Map(source, sourceType, targetType));
        }
Ejemplo n.º 13
0
        public void MappingConfigureTests()
        {
            var configure = new MapperConfiguration(cfg => cfg.CreateMapper <Source, Destination>());

            Assert.IsNotNull(configure.FindTypeMapFor <Source, Destination>());
        }
Ejemplo n.º 14
0
        public void Should_find_configured_type_map_when_two_types_are_configured()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap <Source, Destination>());

            config.FindTypeMapFor <Source, Destination>().ShouldNotBeNull();
        }
Ejemplo n.º 15
0
        public void Should_find_configured_type_map_when_two_types_are_configured()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>());

            config.FindTypeMapFor<Source, Destination>().ShouldNotBeNull();
        }
Ejemplo n.º 16
0
        public Dictionary <string, MapExpression <TEntity> > GetModelMappings <TEntity, TViewModel>(Dictionary <string, MapExpression <TEntity> > mappings = null)
        {
            if (SameTypes <TEntity, TViewModel>())
            {
                return(null);
            }

            var map = _mapperConfiguration?.FindTypeMapFor <TEntity, TViewModel>();

            if (map == null)
            {
                return(null);
            }

            mappings = mappings ?? new Dictionary <string, MapExpression <TEntity> >();

            // Custom expressions because they do not map field to field
            foreach (var propertyMap in map.GetPropertyMaps().Where(pm => pm.CustomExpression != null))
            {
                // Get the linq expression body
                string body = propertyMap.CustomExpression.Body.ToString();

                // Get the item tag
                string tag = propertyMap.CustomExpression.Parameters[0].Name;

                string destination = body.Replace($"{tag}.", string.Empty);
                string source      = propertyMap.DestinationProperty.Name;

                var customExpression = new MapExpression <TEntity>
                {
                    Path       = destination,
                    Expression = propertyMap.CustomExpression.ToTypedExpression <TEntity>()
                };

                if (!mappings.ContainsKey(source))
                {
                    mappings.Add(source, customExpression);
                }
            }

            foreach (var propertyMap in map.GetPropertyMaps().Where(pm => pm.CustomExpression == null))
            {
                var customResolver = propertyMap.ValueResolverConfig?.Instance;
                if (customResolver is IKendoGridExValueResolver <TEntity> )
                {
                    string source = propertyMap.DestinationProperty.Name;

                    IKendoGridExValueResolver <TEntity> kendoResolver = customResolver as IKendoGridExValueResolver <TEntity>;
                    string destination = kendoResolver.DestinationProperty;
                    var    expression  = propertyMap.CustomExpression != null?propertyMap.CustomExpression.ToTypedExpression <TEntity>() : kendoResolver.Expression;

                    var customExpression = new MapExpression <TEntity>
                    {
                        Path       = destination,
                        Expression = expression
                    };

                    if (!mappings.ContainsKey(source))
                    {
                        mappings.Add(source, customExpression);
                    }
                }
            }

            return(mappings);
        }