public void IsInstanceOfType()
		{
			var adapter = new TypeAdapter( typeof(Casted) );
			var instance = new Casted( 6776 );
			Assert.True( adapter.IsInstanceOfType( instance ) );
			Assert.Equal( 6776, instance.Item );
		}
Пример #2
0
        public void SourceObjectWithNullReference()
        {
            var employeeDto = new EmployeeDto
            {
                Title = "Man"
            };

            var employee = new Employee
            {
                ManagerID = 2,
                ContactID = 3,
                Title = "Developer",
                BirthDate = new DateTime(1965, 1, 1, 0, 0, 0),
                HireDate = DateTime.Now,
                Gender = "M",
                MaritalStatus = "M",
                ModifiedDate = DateTime.Now,
                NationalIDNumber = "2",
                rowguid = new Guid(),
                CurrentFlag = true,
                VacationHours = 2,
                SickLeaveHours = 3,
                SalariedFlag = false,
                LoginID = "adventure-works\\peter"
            };

            ITypeAdapter typeAdapter = new TypeAdapter();
            employee = typeAdapter.Transform(employeeDto, employee);

            Assert.NotNull(employee.Gender);
            Assert.Equal(employee.Title, employeeDto.Title);
        }
Пример #3
0
        public void TransformDTOtoContact()
        {
            var adapter = new TypeAdapter<ContactDTO, Contact>();
            var contact = new ContactDTO()
            {
                FirstName = "gates"
            };
            var dto = adapter.Transform<ContactDTO,Contact>(contact);

            Assert.Equal(dto.FirstName, contact.FirstName);
        }
Пример #4
0
        public void TransformContact()
        {
            var adapter = new TypeAdapter();
            var contact = new Contact()
            {
               FirstName="gates"
            };
            var dto = adapter.Transform<Contact, ContactDto>(contact);

            Assert.Equal(contact.FirstName, dto.FirstName);
        }
Пример #5
0
        public void TransformEmployeePayHistory()
        {
            var adapter = new TypeAdapter();
            var eph = new EmployeePayHistory()
            {
                EmployeeID = 1,
                ModifiedDate = DateTime.Now
            };
            var dto = adapter.Transform<EmployeePayHistory, EmployeePayHistoryDto>(eph);

            Assert.Equal(1, dto.EmployeeID);
        }
Пример #6
0
        public void TransformDTOtoEmployeePayHistory()
        {
            var adapter = new TypeAdapter<EmployeePayHistoryDTO,EmployeePayHistory>();
            var eph = new EmployeePayHistoryDTO()
            {
                EmployeeID = 1,
                ModifiedDate = DateTime.Now
            };
            var dto = adapter.Transform<EmployeePayHistoryDTO, EmployeePayHistory>(eph);

            Assert.Equal(dto.EmployeeID,eph.EmployeeID);
        }
        public void TryGetPropertyDisplayName_WithMultiLingualNameAttributeAppliedToOverride_ThrowsInvalidOperationException()
        {
            var service = SafeServiceLocator.Current.GetInstance <IMemberInformationGlobalizationService>();

            string resourceValue;

            Assert.That(
                () =>
                service.TryGetPropertyDisplayName(
                    PropertyInfoAdapter.Create(
                        typeof(DerivedClassWithMultiLingualNameAttribute)
                        .GetProperty("PropertyWithMultiLingualNameAttributeOnOverride")),
                    TypeAdapter.Create(typeof(ClassWithoutMultiLingualResourcesAttributes)),
                    out resourceValue),
                Throws.InvalidOperationException);
        }
        public void Can_Map_From_Nullable_Source_Without_Values_To_Non_Nullable_Target()
        {
            TypeAdapterConfig <NullablePrimitivesPoco, NonNullablePrimitivesDto> .NewConfig()
            .Compile();

            var poco = new NullablePrimitivesPoco {
                Id = Guid.NewGuid(), Name = "TestName"
            };

            NonNullablePrimitivesDto dto = TypeAdapter.Adapt <NullablePrimitivesPoco, NonNullablePrimitivesDto>(poco);

            dto.Id.ShouldEqual(poco.Id);
            dto.Name.ShouldEqual(poco.Name);
            dto.IsImport.ShouldBeFalse();
            dto.Amount.ShouldEqual(0);
        }
Пример #9
0
        public JsonResult Add(UserModel model)
        {
            UserRegistrationRequest request = new UserRegistrationRequest();

            TypeAdapter.Adapt(model, request);
            foreach (var roleId in model.SelectedRoles)
            {
                request.Roles.Add(new UserRole()
                {
                    Id = roleId
                });
            }
            var result = _userRegistrationService.RegisterUser(request);

            return(Json(result));
        }
Пример #10
0
 public CreateResponse Create(SaucerMultimediaRequest request, File file)
 {
     try
     {
         var saucerMultimedia = TypeAdapter.Adapt <SaucerMultimedia>(request);
         _saucerMultimediaValidator.ValidateAndThrowException(saucerMultimedia, "Base");
         //_fileValidator.ValidateAndThrowException(file, "Base");
         var savedFilePath = _storageProvider.Save(file);
         saucerMultimedia.Path = savedFilePath;
         _saucerMultimediaRepository.Add(saucerMultimedia);
         return(new CreateResponse(saucerMultimedia.Id));
     }
     catch (DataAccessException)
     {
         throw new ApplicationException();
     }
 }
Пример #11
0
        public ActionResult Update(int Id)
        {
            var currentModel = _carService.GetModelById(Id);
            var model        = TypeAdapter.Adapt <Model, ModelViewModel>(currentModel);

            model.SelectedCategoryId = currentModel.CategoryId;
            var allCategories = _carService.GetAllCategory();

            foreach (var category in allCategories)
            {
                model.AllCategories.Add(new SelectListItem()
                {
                    Text = category.Name, Value = category.Id.ToString()
                });
            }
            return(View("Edit", model));
        }
        public async Task <IHttpActionResult> UpdateAsync([FromBody] ItemCreate itemCreate, [FromUri] int id)
        {
            //It does not allow activate item by this method

            var userId = 1;

            //var itemEntity = TypeAdapter.Adapt<ItemCreate, ItemEntity>(item);
            var itemEntity = itemCreate.ToEntity();

            itemEntity.Id = id;

            var updItem = await Task.Run(() => _appService.Update(itemEntity, userId));

            var readItems = TypeAdapter.Adapt <ItemEntity, ItemRead>(updItem);

            return(this.Ok(readItems));
        }
Пример #13
0
        public void Simple_Type_Is_Converted_With_Adapter_Function()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .MapWith(() => new SimplePocoResolver());


            var source = new SimplePoco
            {
                Id   = Guid.NewGuid(),
                Name = "SimplePoco"
            };

            var dest = TypeAdapter.Adapt <SimpleDto>(source);

            dest.Id.ShouldEqual(source.Id);
            dest.Name.ShouldEqual("I got converted!");
        }
        public void Dictionary_To_Object_Map()
        {
            var dict = new Dictionary <string, object>
            {
                ["Code"] = Guid.NewGuid(),
                ["Foo"]  = "test",
            };

            TypeAdapterConfig <IReadOnlyDictionary <string, object>, SimplePoco> .NewConfig()
            .Map(c => c.Id, "Code")
            .Compile();

            var poco = TypeAdapter.Adapt <IReadOnlyDictionary <string, object>, SimplePoco>(dict);

            poco.Id.ShouldBe(dict["Code"]);
            poco.Name.ShouldBeNull();
        }
        public void Unmapped_Classes_Should_Throw()
        {
            TypeAdapterConfig.GlobalSettings.RequireExplicitMapping = true;

            TypeAdapterConfig <SimplePoco, SimpleDto> .Clear();

            var simplePoco = new SimplePoco {
                Id = Guid.NewGuid(), Name = "TestName"
            };

            var exception = Assert.Throws <InvalidOperationException>(() => TypeAdapter.Adapt <SimplePoco, SimpleDto>(simplePoco));

            Console.WriteLine(exception.Message);

            exception.Message.ShouldContain("SimplePoco");
            exception.Message.ShouldContain("SimpleDto");
        }
Пример #16
0
        public ProdutoViewModel Adicionar(ProdutoViewModel produtoViewModel)
        {
            var _produto = ProdutoAdapter.ToDomainModel(produtoViewModel);

            if (!Notifications.HasNotifications())
            {
                var _adicionado = _produtoService.Adicionar(_produto);

                if (Commit())
                {
                    produtoViewModel = TypeAdapter.Adapt <Produto, ProdutoViewModel>(_adicionado);
                }
            }


            return(produtoViewModel);
        }
Пример #17
0
 public CustomerResponse Get(GetCustomerRequest request)
 {
     try
     {
         request.Id.ThrowExceptionIfIsZero();
         _customerQuery.Init();
         _customerQuery.WithOnlyActivated(true);
         _customerQuery.WithId(request.Id);
         var customer = _customerQuery.Execute().FirstOrDefault();
         customer.ThrowExceptionIfRecordIsNull();
         return(TypeAdapter.Adapt <Customer, CustomerResponse>(customer));
     }
     catch (DataAccessException)
     {
         throw new ApplicationException();
     }
 }
Пример #18
0
        [HttpPost] //mvcpostaction4
        public ActionResult Cadastrar(ClienteViewModel dadosTela)
        {
            //Só chega na action sem validação se o javascript estiver desabilidatado. Neste caso deve ser valiado também no lado servidor atraves
            //ModelStatate, onde temos as informações dos campos que não foram preenchidos corretamente
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var dadosTabela = TypeAdapter.Adapt <ClienteViewModel, Cliente>(dadosTela); //converte modelView para entity

            _negocioCliente.Cadastrar(dadosTabela);

            TempData.Add("Mensagem", "Cliente cadastrado com sucesso");

            return(RedirectToAction("Listar")); //Para levar o usuario para outra tela usamos o comando RedirectToAction
        }
        public void GetResourceManager_WithExpectedType()
        {
            var type            = typeof(ResourceTarget);
            var typeInformation = TypeAdapter.Create(type);

            _resourceManagerStub
            .Stub(stub => stub.TryGetString(Arg.Is("property:Value1"), out Arg <string> .Out("TheValue").Dummy))
            .Return(true);
            _resolverStub.Stub(stub => stub.Resolve(type)).Return(_resolvedResourceManagerResult);

            var resourceManager = _globalizationService.GetResourceManager(typeInformation);

            string value;

            Assert.That(resourceManager.TryGetString("property:Value1", out value), Is.True);
            Assert.That(value, Is.EqualTo("TheValue"));
        }
        public void Ignores_Are_Derived_From_Base_Dest_Configurations()
        {
            TypeAdapterConfig.GlobalSettings.AllowImplicitDestinationInheritance = true;
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Map(dest => dest.Name, src => src.Name + "_Suffix");

            var source = new DerivedPoco
            {
                Id   = new Guid(),
                Name = "SourceName"
            };

            var dto = TypeAdapter.Adapt <DerivedDto>(source);

            dto.Id.ShouldEqual(source.Id);
            dto.Name.ShouldEqual(source.Name + "_Suffix");
        }
        public void GetResourceManagerTwice_SameFromCache()
        {
            var type            = typeof(ResourceTarget);
            var typeInformation = TypeAdapter.Create(type);

            _resourceManagerStub
            .Stub(stub => stub.TryGetString(Arg.Is("property:Value1"), out Arg <string> .Out("TheValue").Dummy))
            .Return(true);

            _resolverStub.Stub(stub => stub.Resolve(type)).Return(_resolvedResourceManagerResult);

            var resourceManager1 = _globalizationService.GetResourceManager(typeInformation);
            var resourceManager2 = _globalizationService.GetResourceManager(typeInformation);

            Assert.That(resourceManager1, Is.SameAs(resourceManager2));
            _resolverStub.AssertWasCalled(stub => stub.Resolve(Arg <Type> .Is.Anything), options => options.Repeat.Once());
        }
        public void GetResourceManager_TypeWithMultipleMixins_ReturnsMostSpecificResourceManagerFirst()
        {
            using (MixinConfiguration.BuildFromActive()
                   .ForClass <ClassWithoutMultiLingualResourcesAttributes>()
                   .AddMixin <MixinAddingMultiLingualResourcesAttributes1>()
                   .AddMixin <MixinWithoutResourceAttribute>()
                   .ForClass <MixinWithoutResourceAttribute>()
                   .AddMixin <MixinOfMixinWithResources>()
                   .EnterScope())
            {
                var typeInformation = TypeAdapter.Create(typeof(ClassWithoutMultiLingualResourcesAttributes));

                var result = (ResourceManagerSet)_globalizationService.GetResourceManager(typeInformation);

                Assert.That(result.ResourceManagers.First().Name, Is.EqualTo(NamedResources.MixinOfMixinWithResources));
            }
        }
Пример #23
0
        public DTO.Worker Execute(Worker worker)
        {
            var workerDto  = TypeAdapter.Adapt <DTO.Worker>(worker);
            var department = _departmentRepository.FindBy(worker.DepartmentId);

            workerDto.Department = TypeAdapter.Adapt <DTO.Department>(department);
            var job = _jobRepository.FindBy(worker.JobId);

            workerDto.Job = TypeAdapter.Adapt <DTO.Job>(job);
            var role = _roleRepository.FindBy(worker.RoleId);

            workerDto.Role = TypeAdapter.Adapt <DTO.Role>(role);
            var branch = _branchRepository.FindBy(worker.BranchId);

            workerDto.Branch = TypeAdapter.Adapt <DTO.Branch>(branch);
            return(workerDto);
        }
Пример #24
0
        /// <summary>
        /// carrega a tela cadastrar
        /// </summary>
        /// <returns></returns>
        //OutputCache[(Duration = 60)]
        public ActionResult Cadastrar()
        {
            //Deixando as telas que são carregadas com frequencia e que seu contéudo nao seja alterado com frequencia podem ser deixadas em cache.
            //a configuração do tempo é em segundos

            var vmCliente = new ClienteViewModel();

            //quando criamos um SELECTLIST passamos 3 parametros: 1) Lista de registros; 2) Nome do campo que é chave primaria
            //3) Nome do campo que é texto
            var sexosTabela = _negocioSexo.Listar();

            var sexosTela = TypeAdapter.Adapt <IEnumerable <Sexo>, IEnumerable <SexoViewModel> >(sexosTabela);//lista de sexo será transformada em SexoViewModel

            vmCliente.ListaSexos = new SelectList(sexosTela, "Codigo", "Descricao");

            return(View(vmCliente));
        }
Пример #25
0
        public void Base_Configuration_Applies_To_Derived_Class_If_No_Explicit_Configuration()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Map(dest => dest.Name, src => src.Name + "_Suffix")
            .Compile();

            var source = new DerivedPoco
            {
                Id   = new Guid(),
                Name = "SourceName"
            };

            var dto = TypeAdapter.Adapt <SimpleDto>(source);

            dto.Id.ShouldBe(source.Id);
            dto.Name.ShouldBe(source.Name + "_Suffix");
        }
Пример #26
0
        public void Object_To_Dictionary_Map()
        {
            var poco = new SimplePoco
            {
                Id   = Guid.NewGuid(),
                Name = "test",
            };

            TypeAdapterConfig <SimplePoco, Dictionary <string, object> > .NewConfig()
            .Map("Code", c => c.Id);

            var dict = TypeAdapter.Adapt <Dictionary <string, object> >(poco);

            dict.Count.ShouldBe(2);
            dict["Code"].ShouldBe(poco.Id);
            dict["Name"].ShouldBe(poco.Name);
        }
Пример #27
0
        public void When_Condition_Throws_Exception_Bubbles_Up()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Map(dest => dest.Amount, src => src.Amount, cond => cond.Amount / cond.Count > 0);

            var poco = new SimplePoco
            {
                Id     = new Guid(),
                Name   = "TestName",
                Amount = 100,
                Count  = 0
            };

            var exception = Assert.Throws <InvalidOperationException>(() => TypeAdapter.Adapt <SimpleDto>(poco));

            exception.InnerException.ShouldBeType <DivideByZeroException>();
        }
        public static VirtualRelationEndPointDefinition Create(
            ClassDefinition classDefinition,
            string propertyName,
            bool isMandatory,
            CardinalityType cardinality,
            Type propertyType,
            string sortExpressionString)
        {
            var propertyInformationStub = MockRepository.GenerateStub <IPropertyInformation>();

            propertyInformationStub.Stub(stub => stub.Name).Return(propertyName);
            propertyInformationStub.Stub(stub => stub.PropertyType).Return(propertyType);
            propertyInformationStub.Stub(stub => stub.DeclaringType).Return(TypeAdapter.Create(classDefinition.ClassType));

            return(new VirtualRelationEndPointDefinition(
                       classDefinition, propertyName, isMandatory, cardinality, sortExpressionString, propertyInformationStub));
        }
Пример #29
0
        public void Simple_String_Value_Is_Converted_With_Resolver_Instance()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Resolve(dest => dest.Name, new SimplePocoNameResolver());


            var source = new SimplePoco
            {
                Id   = Guid.NewGuid(),
                Name = "SimplePoco"
            };

            var destination = TypeAdapter.Adapt <SimpleDto>(source);

            destination.Id.ShouldEqual(source.Id);
            destination.Name.ShouldEqual("Resolved:SimplePoco");
        }
        public void GetGetMethod_GetSetMethod_ImplicitWriteOnlyPropertyImplementationAddingPrivateSetAccessor_NonPublicFlagFalse()
        {
            var implementationPropertyInfo = PropertyInfoAdapter.Create(typeof(ClassImplementingInterface).GetProperty("PropertyAddingPrivateSetAccessor"));
            var declaringPropertyInfo      = PropertyInfoAdapter.Create(typeof(IInterfaceToImplement).GetProperty("PropertyAddingPrivateSetAccessor"));

            var interfaceImplementationPropertyInformation = new InterfaceImplementationPropertyInformation(
                implementationPropertyInfo, declaringPropertyInfo);

            var getMethodResult = interfaceImplementationPropertyInformation.GetGetMethod(false);

            CheckMethodInformation(
                typeof(InterfaceImplementationMethodInformation),
                TypeAdapter.Create(typeof(ClassImplementingInterface)),
                "get_PropertyAddingPrivateSetAccessor",
                getMethodResult);
            Assert.That(interfaceImplementationPropertyInformation.GetSetMethod(false), Is.Null);
        }
        public void Dest_Calls_Calls_Non_Default_Constructor_With_ConstructUsing()
        {
            TypeAdapterConfig <SimplePoco, SimpleDtoWithDefaultConstructor> .NewConfig()
            .IgnoreNullValues(true)
            .ConstructUsing(src => new SimpleDtoWithDefaultConstructor("unmapped"))
            .Compile();

            var simplePoco = new SimplePoco {
                Id = Guid.NewGuid(), Name = "TestName"
            };

            var dto = TypeAdapter.Adapt <SimpleDtoWithDefaultConstructor>(simplePoco);

            dto.Id.ShouldBe(simplePoco.Id);
            dto.Name.ShouldBe(simplePoco.Name);
            dto.Unmapped.ShouldBe("unmapped");
        }
Пример #32
0
        public override object GetValue()
        {
            TypeDecoratorList itemsDecorator = TypeAdapter.Adapter("[float]") as TypeDecoratorList;

            itemsDecorator.runtimeType = typeof(List <float>);
            itemsDecorator.ResetFlag(1);
            object       vs     = ValueAdapter.Adapter(value, itemsDecorator);
            List <float> realvs = vs as List <float>;

            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
            object       v3    = Common.Utility.Reflection.CreateInstance(decorator.runtimeType);

            Common.Utility.Reflection.SetValue(decorator.runtimeType, "x", v3, realvs.Count > 0 ? realvs[0] : 0, flags);
            Common.Utility.Reflection.SetValue(decorator.runtimeType, "y", v3, realvs.Count > 1 ? realvs[1] : 0, flags);
            Common.Utility.Reflection.SetValue(decorator.runtimeType, "z", v3, realvs.Count > 2 ? realvs[2] : 0, flags);
            return(v3);
        }
        public void GetGetMethod_GetSetMethod_WriteOnlyImplicitPropertyImplementation()
        {
            var implementationPropertyInfo = PropertyInfoAdapter.Create(typeof(ClassImplementingInterface).GetProperty("WriteOnlyImplicitProperty"));
            var declaringPropertyInfo      = PropertyInfoAdapter.Create(typeof(IInterfaceToImplement).GetProperty("WriteOnlyImplicitProperty"));

            var interfaceImplementationPropertyInformation = new InterfaceImplementationPropertyInformation(
                implementationPropertyInfo, declaringPropertyInfo);

            Assert.That(interfaceImplementationPropertyInformation.GetGetMethod(false), Is.Null);
            var getMethodResult = interfaceImplementationPropertyInformation.GetSetMethod(false);

            CheckMethodInformation(
                typeof(InterfaceImplementationMethodInformation),
                TypeAdapter.Create(typeof(ClassImplementingInterface)),
                "set_WriteOnlyImplicitProperty",
                getMethodResult);
        }
Пример #34
0
        public void Dictionary_To_Object_Flexible()
        {
            var config = new TypeAdapterConfig();

            config.Default.NameMatchingStrategy(NameMatchingStrategy.Flexible);
            var dict = new Dictionary <string, object>
            {
                ["id"]   = Guid.NewGuid(),
                ["Name"] = "bar",
                ["foo"]  = "test",
            };

            var poco = TypeAdapter.Adapt <SimplePoco>(dict, config);

            poco.Id.ShouldBe(dict["id"]);
            poco.Name.ShouldBe(dict["Name"]);
        }
Пример #35
0
        public void Int_Is_Mapped_To_Enum()
        {
            TypeAdapterConfig <Employee, EmployeeDTO>
            .NewConfig();

            var employee = new Employee {
                Id = Guid.NewGuid(), Name = "Timuçin", Surname = "KIVANÇ", Department = (int)Departments.IT
            };

            var dto = TypeAdapter.Adapt <Employee, EmployeeDTO>(employee);

            Assert.IsNotNull(dto);

            Assert.IsTrue(dto.Id == employee.Id &&
                          dto.Name == employee.Name &&
                          dto.Department == Departments.IT);
        }
Пример #36
0
        public void Empty_String_Is_Mapped_To_Enum_Default()
        {
            TypeAdapterConfig <EmployeeWithStringEnum, EmployeeDTO>
            .NewConfig();

            var employee = new EmployeeWithStringEnum {
                Id = Guid.NewGuid(), Name = "Timuçin", Department = ""
            };

            var dto = TypeAdapter.Adapt <EmployeeWithStringEnum, EmployeeDTO>(employee);

            dto.ShouldNotBeNull();

            dto.Id.ShouldBe(employee.Id);
            dto.Name.ShouldBe(employee.Name);
            dto.Department.ShouldBe(Departments.Finance);
        }
        public void TypeAdapter_AdaptMappedTypes()
        {
            //Arrange
            TypeAdapter adapter = null;

            RegisterTypesMap[] mapModules = new RegisterTypesMap[]
            {
                new CRMRegisterTypesMap(),
                new SalesRegisterTypesMap()
            };

            adapter = new TypeAdapter(mapModules);

            Customer customer = new Customer()
            {
                Id = 1,
                FirstName = "Unai",
                LastName = "Zorrilla"
            };

            Order order = new Order()
            {
                Id = 1,
                OrderDate = DateTime.UtcNow,
                Total = 1000
            };

            //Act

            var dtoCustomer = adapter.Adapt<Customer, CustomerDTO>(customer);
            var dtoOrder = adapter.Adapt<Order, OrderDTO>(order);

            //Assert
            Assert.IsNotNull(dtoCustomer);
            Assert.IsNotNull(dtoOrder);

            Assert.IsTrue(dtoCustomer.CustomerId == 1);
            Assert.IsTrue(dtoCustomer.FullName == string.Format("{0},{1}",customer.LastName,customer.FirstName));

            Assert.IsTrue(dtoOrder.OrderId == 1);
            Assert.IsTrue(dtoOrder.Description == string.Format("{0} - {1}",order.OrderDate,order.Total));
        }
        ITypeAdapter PrepareTypeAdapter()
        {
            TypeAdapter adapter = new TypeAdapter(new RegisterTypesMap[] { new BankingModuleRegisterTypesMap() });

            return adapter;
        }
Пример #39
0
		public void EnumerableType()
		{
			var item = new TypeAdapter( typeof(List<int>) ).GetEnumerableType();
			Assert.Equal( typeof(int), item );
		}
Пример #40
0
		public MethodMapper( TypeAdapter adapter )
		{
			this.adapter = adapter;
		}
        public void TypeAdapter_AdaptNullItemThrowArgumentException()
        {
            //Arrange
            TypeAdapter adapter = null;
            RegisterTypesMap[] mapModules = new RegisterTypesMap[]
            {
                new CRMRegisterTypesMap(),
                new SalesRegisterTypesMap()
            };
            adapter = new TypeAdapter(mapModules);

            //Act
            adapter.Adapt<Customer, CustomerDTO>(null);
        }
        public void TypeAdapter_LoadRegisterTypesMapFromConfiguration()
        {
            //Arrange
            TypeAdapter adapter = null;
            RegisterTypesMap[] mapModules = new RegisterTypesMap[]
            {
                new CRMRegisterTypesMap(),
                new SalesRegisterTypesMap()
            };

            //Act
            adapter = new TypeAdapter(mapModules);

            //Assert
            Assert.IsNotNull(adapter.Maps);
            Assert.IsTrue(adapter.Maps.Count == 2);

            string keyCustomer = TypeMapConfigurationBase<Customer, CustomerDTO>.GetDescriptor();
            string keyOrder = TypeMapConfigurationBase<Order, OrderDTO>.GetDescriptor();

            Assert.IsNotNull(adapter.Maps[keyCustomer] !=null );
            Assert.IsNotNull(adapter.Maps[keyOrder] != null);
        }
        public void TypeAdapter_AdapUnmappedTypesThrowInvalidOperationException()
        {
            //Arrange
            TypeAdapter adapter = null;
            RegisterTypesMap[] mapModules = new RegisterTypesMap[]
            {
                new CRMRegisterTypesMap(),
                new SalesRegisterTypesMap()
            };
            adapter = new TypeAdapter(mapModules);

            Product product = new Product()
            {
                ProductId = 1,
                LaunchDate = DateTime.UtcNow,
                ProductName ="Product Name"
            };

            //Act
            adapter.Adapt<Product, ProductDTO>(product);
        }