protected override string CreateMessage(Type dtoType)
        {
            var requestObj   = AutoMappingUtils.PopulateWith(Activator.CreateInstance(dtoType));
            var xml          = DataContractSerializer.Instance.Parse(requestObj, true);
            var soapEnvelope =
                $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
    <soap:Body>

{xml}

    </soap:Body>
</soap:Envelope>";

            return(soapEnvelope);
        }
        public void Populate_From_Properties_With_Attribute()
        {
            var originalToObj = ModelWithOnlyStringFields.Create("id-1");
            var toObj         = ModelWithOnlyStringFields.Create("id-1");
            var fromObj       = ModelWithOnlyStringFields.Create("id-2");

            AutoMappingUtils.PopulateFromPropertiesWithAttribute(toObj, fromObj,
                                                                 typeof(IndexAttribute));

            Assert.That(toObj.Id, Is.EqualTo(originalToObj.Id));
            Assert.That(toObj.AlbumId, Is.EqualTo(originalToObj.AlbumId));

            //Properties with IndexAttribute
            Assert.That(toObj.Name, Is.EqualTo(fromObj.Name));
            Assert.That(toObj.AlbumName, Is.EqualTo(fromObj.AlbumName));
        }
        public void Populate_Same_Objects()
        {
            var toObj   = ModelWithFieldsOfDifferentTypes.Create(1);
            var fromObj = ModelWithFieldsOfDifferentTypes.Create(2);

            var obj3 = AutoMappingUtils.PopulateWith(toObj, fromObj);

            Assert.IsTrue(obj3 == toObj);
            Assert.That(obj3.Bool, Is.EqualTo(fromObj.Bool));
            Assert.That(obj3.DateTime, Is.EqualTo(fromObj.DateTime));
            Assert.That(obj3.Double, Is.EqualTo(fromObj.Double));
            Assert.That(obj3.Guid, Is.EqualTo(fromObj.Guid));
            Assert.That(obj3.Id, Is.EqualTo(fromObj.Id));
            Assert.That(obj3.LongId, Is.EqualTo(fromObj.LongId));
            Assert.That(obj3.Name, Is.EqualTo(fromObj.Name));
        }
Example #4
0
        public void Should_Convert_LocalDate_To_DateTime()
        {
            MapperConfig.RegisterLocalDateToDateTimeConverter();

            var map = new Dictionary <string, object>
            {
                { nameof(EntityWithClrTypes.DateValue), new LocalDate(2019, 1, 12) }
            };

            var entity = ValueMapper.MapValue <EntityWithClrTypes>(map);

            entity.DateValue.Year.Should().Be(2019);
            entity.DateValue.Month.Should().Be(1);
            entity.DateValue.Day.Should().Be(12);

            AutoMappingUtils.Reset();
        }
        public void Should_Convert_LocalDate_To_DateTime()
        {
            Neo4jMapperConfig.RegisterLocalDateToDateTimeConverter();

            var map = new Dictionary <string, object>
            {
                { nameof(EntityWithClrTypes.DateValue), new LocalDate(2019, 1, 12) }
            };

            var entity = ValueMapper.MapValue <EntityWithClrTypes>(map);

            Assert.AreEqual(2019, entity.DateValue.Year);
            Assert.AreEqual(1, entity.DateValue.Month);
            Assert.AreEqual(12, entity.DateValue.Day);

            AutoMappingUtils.Reset();
        }
        private void AssertLocalTimeConvertersAreRegistered()
        {
            var localTimeToTimeSpanConverter = AutoMappingUtils.GetConverter(typeof(LocalTime), typeof(TimeSpan));

            localTimeToTimeSpanConverter.Should().NotBeNull();

            var localTimeToNullableTimeSpanConverter = AutoMappingUtils.GetConverter(typeof(LocalTime), typeof(TimeSpan?));

            localTimeToNullableTimeSpanConverter.Should().NotBeNull();

            var timeSpanToLocalTimeConverter = AutoMappingUtils.GetConverter(typeof(TimeSpan), typeof(LocalTime));

            timeSpanToLocalTimeConverter.Should().NotBeNull();

            var nullableTimeSpanToLocalTimeConverter = AutoMappingUtils.GetConverter(typeof(TimeSpan?), typeof(LocalTime));

            nullableTimeSpanToLocalTimeConverter.Should().NotBeNull();
        }
        private void AssertLocalDateConvertersAreRegistered()
        {
            var localDateToDateTimeConverter = AutoMappingUtils.GetConverter(typeof(LocalDate), typeof(DateTime));

            localDateToDateTimeConverter.Should().NotBeNull();

            var localDateToNullableDateTimeConverter = AutoMappingUtils.GetConverter(typeof(LocalDate), typeof(DateTime?));

            localDateToNullableDateTimeConverter.Should().NotBeNull();

            var dateTimeToLocalDateTimeConverter = AutoMappingUtils.GetConverter(typeof(DateTime), typeof(LocalDate));

            dateTimeToLocalDateTimeConverter.Should().NotBeNull();

            var nullableDateTimeToLocalDateTimeConverter = AutoMappingUtils.GetConverter(typeof(DateTime?), typeof(LocalDate));

            nullableDateTimeToLocalDateTimeConverter.Should().NotBeNull();
        }
        private void AssertZonedDateTimeConvertersAreRegistered()
        {
            var zonedDateTimeToDateTimeOffsetConverter = AutoMappingUtils.GetConverter(typeof(ZonedDateTime), typeof(DateTimeOffset));

            zonedDateTimeToDateTimeOffsetConverter.Should().NotBeNull();

            var zonedDateTimeToNullableDateTimeOffsetConverter = AutoMappingUtils.GetConverter(typeof(ZonedDateTime), typeof(DateTimeOffset?));

            zonedDateTimeToNullableDateTimeOffsetConverter.Should().NotBeNull();

            var dateTimeOffsetToZonedDateTimeConverter = AutoMappingUtils.GetConverter(typeof(DateTimeOffset), typeof(ZonedDateTime));

            dateTimeOffsetToZonedDateTimeConverter.Should().NotBeNull();

            var nullableDateTimeOffsetToZonedDateTimeConverter = AutoMappingUtils.GetConverter(typeof(DateTimeOffset?), typeof(ZonedDateTime));

            nullableDateTimeOffsetToZonedDateTimeConverter.Should().NotBeNull();
        }
Example #9
0
        public void Should_Convert_Enum_Type_To_String()
        {
            var entity = new MovieWithType
            {
                Title     = "Top Gun",
                Released  = 1986,
                Tagline   = "As students at the United States Navy's elite fighter weapons school compete to be best in the class, one daring young pilot learns a few things from a civilian instructor that are not taught in the classroom.",
                MovieType = MovieType.Action
            };

            try
            {
                AutoMapping.RegisterConverter <MovieWithType, Dictionary <string, object> >(movieWithType =>
                {
                    var dictionary = movieWithType.ConvertTo <Dictionary <string, object> >(true);
                    dictionary[nameof(movieWithType.MovieType)] = movieWithType.MovieType.ToString();
                    return(dictionary);
                });

                var parameter = entity.ToParameterMap("entity");

                Assert.AreEqual("entity", parameter.Key);
                Assert.AreEqual(4, parameter.Value.Count);

                Assert.IsTrue(parameter.Value.ContainsKey("Title"));
                var titleValue = parameter.Value["Title"];
                Assert.IsInstanceOf <string>(titleValue);
                Assert.AreEqual("Top Gun", titleValue);

                Assert.IsTrue(parameter.Value.ContainsKey("Released"));
                var releasedValue = parameter.Value["Released"];
                Assert.IsInstanceOf <int>(releasedValue);
                Assert.AreEqual(1986, releasedValue);

                Assert.IsTrue(parameter.Value.ContainsKey("MovieType"));
                var movieTypeValue = parameter.Value["MovieType"];
                Assert.IsInstanceOf <string>(movieTypeValue);
                Assert.AreEqual("Action", movieTypeValue);
            }
            finally
            {
                AutoMappingUtils.Reset();
            }
        }
        public void Should_Not_Throw_Exception_When_Multiple_Same_Type_CustomTypeConverters_Found()
        {
            AutoMappingUtils.RegisterConverter((DateTimeOffset from) => new WrappedDateTimeOffset(from));

            var personWithWrappedDateOfBirth = new PersonWithWrappedDateOfBirth
            {
                DateOfBirth = new WrappedDateTimeOffset(
                    new DateTimeOffset(1971, 3, 23, 4, 30, 0, TimeSpan.Zero))
            };

            var personWithDoB = personWithWrappedDateOfBirth.ConvertTo <PersonWithDateOfBirth>();

            // Object returned but mapping failed
            Assert.That(personWithDoB.FirstName, Is.Null);
            Assert.That(personWithDoB.LastName, Is.Null);
            Assert.That(personWithDoB.DateOfBirth, Is.EqualTo(DateTimeOffset.MinValue));

            AutoMappingUtils.Reset();
        }
Example #11
0
        public void Can_Convert_POCO_collections_with_custom_Converter()
        {
            AutoMapping.RegisterConverter((User from) => {
                var to        = from.ConvertTo <UserDto>(skipConverters: true); // avoid infinite recursion
                to.FirstName += "!";
                to.LastName  += "!";
                return(to);
            });
            AutoMapping.RegisterConverter((Car from) => $"{from.Name} ({from.Age})");

            var user = new User {
                FirstName = "John",
                LastName  = "Doe",
                Car       = new Car {
                    Name = "BMW X6", Age = 3
                }
            };
            var users = new UsersData {
                Id        = 1,
                User      = user,
                UsersList = { user },
                UsersMap  = { { 1, user } }
            };

            var dtoUsers = users.ConvertTo <UsersDto>();

            Assert.That(dtoUsers.Id, Is.EqualTo(users.Id));

            void AssertUser(UserDto userDto)
            {
                Assert.That(userDto.FirstName, Is.EqualTo(user.FirstName + "!"));
                Assert.That(userDto.LastName, Is.EqualTo(user.LastName + "!"));
                Assert.That(userDto.Car, Is.EqualTo($"{user.Car.Name} ({user.Car.Age})"));
            }

            AssertUser(user.ConvertTo <UserDto>());
            AssertUser(dtoUsers.User);
            AssertUser(dtoUsers.UsersList[0]);
            AssertUser(dtoUsers.UsersMap[1]);

            AutoMappingUtils.Reset();
        }
Example #12
0
        public void AddMatch(string name, AssignmentMember readMember, AssignmentMember writeMember)
        {
            if (AutoMappingUtils.ShouldIgnoreMapping(readMember.Type, writeMember.Type))
            {
                return;
            }

            // Ignore mapping collections if Element Types are ignored
            if (typeof(IEnumerable).IsAssignableFrom(readMember.Type) && typeof(IEnumerable).IsAssignableFrom(writeMember.Type))
            {
                var fromGenericDef = readMember.Type.GetTypeWithGenericTypeDefinitionOf(typeof(IDictionary <,>));
                var toGenericDef   = writeMember.Type.GetTypeWithGenericTypeDefinitionOf(typeof(IDictionary <,>));
                if (fromGenericDef != null && toGenericDef != null)
                {
                    // Check if to/from Key or Value Types are ignored
                    var fromArgs = fromGenericDef.GetGenericArguments();
                    var toArgs   = toGenericDef.GetGenericArguments();
                    if (AutoMappingUtils.ShouldIgnoreMapping(fromArgs[0], toArgs[0]))
                    {
                        return;
                    }
                    if (AutoMappingUtils.ShouldIgnoreMapping(fromArgs[1], toArgs[1]))
                    {
                        return;
                    }
                }
                else if (readMember.Type != typeof(string) && writeMember.Type != typeof(string))
                {
                    var elFromType = readMember.Type.GetCollectionType();
                    var elToType   = writeMember.Type.GetCollectionType();

                    if (AutoMappingUtils.ShouldIgnoreMapping(elFromType, elToType))
                    {
                        return;
                    }
                }
            }

            this.AssignmentMemberMap[name] = new AssignmentEntry(name, readMember, writeMember);
        }
Example #13
0
        protected override string CreateMessage(Type dtoType)
        {
            try
            {
                var requestObj = AutoMappingUtils.PopulateWith(Activator.CreateInstance(dtoType));

                using var ms = MemoryStreamFactory.GetStream();
                HostContext.ContentTypes.SerializeToStreamAsync(
                    new BasicRequest {
                    ContentType = this.ContentType
                }, requestObj, ms).Wait();

                return(ms.ReadToEnd());
            }
            catch (Exception ex)
            {
                var error = $"Error serializing type '{dtoType.GetOperationName()}' with custom format '{this.ContentFormat}'";
                Log.Error(error, ex);

                return($"{{Unable to show example output for type '{dtoType.GetOperationName()}' using the custom '{this.ContentFormat}' filter}}{ex.Message}");
            }
        }
Example #14
0
        public static void PopulateSession(this IAuthSession session, IUserAuth userAuth, List <IAuthTokens> authTokens = null)
        {
            if (userAuth == null)
            {
                return;
            }

            var holdSessionId = session.Id;

            session.PopulateWith(userAuth);
            session.Id              = holdSessionId;
            session.UserAuthId      = session.UserAuthId ?? userAuth.Id.ToString(CultureInfo.InvariantCulture);
            session.IsAuthenticated = true;
            if (authTokens != null)
            {
                session.ProviderOAuthAccess = authTokens;
            }

            var existingPopulator = AutoMappingUtils.GetPopulator(typeof(IAuthSession), typeof(IUserAuth));

            existingPopulator?.Invoke(session, userAuth);
        }
Example #15
0
 public void OneTimeTearDown()
 {
     AutoMappingUtils.Reset();
 }
Example #16
0
        public void Can_create_Dictionary_default_value()
        {
            var obj = (Dictionary <string, ClassWithEnum>)AutoMappingUtils.CreateDefaultValue(typeof(Dictionary <string, ClassWithEnum>), new Dictionary <Type, int>());

            Assert.That(obj, Is.Not.Null);
        }
Example #17
0
        public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType)
        {
            if (fromType == toType)
            {
                return(null);
            }

            var converter = AutoMappingUtils.GetConverter(fromType, toType);

            if (converter != null)
            {
                return(converter);
            }

            if (fromType == typeof(string))
            {
                return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType));
            }

            if (toType == typeof(string))
            {
                return(o => TypeSerializer.SerializeToString(o).StripQuotes());
            }

            var underlyingToType   = Nullable.GetUnderlyingType(toType) ?? toType;
            var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType;

            if (underlyingToType.IsEnum)
            {
                if (underlyingFromType.IsEnum || fromType == typeof(string))
                {
                    return(fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true));
                }

                if (underlyingFromType.IsIntegerType())
                {
                    return(fromValue => Enum.ToObject(underlyingToType, fromValue));
                }
            }
            else if (underlyingFromType.IsEnum)
            {
                if (underlyingToType.IsIntegerType())
                {
                    return(fromValue => Convert.ChangeType(fromValue, underlyingToType, null));
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(fromType) && underlyingToType != typeof(string))
            {
                return(fromValue => AutoMappingUtils.TryConvertCollections(fromType, underlyingToType, fromValue));
            }
            else if (underlyingToType.IsValueType)
            {
                return(fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType));
            }
            else
            {
                return(fromValue =>
                {
                    if (fromValue == null)
                    {
                        return fromValue;
                    }
                    if (toType == typeof(string))
                    {
                        return fromValue.ToJsv();
                    }

                    var toValue = toType.CreateInstance();
                    toValue.PopulateWith(fromValue);
                    return toValue;
                });
            }

            return(null);
        }
        protected override string CreateMessage(Type dtoType)
        {
            var requestObj = AutoMappingUtils.PopulateWith(Activator.CreateInstance(dtoType));

            return(requestObj.SerializeAndFormat());
        }
        protected override string CreateMessage(Type dtoType)
        {
            var requestObj = AutoMappingUtils.PopulateWith(dtoType.CreateInstance());

            return(JsonDataContractSerializer.Instance.SerializeToString(requestObj));
        }
Example #20
0
 public void Can_create_DTO_with_Stream()
 {
     var o          = typeof(RawRequest).CreateInstance();
     var requestObj = AutoMappingUtils.PopulateWith(o);
 }
Example #21
0
        public void PopulateObject_UsesDefinedEnum_OnNestedTypes()
        {
            var requestObj = (Dictionary <string, TestClass2>)AutoMappingUtils.CreateDefaultValue(typeof(Dictionary <string, TestClass2>), new Dictionary <Type, int>());

            Assert.True(Enum.IsDefined(typeof(TestClassType), requestObj.First().Value.Type));
        }
Example #22
0
        public void PopulateObject_UsesDefinedEnum()
        {
            var requestObj = (TestClass2)AutoMappingUtils.PopulateWith(Activator.CreateInstance(typeof(TestClass2)));

            Assert.True(Enum.IsDefined(typeof(TestClassType), requestObj.Type));
        }
 public string Parse(Type type)
 {
     return(Parse(AutoMappingUtils.PopulateWith(type.CreateInstance()), true));
 }