예제 #1
0
파일: Global.asax.cs 프로젝트: aiten/CNCLib
		protected void Application_Start()
		{
			Dependency.Initialize(new LiveDependencyProvider());
			Dependency.Container.RegisterTypesIncludingInternals(
				typeof(CNCLib.ServiceProxy.Logic.MachineService).Assembly,
				typeof(CNCLib.Repository.MachineRepository).Assembly,
				typeof(CNCLib.Logic.Client.DynItemController).Assembly,
				typeof(CNCLib.Logic.MachineController).Assembly);
			Dependency.Container.RegisterType<IUnitOfWork, UnitOfWork<Repository.Context.CNCLibContext>>();

			Dependency.Container.RegisterType<IRest< CNCLib.Logic.Contracts.DTO.Machine>, MachineRest>();
			Dependency.Container.RegisterType<IRest<CNCLib.Logic.Contracts.DTO.LoadOptions>, LoadInfoRest>();
			Dependency.Container.RegisterType<IRest<CNCLib.Logic.Contracts.DTO.Item>, ItemRest>();

			var config = new MapperConfiguration(cfg =>
			{
				cfg.AddProfile<LogicAutoMapperProfile>();
			});

			var mapper = config.CreateMapper();

			Dependency.Container.RegisterInstance<IMapper>(mapper);

			AreaRegistration.RegisterAllAreas();
			GlobalConfiguration.Configure(WebApiConfig.Register);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
		}
예제 #2
0
        // <summary>取得所有客戶資料(分頁)</summary>
        /// <returns></returns>
        public IQueryable<CustomerViewModel> Get(int CurrPage, int PageSize, out int TotalRow)
        {
            // 取得所有筆數
            TotalRow = db.Get().ToList().Count();

            // 使用Linq篩選分頁
            var DbResult = db.Get().ToList().Skip((CurrPage - 1) * PageSize).Take(PageSize).ToList();

            #region AutoMapper V4.2 以前的寫法
            // Mapping到ViewModel
            
            //
            //Mapper.CreateMap<Customers, CustomerViewModel>();
            //return Mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult).AsQueryable();
            #endregion

            #region 新版AutoMapper 寫法
            //AutoMapper V >= 4.2 的寫法
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Customers, CustomerViewModel>());
            config.AssertConfigurationIsValid();//驗證應對

            var mapper = config.CreateMapper();
            return mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult).AsQueryable();
            #endregion
        }
예제 #3
0
        /// <summary>
        /// 取得所有客戶資料
        /// </summary>
        /// <returns></returns>
        public List<CustomerViewModel> Get()
        {
            #region 很累的寫法(一個一個丟)
            //List<CustomerViewModel> model = new List<CustomerViewModel>();
            //var DbResult = db.Get().AsQueryable();
            //
            //foreach (var item in DbResult)
            //{
            //    //將Customers的清單資料一個一個丟到CustomerViewModel
            //    CustomerViewModel _model = new CustomerViewModel();
            //    _model.CustomerID = item.CustomerID;
            //    _model.ContactName = item.ContactName;
            //    model.Add(_model);
            //}
            //
            //return model.AsQueryable();
            #endregion

            #region 改用AutoMapper
            var DbResult = db.Get().ToList();
            //AntoMapper before V4.2
            //Mapper.CreateMap<Customers, CustomerViewModel>();
            //
            //return Mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult);

            var config = new MapperConfiguration(cfg => cfg.CreateMap<Customers, CustomerViewModel>());
            config.AssertConfigurationIsValid();//驗證應對

            var mapper = config.CreateMapper();
            return mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult);
            #endregion
        }
예제 #4
0
        private void ConfigureMapper()
        {
            //var config = Mapper.Configuration;
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Record, JWSModels.Record>().ForMember(target => target.TierLevel, opts => opts.Ignore()).ForMember(target => target.TierLevelId, opts => opts.Ignore()).ForMember(target => target.TierName, opts => opts.Ignore()).ForMember(target => target.UserLevel, opts => opts.Ignore()).ForMember(target => target.IndexCode, opts => opts.Ignore()).ForMember(target => target.NumberPayPeriods, opts => opts.Ignore()).ForMember(target => target.PayRatePerPayPeriod, opts => opts.Ignore()).ForMember(target => target.AnnualHours, opts => opts.Ignore()).ForMember(target => target.AnnualPayRate, opts => opts.Ignore()).ForMember(target => target.AddressLine1, opts => opts.ResolveUsing(c => c.Address1)).ForMember(target => target.AddressLine2, opts => opts.ResolveUsing(c => c.Address2)).ForMember(target => target.City, opts => opts.ResolveUsing(c => c.City)).ForMember(target => target.DateOfBirth, opts => opts.ResolveUsing(c => c.DateOfBirth)).ForMember(target => target.DaysWorkedPerWeek, opts => opts.Ignore()).ForMember(target => target.EmployeeId, opts => opts.Ignore()).ForMember(target => target.FirstName, opts => opts.ResolveUsing(c => c.FirstName)).ForMember(target => target.Gender, opts => opts.ResolveUsing(c => c.Gender)).ForMember(target => target.HireDate, opts => opts.ResolveUsing(c => c.HireDate)).ForMember(target => target.JobClassCode, opts => opts.Ignore()).ForMember(target => target.JobDescription, opts => opts.Ignore()).ForMember(target => target.LastName, opts => opts.ResolveUsing(c => c.LastName)).ForMember(target => target.OccupationCode, opts => opts.Ignore()).ForMember(target => target.PayRate, opts => opts.Ignore()).ForMember(target => target.HoursWorkedPerDay, opts => opts.Ignore()).ForMember(target => target.PayRateType, opts => opts.Ignore()).ForMember(target => target.PhoneNumber, opts => opts.Ignore()).ForMember(target => target.SocialSecurityNumber, opts => opts.ResolveUsing(c => c.SocialSecurityNumber)).ForMember(target => target.State, opts => opts.ResolveUsing(c => c.State)).ForMember(target => target.UnionCode, opts => opts.Ignore()).ForMember(target => target.NameSuffix, opts => opts.Ignore()).ForMember(target => target.ZipCode, opts => opts.ResolveUsing(c => c.ZipCode)).AfterMap((src, target) =>
                {
                    TierMapping tierMapping; //= new TierMapping(this, target);

                    if (!src.DepartmentName.IsEmpty())
                    {
                        tierMapping = new TierMapping(this, target, src.DepartmentName);
                        tierMapping.MapOrgLevel(Tiers4, 4, src.DepartmentName.ToUpper(), src.DepartmentName.ToUpper(), MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }

                    if (!src.DivisionName.IsEmpty())
                    {
                        tierMapping = new TierMapping(this, target, src.DivisionName);
                        tierMapping.MapOrgLevel(Tiers3, 3, src.DivisionName.ToUpper(), src.DivisionName.ToUpper(), MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }
                });
            });
            config.AssertConfigurationIsValid();
            mapper = config.CreateMapper();
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddCaching();
            services.AddSession();

            // Configuration
            services.Configure<EncryptionConfig>(Configuration.GetSection("Encryption"));
            services.Configure<EmailConfig>(Configuration.GetSection("Email"));
            services.Configure<RedisConfig>(Configuration.GetSection("Redis"));

            // Dependency Injection
            services.AddSingleton<IRedisService, RedisService>();
            services.AddSingleton<IEncryptionService, BasicEncryption>();
            services.AddSingleton<ISchedulerService, SchedulerService>();
            services.AddSingleton<IEmailService, EmailService>();
            services.AddTransient<IMojangService, MojangService>();
            services.AddTransient<IUserService, UserService>();
            services.AddTransient<IUsernameService, UsernameService>();

            // Automapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            services.AddSingleton(sp => config.CreateMapper());
        }
예제 #6
0
        public void Example()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<ContainsASrc, ContainsADest>();

                cfg.CreateMap<ASrc, ADest>()
                    .Include<BSrc, BDest>()
                    .Include<CSrc, CDest>();

                cfg.CreateMap<BSrc, BDest>()
                    .Include<CSrc, CDest>();

                cfg.CreateMap<CSrc, CDest>();
            });

            var expectedCSrc = new CSrc() {StringA = "A", StringB = "B", StringC = "C"};
            var expectedBSrc = new BSrc() {StringA = "A", StringB = "B"};

            var expectedContCSrc = new ContainsASrc() {A = expectedCSrc};
            var expectedContBSrc = new ContainsASrc() {A = expectedBSrc};

            var mapper = config.CreateMapper();
            var actualContCDest = mapper.Map<ContainsASrc, ContainsADest>(expectedContCSrc);
            var actualContBDest = mapper.Map<ContainsASrc, ContainsADest>(expectedContBSrc); // THROWS

            config.AssertConfigurationIsValid();
            actualContBDest.ShouldNotBeNull();
            actualContCDest.ShouldNotBeNull();
        }
예제 #7
0
        public void Fact()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateProfile("New Profile", profile =>
                {
                    profile.AddMemberConfiguration().AddName<PrePostfixName>(
                            _ => _.AddStrings(p => p.DestinationPostfixes, "Transfer")
                                .AddStrings(p => p.Postfixes, "Transfer")
                                .AddStrings(p => p.DestinationPrefixes, "Trans")
                                .AddStrings(p => p.Prefixes, "Trans"));
                    profile.AddConditionalObjectMapper().Where((s, d) => s.Name.Contains(d.Name) || d.Name.Contains(s.Name));
                });
            });

            var mapper = config.CreateMapper();
            var a2 = mapper.Map<ClientDto>(new Client() { Value= "Test", Transval = "test"});
            a2.ValueTransfer.ShouldEqual("Test");
            a2.val.ShouldEqual("test");

            var a = mapper.Map<Client>(new ClientDto() { ValueTransfer = "TestTransfer", val = "testTransfer"});
            a.Value.ShouldEqual("TestTransfer");
            a.Transval.ShouldEqual("testTransfer");

            var clients = mapper.Map<Client[]>(new[] { new ClientDto() });
            Expression<Func<Client, bool>> expr = c => c.ID < 5;
            var clientExp = mapper.Map<Expression<Func<ClientDto,bool>>>(expr);
        }
예제 #8
0
 public IEnumerable<CurrentPosition> GetCurrentPosition()
 {
     var config = new MapperConfiguration(cfg => cfg.CreateMap<Position, CurrentPosition>());
     var mapper = config.CreateMapper();
     var result = new List<CurrentPosition>();
     var positions = _positionRepository.Get();
     foreach (var position in positions)
     {
         var current = mapper.Map<CurrentPosition>(position);
         if (current.CurrencyCode == "AUD")
         {
             current.CurrentPrice = _screenScrapper.GetYahooPrice($"{current.Key}.AX").Result;
         }
         else
         {
             current.CurrentPrice = _screenScrapper.GetYahooPrice(current.Key).Result / _screenScrapper.GetYahooPrice($"AUD{current.CurrencyCode}=X").Result;
         }
         //make the calculation
         current.TotalNow = current.Quantity * current.CurrentPrice;
         current.TotalWhenBought = current.Quantity * current.PriceWhenBought;
         current.DaysSinceBought = (int)(DateTime.Now - current.DateWhenBought).TotalDays;
         current.DifferenceMoney = current.TotalNow - current.TotalWhenBought;
         current.DifferencePercentage = (current.DifferenceMoney / current.TotalWhenBought) * 100;
         result.Add(current);
     }
     return result;
 }
예제 #9
0
 public void Should_map_source_properties()
 {
     var config = new MapperConfiguration(cfg => { });
     _destination = config.CreateMapper().Map<DynamicDictionary>(new Destination {Foo = "Foo", Bar = "Bar"});
     Assert.Equal("Foo", _destination.Foo);
     Assert.Equal("Bar", _destination.Bar);
 }
예제 #10
0
            public void Should_map_the_existing_array_elements_over()
            {
                var sourceList = new List<SourceObject>();
                var destList = new List<DestObject>();

                var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceObject, DestObject>().PreserveReferences());
                config.AssertConfigurationIsValid();

                var source1 = new SourceObject
                {
                    Id = 1,
                };
                sourceList.Add(source1);

                var source2 = new SourceObject
                {
                    Id = 2,
                };
                sourceList.Add(source2);

                source1.AddChild(source2); // This causes the problem

                config.CreateMapper().Map(sourceList, destList);

                destList.Count.ShouldEqual(2);
                destList[0].Children.Count.ShouldEqual(1);
                destList[0].Children[0].ShouldBeSameAs(destList[1]);
            }
 public InMemoryIdentityManagerService(ICollection<InMemoryScope> scopes, ICollection<InMemoryClient> clients)
 {
     this._clients = clients;
     this._scopes = scopes;
     Config = new MapperConfiguration(cfg => {
         cfg.CreateMap<InMemoryClientClaim, ClientClaimValue>();
         cfg.CreateMap<ClientClaimValue, InMemoryClientClaim>();
         cfg.CreateMap<InMemoryClientSecret, ClientSecretValue>();
         cfg.CreateMap<ClientSecretValue, InMemoryClientSecret>();
         cfg.CreateMap<InMemoryClientIdPRestriction, ClientIdPRestrictionValue>();
         cfg.CreateMap<ClientIdPRestrictionValue, InMemoryClientIdPRestriction>();
         cfg.CreateMap<InMemoryClientPostLogoutRedirectUri, ClientPostLogoutRedirectUriValue>();
         cfg.CreateMap<ClientPostLogoutRedirectUriValue, InMemoryClientPostLogoutRedirectUri>();
         cfg.CreateMap<InMemoryClientRedirectUri, ClientRedirectUriValue>();
         cfg.CreateMap<ClientRedirectUriValue, InMemoryClientRedirectUri>();
         cfg.CreateMap<InMemoryClientCorsOrigin, ClientCorsOriginValue>();
         cfg.CreateMap<ClientCorsOriginValue, InMemoryClientCorsOrigin>();
         cfg.CreateMap<InMemoryClientCustomGrantType, ClientCustomGrantTypeValue>();
         cfg.CreateMap<ClientCustomGrantTypeValue, InMemoryClientCustomGrantType>();
         cfg.CreateMap<InMemoryClientScope, ClientScopeValue>();
         cfg.CreateMap<ClientScopeValue, InMemoryClientScope>();
         cfg.CreateMap<InMemoryScopeClaim, ScopeClaimValue>();
         cfg.CreateMap<ScopeClaimValue, InMemoryScopeClaim>();
         cfg.CreateMap<InMemoryScope, Scope>();
         cfg.CreateMap<Scope, InMemoryScope>();
     });
     Mapper = Config.CreateMapper();
 }
예제 #12
0
 public void Should_map_source_properties()
 {
     var config = new MapperConfiguration(cfg => { });
     dynamic destination = config.CreateMapper().Map<DynamicDictionary>(new Source());
     ((int)destination.Count).ShouldEqual(1);
     Assert.Equal(24, destination.Value);
 }
예제 #13
0
        public List<StoreResultModel> Get(StoreInfoModel info)
        {
            var mapConfig = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<StoreInfoModel, StoreQueryModel>();
                cfg.CreateMap<StoreInfoModel, CheckQueryModel>();
                cfg.CreateMap<StoreDataModel, StoreResultModel>();
                cfg.CreateMap<CheckDataModel, StoreResultModel>()
                    .ForMember(d => d.Checks, o => o.MapFrom(s => new CheckDataModel()));
            });

            var mapper = mapConfig.CreateMapper();
            var queryStore = mapper.Map<StoreQueryModel>(info);
            var stores = (this.StoreRepository.Get(queryStore)
                                                .Select(x => mapper.Map<StoreResultModel>(x)))
                                                .ToList();

            // 商業邏輯 - 非體系內 多顯示簽到記錄
            if (info.System != null &&
                info.System != "永慶" &&
                info.System != "有巢" &&
                info.System != "台慶")
            {
                var queryCheck = mapper.Map<CheckQueryModel>(info);
                var checks = (this.CheckRepository.Get(queryCheck)
                                                .Select(x => mapper.Map<StoreResultModel>(x)))
                                                .ToList();
            }

            return stores;
        }
        public static IMapper RegisterProfiles()
        {
            var config = new MapperConfiguration(
                cfg =>
                {
                    //Model para Dto
                    cfg.CreateMap<TarefaCadastroModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id,model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaEdicaoModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaExcluirModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaEdicaoModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<AutenticacaoModel, UsuarioDto>();

                    //Dto para Model
                    /*
                    cfg.CreateMap<Usuario, UsuarioDto>();
                    cfg.CreateMap<UsuarioDto, Usuario>();
                     */
                }
            );

            var mapper = config.CreateMapper();

            return mapper;
        }
예제 #15
0
            public void Example()
            {
                // Model
                var calendarEvent = new CalendarEvent
                    {
                        EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
                        Title = "Company Holiday Party"
                    };

                var config = new MapperConfiguration(cfg =>
                {
                    // Configure AutoMapper
                    cfg.CreateMap<CalendarEvent, CalendarEventForm>()
                        .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))
                        .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))
                        .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));
                });

                // Perform mapping
                var mapper = config.CreateMapper();
                CalendarEventForm form = mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);

                form.EventDate.ShouldEqual(new DateTime(2008, 12, 15));
                form.EventHour.ShouldEqual(20);
                form.EventMinute.ShouldEqual(30);
                form.Title.ShouldEqual("Company Holiday Party");
            }
예제 #16
0
 public ImageService(IAlbumUnitOfWork db, MapperConfiguration mapperConfig)
 {
     _db = db
           ?? throw new ArgumentNullException("UnitOfWork must be not null!");
     _mapper = mapperConfig?.CreateMapper()
               ?? throw new ArgumentNullException("Mapper configuration must be not null!");
 }
예제 #17
0
        public void Should_map_properties_with_different_names()
        {
            var config = new MapperConfiguration(c =>
            {
                c.ReplaceMemberName("Ä", "A");
                c.ReplaceMemberName("í", "i");
                c.ReplaceMemberName("Airlina", "Airline");
                c.CreateMap<Source, Destination>();
            });

            var source = new Source()
            {
                Value = 5,
                Ävíator = 3,
                SubAirlinaFlight = 4
            };

            //Mapper.AddMemberConvention().AddName<ReplaceName>(_ => _.AddReplace("A", "Ä").AddReplace("i", "í").AddReplace("Airline", "Airlina")).SetMemberInfo<FieldPropertyMemberInfo>();
            var mapper = config.CreateMapper();
            var destination = mapper.Map<Source, Destination>(source);

            Assert.AreEqual(source.Value, destination.Value);
            Assert.AreEqual(source.Ävíator, destination.Aviator);
            Assert.AreEqual(source.SubAirlinaFlight, destination.SubAirlineFlight);
        }
예제 #18
0
			public void Example()
			{
				var config = new MapperConfiguration(cfg =>
				{
					cfg.AddProfile<ViewModelProfile>();
					cfg.CreateMap<Order, OrderEditViewModel>();
				});

				var order = new Order {Amount = 50m};

				var listViewModel = config.CreateMapper().Map<Order, OrderListViewModel>(order);
				var editViewModel = config.CreateMapper().Map<Order, OrderEditViewModel>(order);

				listViewModel.Amount.ShouldEqual(order.Amount.ToString("c"));
				editViewModel.Amount.ShouldEqual("50");
			}
예제 #19
0
 public TodoListService(IUnitOfWork uow,ITodoListRepository todoListRepository)
 {
     _todoListRepository = todoListRepository;
     db = uow;
     var config = new MapperConfiguration(cfg => { cfg.CreateMap<TodoListEntity, TodoListDTO>(); });
     _mapper = config.CreateMapper();
 }
예제 #20
0
        public static void RegisterMappings()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<BookViewModel, Book>());
            var mapper = config.CreateMapper();

            //AutoMapper.Mapper.CreateMap<Book, BookViewModel>()
            //    .ForMember(dest => dest.Author, opts => opts.MapFrom(src => src.Author.Name));
        }
예제 #21
0
 public void SimpleTypeExample()
 {
     // No configuration needed
     var config = new MapperConfiguration(cfg => { });
     var mapper = config.CreateMapper();
     mapper.Map<int, int>(5).ShouldEqual(5);
     mapper.Map<string, string>("foo").ShouldEqual("foo");
 }
예제 #22
0
 public void Should_dynamic_map_the_array()
 {
     source = Enumerable.Range(0, 9).Select(i => new Source(i)).ToArray();
     var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
     destination = config.CreateMapper().Map<Destination[]>(source);
     destination.Length.ShouldEqual(source.Length);
     Array.TrueForAll(source, s => s.Value == destination[s.Value].Value).ShouldBeTrue(); 
 }
예제 #23
0
 public UserService(IUnitOfWork uow,IUserRepository userRepository, ApplicationUserManager manager)
 {
     _uow = uow;
     var config = new MapperConfiguration(cfg => { cfg.CreateMap<ApplicationUserEntity, ApplicationUserDTO>(); });
     _mapper = config.CreateMapper();
     _userRepository = userRepository;
     _userManager = manager;
 }
예제 #24
0
 public ActionResult Public()
 {
     ViewBag.Layout = User.Identity.IsAuthenticated ? "~/Views/Shared/AuthLayout.cshtml" : "~/Views/Shared/NotAuthLayout.cshtml";
     var fileConfig = new MapperConfiguration(cfg => { cfg.CreateMap<FileDTO, FileViewModel>(); });
     IMapper fileMapper = fileConfig.CreateMapper();
     List<FileViewModel> files = fileMapper.Map<IEnumerable<FileDTO>, List<FileViewModel>>(FileService.GetAllPublicFiles());
     return View(files);
 }
예제 #25
0
 public void Should_map_existing_properties()
 {
     dynamic source = new DynamicDictionary();
     source.Foo = "Foo";
     var config = new MapperConfiguration(cfg => { });
     _destination = config.CreateMapper().Map<Destination>(source);
     _destination.Foo.ShouldEqual("Foo");
     _destination.Bar.ShouldBeNull();
 }
예제 #26
0
 public static void AutoMapperConfig()
 {
     configuration = new MapperConfiguration(config =>
     {
         config.CreateMap<Player, PlayerModel>();
         config.CreateMap<PlayerModel, Player>();
     });
     Mapper = configuration.CreateMapper();
 }
예제 #27
0
			public void FlagsEnumerationExample()
			{
			    var config = new MapperConfiguration(cfg => { });
			    var mapper = config.CreateMapper();
			    var targets = mapper.Map<AttributeTargets, AttributeTargets>(AttributeTargets.Class | AttributeTargets.Interface);

				(targets & AttributeTargets.Class).ShouldEqual(AttributeTargets.Class);
				(targets & AttributeTargets.Interface).ShouldEqual(AttributeTargets.Interface);
			}
예제 #28
0
파일: Startup.cs 프로젝트: tinodu/Dite
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AuthSettings>(Configuration.GetSection("Auth"));

            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            /*
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
                */

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<IUserIdentityService, UserIdentityService>();

            var mapperConfig = new MapperConfiguration(cfg =>{});
            services.AddSingleton<IMapper>(provider => mapperConfig.CreateMapper());

            // swagger         
            services.AddSwaggerGen();

            services.ConfigureSwaggerDocument(options =>
            {
                options.MultipleApiVersions(new Info[]
                {
                    new Swashbuckle.SwaggerGen.Info
                    {
                        Version = "v1",
                        Title = "Dite API",
                        Description = "Dite RESTful API"
                    },
                    new Swashbuckle.SwaggerGen.Info
                    {
                        Version = "v2",
                        Title = "Dite API (v2)",
                        Description = "Dite RESTful API"
                    }
                }, VersionSupportResolver);               
                //options.OperationFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlActionComments(pathToDoc));
            });

            services.ConfigureSwaggerSchema(options =>
            {
                options.DescribeAllEnumsAsStrings = true;
                //options.ModelFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlTypeComments(pathToDoc));
            });
        }
예제 #29
0
 public IndexController()
 {
     AutomMapperConfig = new MapperConfiguration(cfg =>
     {
         //cfg.CreateMap<DEMANDA, DemandaViewModel>();
         //cfg.CreateMap<DemandaViewModel, DEMANDA>();
     });
     Mapper = AutomMapperConfig.CreateMapper();
 }
예제 #30
0
            public void Should_use_the_implicit_conversion_operator()
            {
                var source = new Foo { Value = "Hello" };

                var config = new MapperConfiguration(cfg => { });
                _bar = config.CreateMapper().Map<Foo, Bar>(source);

                _bar.OtherValue.ShouldEqual("Hello");
            }
예제 #31
0
        private static IMapper CreateMapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<EmployeeMappingProfile>();
            });

            return config.CreateMapper();
        }
예제 #32
0
 public ImageFileService(IAlbumUnitOfWork db, MapperConfiguration mapperConfig,
                         Lazy <List <string> > allowedFileExtensions)
 {
     _db = db
           ?? throw new ArgumentNullException("UnitOfWork must be not null!");
     _mapper = mapperConfig?.CreateMapper()
               ?? throw new ArgumentNullException("Mapper configuration must be not null!");
     _random          = new Random();
     _imageExtensions = allowedFileExtensions
                        ?? throw new ArgumentNullException("Extensions must be not null!");
 }
예제 #33
0
        /// <summary>
        /// Projects the specified destination.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item">The item.</param>
        /// <param name="destination">The destination.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        public static T Project <T>(this Item item, T destination = default(T), MapperConfiguration configuration = null) where T : class
        {
            Assert.ArgumentNotNull(item, "item");

            var mapper = configuration?.CreateMapper() ?? Mapper.Instance;

            if (destination == null)
            {
                return(mapper.Map(item, typeof(T)) as T);
            }
            return(mapper.Map(item, destination, typeof(Item), destination.GetType()) as T);
        }
예제 #34
0
 /// <summary>
 ///  集合列表类型映射
 /// </summary>
 /// <typeparam name="T">目标类型</typeparam>
 /// <param name="this">源数据</param>
 /// <param name="config">映射配置</param>
 /// <returns>映射后的数据</returns>
 public static List <T> MapTo <T>(this IEnumerable @this, MapperConfiguration config = null)
 {
     if (@this == null)
     {
         return(null);
     }
     foreach (var item in @this)
     {
         if (config == null)
         {
             config = autoMapperCache.GetOrAdd(GetKey(item.GetType(), typeof(T)),
                                               x => new MapperConfiguration(cfg => cfg.CreateMap(item.GetType(), typeof(T))));
         }
         break;
     }
     return(config?.CreateMapper().Map <List <T> >(@this));
 }
예제 #35
0
        public List <CommContracts.InspectDoctorAdvice> getAllInHospitalInspectDoctorAdvice(int InpatientID)
        {
            List <CommContracts.InspectDoctorAdvice> list = new List <CommContracts.InspectDoctorAdvice>();

            using (DAL.HisContext ctx = new DAL.HisContext())
            {
                var query = from i in ctx.InspectDoctorAdvices
                            where i.InpatientID == InpatientID
                            select i;
                foreach (DAL.InspectDoctorAdvice ins in query)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap <DAL.InspectDoctorAdvice, CommContracts.InspectDoctorAdvice>();
                    });
                    var mapper = config.CreateMapper();

                    CommContracts.InspectDoctorAdvice temp = mapper.Map <CommContracts.InspectDoctorAdvice>(ins);
                    list.Add(temp);
                }
            }
            return(list);
        }
예제 #36
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <OrderPOSContext>();
            services.AddScoped <IRepository <Order>, OrderRepository>();
            services.AddScoped <IRepository <Product>, Repository <Product> >();
            services.AddScoped <IService <OrderDto>, OrderService>();
            services.AddScoped <IService <ProductDto>, Service <ProductDto, Product> >();
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);
            services.AddMvc();
            services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null).AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });
        }
        public static void Configurate()
        {
            var container = new ServiceContainer();

            container.RegisterApiControllers(Assembly.GetExecutingAssembly());

            container.EnablePerWebRequestScope();

            var config = new MapperConfiguration(cfg => cfg.AddProfiles(
                                                     new List <Profile>()
            {
                new WebAutomapperProfile(), new BLAutomapperProfile()
            }));

            container.Register(c => config.CreateMapper());

            container = BLLightInjectConfiguration.Configuration(container);

            container.Register <ICategoryService, CategoryService>();
            container.Register <IOperationService, OperationService>();

            container.EnableWebApi(GlobalConfiguration.Configuration);
        }
        public RecipeEndPointTest()
        {
            // Auto Mapper Configurations
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            _mapper = mappingConfig.CreateMapper();

            ApplicationUser appuser = new ApplicationUser()
            {
                UserName = "******",
                Id       = "123"
            };

            var store = new Mock <Microsoft.AspNetCore.Identity.IUserStore <ApplicationUser> >();

            store.Setup(x => x.FindByIdAsync("123", CancellationToken.None))
            .Returns
            (
                Task.FromResult <ApplicationUser>(appuser));
        }
예제 #39
0
 /// <summary>Configures the dependency injection.</summary>
 /// <param name="services">The services.</param>
 private void ConfigureDependencyInjection(IServiceCollection services)
 {
     #region Cryptography
     services.AddTransient <ICipher, Cipher>();
     #endregion
     services.AddTransient <IAppConfiguration, AppConfiguration>();
     services.AddTransient <ITokenGenerator, TokenGenerator>();
     #region Repository
     services.AddSingleton(typeof(IMongoDBRepository <>), typeof(MongoDBRepository <>));
     #endregion
     services.AddTransient <IAccountRepository, AccountRepository>();
     services.AddTransient <IAccountBL, AccountBL>();
     services.AddTransient <IUserRepository, UserRepository>();
     services.AddTransient <IUserBL, UserBL>();
     services.AddTransient <ITodoRepository, TodoRepository>();
     services.AddTransient <ITodoBL, TodoBL>();
     var mapperConfiguration = new MapperConfiguration(cfg =>
     {
         cfg.AddProfile(new MapperModelConfiguration());
     });
     IMapper mapper = mapperConfiguration.CreateMapper();
     services.AddSingleton(mapper);
 }
예제 #40
0
        public List <CommContracts.MaterialDoctorAdvice> getAllMaterialDoctorAdvice(int RegistrationID)
        {
            List <CommContracts.MaterialDoctorAdvice> list = new List <CommContracts.MaterialDoctorAdvice>();

            using (DAL.HisContext ctx = new DAL.HisContext())
            {
                var query = from a in ctx.MaterialDoctorAdvices
                            where a.RegistrationID == RegistrationID
                            select a;
                foreach (DAL.MaterialDoctorAdvice ass in query)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap <DAL.MaterialDoctorAdvice, CommContracts.MaterialDoctorAdvice>();
                    });
                    var mapper = config.CreateMapper();

                    CommContracts.MaterialDoctorAdvice temp = mapper.Map <CommContracts.MaterialDoctorAdvice>(ass);
                    list.Add(temp);
                }
            }
            return(list);
        }
예제 #41
0
        // GET: Autor/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            QueryAutor queryAutor = new QueryAutor(db);
            var        config     = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Autor, AutorViewModel>();
            });
            IMapper iMapper = config.CreateMapper();

            Autor request = queryAutor.getAutorXId((int)id);

            if (request == null)
            {
                return(HttpNotFound());
            }
            var autor = iMapper.Map <Autor, AutorViewModel>(request);

            return(View(autor));
        }
        internal static void RegisterContainer(HttpConfiguration httpConfiguration)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new UserMappingProfile());
            });

            builder.RegisterInstance(config.CreateMapper()).As <IMapper>().SingleInstance();
            //Test data - in memory
            builder.RegisterType <TestUserData>().As <IUserData>().SingleInstance();
            //Data - database
            //builder.RegisterType<SqlUserData>().As<IUserData>().InstancePerRequest();
            //builder.RegisterType<AdministrationDbContext>().InstancePerRequest();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
예제 #43
0
        public async Task When_Apply_Is_Given_It_Should_Be_Return_Ok()
        {
            Apply apply = new Apply()
            {
                Id = 10000, AnnouncementId = 1, ResumeId = 1
            };

            var applyServiceMock = new Mock <IApplyService>();

            applyServiceMock.Setup(p => p.GetByIdAsync(10000)).Returns(Task.FromResult(apply));

            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MapProfile());
            });
            var mapper = mockMapper.CreateMapper();

            var applysController = new ApplysController(applyServiceMock.Object, mapper, Mock.Of <ILogger <ApplysController> >());

            var actionResult = await applysController.GetById(10000);

            actionResult.Should().BeOfType <OkObjectResult>();
        }
        public void Mapper_Should_Allow_Overriding_Of_Destination_Type()
        {
            var order = new Order()
            {
                Customer = new Customer()
                {
                    Id = 1, Name = "A"
                }
            };

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Order, OrderDTO>();
                cfg.CreateMap <Customer, CustomerDTO>();
                cfg.CreateMap <Customer, CustomerStubDTO>().As <CustomerDTO>();
            });
            var orderDto = config.CreateMapper().Map <Order, OrderDTO>(order);

            var customerDto = (CustomerDTO)orderDto.Customer;

            "A".ShouldEqual(customerDto.Name);
            1.ShouldEqual(customerDto.Id);
        }
예제 #45
0
        public CommContracts.InspectDoctorAdvice GetInspectDoctorAdvice(int Id)
        {
            CommContracts.InspectDoctorAdvice inspectDoctorAdvice = new CommContracts.InspectDoctorAdvice();
            using (DAL.HisContext ctx = new DAL.HisContext())
            {
                var query = from t in ctx.InspectDoctorAdvices
                            where t.ID == Id
                            select t;
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <DAL.InspectDoctorAdvice, CommContracts.InspectDoctorAdvice>();
                });
                var mapper = config.CreateMapper();


                foreach (var tem in query)
                {
                    inspectDoctorAdvice = mapper.Map <CommContracts.InspectDoctorAdvice>(tem);
                    break;
                }
            }
            return(inspectDoctorAdvice);
        }
예제 #46
0
        public List <CommContracts.AssayCharge> GetAllChargeFromAssayAdvice(int AdviceID)
        {
            List <CommContracts.AssayCharge> list = new List <CommContracts.AssayCharge>();

            using (DAL.HisContext ctx = new DAL.HisContext())
            {
                var query = from a in ctx.AssayCharges
                            where a.AssayDoctorAdviceID == AdviceID
                            select a;
                foreach (DAL.AssayCharge ass in query)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap <DAL.AssayCharge, CommContracts.AssayCharge>();
                    });
                    var mapper = config.CreateMapper();

                    CommContracts.AssayCharge temp = mapper.Map <CommContracts.AssayCharge>(ass);
                    list.Add(temp);
                }
            }
            return(list);
        }
        public static void SetupMapping(this ContainerBuilder containerBuilder)
        {
            var config = new MapperConfiguration(x =>
            {
                /* Service mappings */
                x.AddProfile <ProductProfile>();
                x.AddProfile <ProductReviewProfile>();
                x.AddProfile <UserProfile>();
                x.AddProfile <OrderProfile>();
                x.AddProfile <PaymentProfile>();
                x.AddProfile <FeedbackProfile>();

                /* Service agent mappings */
                x.AddProfile <FirebaseServiceAgentProfile>();
                x.AddProfile <MultiParcelServiceAgentProfile>();
            });

            var mapper = config.CreateMapper();

            containerBuilder.RegisterInstance(mapper)
            .As <IMapper>()
            .SingleInstance();
        }
예제 #48
0
            public void Mapper_respects_condition()
            {
                var _c1Called = false;
                var _c2Called = false;
                var config    = new MapperConfiguration(cfg => cfg.CreateMap <EnumTestSource, EnumTestDest>()
                                                        .ForMember(m => m.Prop1, o =>
                {
                    o.Condition((_, srcProp, destProp) => { _c1Called = true; return(srcProp != null); });
                    o.ResolveUsing(f => f.Prop1?.Aggregate((current, next) => current | next));
                })
                                                        .ForMember(m => m.Prop2, o =>
                {
                    o.Condition((_, srcProp, destProp) => { _c2Called = true; return(srcProp != null); });
                    o.ResolveUsing(f => f.Prop2?.Aggregate((current, next) => current | next));
                }));
                var src = new EnumTestSource {
                    Prop1 = new[] { Enum1.One }, Prop2 = null
                };
                var dest = config.CreateMapper().Map <EnumTestDest>(src); // will throw

                _c1Called.ShouldBeTrue();
                _c2Called.ShouldBeTrue();
            }
        public async Task GivenStartNumber_WhenGetFizzBuzz_ThenReturnExpectedResult()
        {
            // Arrange
            var configuration = GetConfig();
            var mockMapper    = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            var mapper = mockMapper.CreateMapper();

            var fizzBuzzService = new FizzBuzzAppService(mapper, new FizzBuzzService(new NullLogger <FizzBuzzService>()));
            var sut             = new FizzBuzzController(configuration, new NullLogger <FizzBuzzController>(), fizzBuzzService);

            // Act
            var fizzBuzzResult = await sut.GetFizzBuzz(1);

            // Assert
            Assert.IsInstanceOf <OkObjectResult>(fizzBuzzResult.Result);
            var okObjectResult = (OkObjectResult)fizzBuzzResult.Result;

            Assert.IsInstanceOf <FizzBuzzDto>(okObjectResult.Value);
            Assert.AreEqual(30, ((FizzBuzzDto)okObjectResult.Value).FizzBuzzResults.Count);
        }
        public void TestUsingProfileWithIgnore()
        {
            //SETUP
            var entity = new Author {
                AuthorId = 1, Name = "Start Name", Email = "*****@*****.**"
            };
            var profile = new UnitTestProfile(true);

            profile.AddWriteMap <WriteAuthorReadOnlyDto, Author>();
            var config = new MapperConfiguration(cfg => cfg.AddProfile(profile));

            //ATTEMPT
            var dto = new WriteAuthorReadOnlyDto {
                AuthorId = 123, Name = "New Name", Email = "*****@*****.**"
            };
            var mapper = config.CreateMapper();
            var data   = mapper.Map(dto, entity);

            //VERIFY
            data.Name.ShouldEqual("New Name");       //changed
            data.AuthorId.ShouldEqual(123);          //changed
            data.Email.ShouldEqual("*****@*****.**"); //not changed - ReadOnly
        }
예제 #51
0
        // GET: Farmer/Pricing/Create
        public ActionResult AddCropPrice(int?farmCropId)
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <CropPrice, CropPriceViewModel>();
            });
            CropPriceViewModel model   = null;
            IMapper            iMapper = config.CreateMapper();

            //if (Id.HasValue && Id.Value > 0)
            //{
            //    CropPrice updateCropPrice = CropPriceService.GetById(Id.Value);
            //    model = iMapper.Map<CropPrice, PriceViewModel>(updateCropPrice);
            //    model.MeasurementDropDown = base.GetMeasurement(updateCropPrice.Id);

            //    return PartialView(model);
            //}

            model                     = iMapper.Map <CropPrice, CropPriceViewModel>(new CropPrice());
            model.FarmCropId          = farmCropId.Value;
            model.MeasurementDropDown = base.GetMeasurement(null);
            return(PartialView("_AddCropPrice", model));
        }
예제 #52
0
        public List <CommContracts.SignalType> GetAllSignalType(string strName = "")
        {
            List <CommContracts.SignalType> list = new List <CommContracts.SignalType>();

            using (DAL.HisContext ctx = new DAL.HisContext())
            {
                var query = from a in ctx.SignalTypes
                            where a.WorkType.Name.StartsWith(strName)
                            select a;
                foreach (DAL.SignalType ass in query)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap <DAL.SignalType, CommContracts.SignalType>();
                    });
                    var mapper = config.CreateMapper();

                    CommContracts.SignalType temp = mapper.Map <CommContracts.SignalType>(ass);
                    list.Add(temp);
                }
            }
            return(list);
        }
예제 #53
0
        public override void Initialise()
        {
            var config = new MapperConfiguration(cfg =>
            {
                //cfg.CreateMap<Associate, Associate>();
                //cfg.CreateMap<AssociateTag, AssociateTag>();
                //cfg.CreateMap<Branch, Branch>();
                //cfg.CreateMap<BranchTag, BranchTag>();
                //cfg.CreateMap<Location, Location>();
                //cfg.CreateMap<LocationTag, LocationTag>();
                //cfg.CreateMap<Movement, Movement>();
                //cfg.CreateMap<MovementTag, MovementTag>();
                //cfg.CreateMap<Product, Product>();
                //cfg.CreateMap<ProductTag, ProductTag>();
                //cfg.CreateMap<Tag, Tag>();
                //cfg.CreateMap<Warehouse, Warehouse>();
                //cfg.CreateMap<WarehouseTag, WarehouseTag>();
                //cfg.CreateMap<WarehouseProduct, WarehouseProduct>();
                //cfg.CreateMap<WarehouseProductTag, WarehouseProductTag>();
            });

            _mapper = config.CreateMapper();
        }
예제 #54
0
        public GetHolidayListHandlerTest(VacationTrackingDbContextFixture fixture)
        {
            _fixture = fixture;
            _logger  = new NullLogger <GetHolidayListHandler>();

            //auto mapper configuration
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(typeof(Service.Mapper.AutoMapping));
            });

            _mapper = mockMapper.CreateMapper();


            _fixture.Initialize(true, () =>
            {
                _fixture.Context.Companies.AddRange(Seed.Companies());
                _fixture.Context.Users.AddRange(Seed.Users());
                _fixture.Context.Teams.AddRange(Seed.Teams());
                _fixture.Context.TeamMembers.AddRange(Seed.TeamMembers());
                _fixture.Context.SaveChanges();
            });
        }
예제 #55
0
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = _config.GetConnectionString("DefaultConnection");

            var configMapper = new MapperConfiguration(c =>
            {
                c.AddProfile(new ApplicationProfile());
            });
            var mapper = configMapper.CreateMapper();


            services.AddMvc()
            .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );
            services.AddDbContext <AledrogoContext>(options => options.UseSqlServer(connectionString));
            services.AddIdentity <User, IdentityRole>().AddEntityFrameworkStores <AledrogoContext>();
            services.AddSingleton(mapper);
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IProductRepository, ProductRespository>();
            services.AddScoped <IAddressRespository, AddressRespository>();
            services.AddScoped <ICategoryCache, CategoryCache>();
        }
        public async Task <IActionResult> Insert(SaleInsertViewModel viewmodel)
        {
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <SaleInsertViewModel, SaleDTO>();
            });
            IMapper mapper = configuration.CreateMapper();
            // new SERService().GetSERByID(4);
            //Transforma o ClienteInsertViewModel em um ClienteDTO
            SaleDTO dto = mapper.Map <SaleDTO>(viewmodel);

            try
            {
                await _saleService.Insert(dto);

                return(RedirectToAction("Index", "Category"));
            }
            catch (Exception ex)
            {
                ViewBag.Erros = ex.Message;
            }
            return(View());
        }
        public async void GetLibroPorId()
        {
            //System.Diagnostics.Debugger.Launch();
            var mockContexto = CrearContexto();

            var mapConfig = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingTest());
            });

            var mapper = mapConfig.CreateMapper();

            var request = new ConsultaFiltro.LibroUnico();

            request.LibroId = Guid.Empty;

            var manejador = new ConsultaFiltro.Manejador(mockContexto.Object, mapper);

            var libro = await manejador.Handle(request, new System.Threading.CancellationToken());

            Assert.NotNull(libro);
            Assert.True(libro.LibreriaMaterialId == Guid.Empty);
        }
예제 #58
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <CompanyDbContext>(options =>
                                                     options.UseSqlServer(Configuration.GetConnectionString("CompanyManagerDb")));

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddTransient <IServiceBusResponder, ServiceBusResponder>();
            services.AddTransient <ICompanyLogic, CompanyLogic>();
            services.AddTransient <IEmployeeLogic, EmployeeLogic>();

            // Cause a problem when AddMigration is runned in PackageManagerConsole!!!
            IBus bus = RabbitHutch.CreateBus("host=localhost");

            services.AddSingleton(bus);
        }
예제 #59
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // Dependency injection support for AutoMapper
            // https://docs.automapper.org/en/latest/Dependency-injection.html
            var configurationExpression = new MapperConfigurationExpression();

            AutoMapperConfiguration.RegisterMappings().ForEach(p => configurationExpression.AddProfile(p));
            var automapperConfig = new MapperConfiguration(configurationExpression);

            automapperConfig.AssertConfigurationIsValid();
            services.TryAddSingleton(automapperConfig.CreateMapper());

            services.AddLogging(
                builder =>
            {
                builder.AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("NToastNotify", LogLevel.Warning)
                .AddConsole();
            });
        }
예제 #60
0
        public void Correctly_map_payment_request_to_payment()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile <PaymentMappingProfile>());
            var mapper = config.CreateMapper();
            var dto    = new PaymentRequestDto
            {
                Amount      = 999,
                CardNumber  = FAKE_CREDIT_CARD_NO,
                Currency    = "GBP",
                Cvv         = "123",
                ExpiryMonth = 6,
                ExpiryYear  = 25
            };

            var payment = mapper.Map <PaymentRequestDto, Payment>(dto);

            payment.Amount.Amount.Should().Be(dto.Amount);
            payment.Amount.Currency.Should().Be(dto.Currency);
            payment.Card.Cvv.Should().Be(dto.Cvv);
            payment.Card.ExpiryMonth.Should().Be(dto.ExpiryMonth);
            payment.Card.ExpiryYear.Should().Be(dto.ExpiryYear);
            payment.Card.Number.Should().Be(dto.CardNumber);
        }