// // GET: /Account/UserInfo public ActionResult UserInfo() { var mapper = new MapperConfiguration(cfg => cfg.CreateMap<ApplicationUser, UserModel>()).CreateMapper(); var user = mapper.Map<ApplicationUser, UserModel>(UserManager.FindById(User.Identity.GetUserId())); return View(user); }
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(); }
public void Example() { var config = new MapperConfiguration(cfg => { cfg.ConstructServicesUsing(ObjectFactory.GetInstance); }); }
static ClientMappers() { Mapper = new MapperConfiguration(config => { config.CreateMap<Entities.Client, Client>(MemberList.Destination) .ForMember(x => x.AllowedGrantTypes, opt => opt.MapFrom(src => src.AllowedGrantTypes.Select(x => x.GrantType))) .ForMember(x => x.RedirectUris, opt => opt.MapFrom(src => src.RedirectUris.Select(x => x.RedirectUri))) .ForMember(x => x.PostLogoutRedirectUris, opt => opt.MapFrom(src => src.PostLogoutRedirectUris.Select(x => x.PostLogoutRedirectUri))) .ForMember(x => x.AllowedScopes, opt => opt.MapFrom(src => src.AllowedScopes.Select(x => x.Scope))) .ForMember(x => x.ClientSecrets, opt => opt.MapFrom(src => src.ClientSecrets.Select(x => x))) .ForMember(x => x.Claims, opt => opt.MapFrom(src => src.Claims.Select(x => new Claim(x.Type, x.Value)))) .ForMember(x => x.IdentityProviderRestrictions, opt => opt.MapFrom(src => src.IdentityProviderRestrictions.Select(x => x.Provider))) .ForMember(x => x.AllowedCorsOrigins, opt => opt.MapFrom(src => src.AllowedCorsOrigins.Select(x => x.Origin))); config.CreateMap<ClientSecret, Secret>(MemberList.Destination) .ForMember(dest => dest.Type, opt => opt.Condition(srs => srs != null)); config.CreateMap<Client, Entities.Client>(MemberList.Source) .ForMember(x => x.AllowedGrantTypes, opt => opt.MapFrom(src => src.AllowedGrantTypes.Select(x => new ClientGrantType {GrantType = x}))) .ForMember(x => x.RedirectUris, opt => opt.MapFrom(src => src.RedirectUris.Select(x => new ClientRedirectUri {RedirectUri = x}))) .ForMember(x => x.PostLogoutRedirectUris, opt => opt.MapFrom(src => src.PostLogoutRedirectUris.Select(x => new ClientPostLogoutRedirectUri {PostLogoutRedirectUri = x}))) .ForMember(x => x.AllowedScopes, opt => opt.MapFrom(src => src.AllowedScopes.Select(x => new ClientScope {Scope = x}))) .ForMember(x => x.Claims, opt => opt.MapFrom( src => src.Claims.Select(x => new ClientClaim {Type = x.Type, Value = x.Value}))) .ForMember(x => x.IdentityProviderRestrictions, opt => opt.MapFrom(src => src.IdentityProviderRestrictions.Select(x => new ClientIdPRestriction {Provider = x}))) .ForMember(x => x.AllowedCorsOrigins, opt => opt.MapFrom(src => src.AllowedCorsOrigins.Select(x => new ClientCorsOrigin {Origin = x}))); config.CreateMap<Secret, ClientSecret>(MemberList.Source); }).CreateMapper(); }
public NullChildItemTest() { _config = new MapperConfiguration(cfg => { cfg.CreateMap<Parent, ParentDto>(); cfg.AllowNullCollections = true; }); }
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"); }
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; }
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 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); }
public static MapperConfiguration ConfigMapper() { var config = new MapperConfiguration(cfg => cfg.CreateMap<User, UserWeChatRequestDto>() .ForMember(d => d.openid, opt => opt.MapFrom(s => s.WeChatOpenID))); return config; }
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); }
// <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 }
/// <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 }
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(); }
// 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()); }
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 ChatController(IUserService userservice, IChatRoomService chatService, IMessageService messageService, IFileService fileService) { UserService = userservice; ChatService = chatService; MessageService = messageService; FileService = fileService; config = new MapperConfiguration(cfg => { cfg.CreateMap<User, UserChatViewModel>() .ForMember(dest => dest.UserFoto, opt => opt.MapFrom(src => src.UserFoto. Insert(src.UserFoto.LastIndexOf('/') + 1, "mini/"))); cfg.CreateMap<ChatRoom, ChatRoomPartialViewModel>(); cfg.CreateMap<Message, MessageViewModels>() .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.User.UserName)) .ForMember(dest => dest.PathFotoUser, opt => opt.MapFrom(src => src.User.UserFoto. Insert(src.User.UserFoto.LastIndexOf('/') + 1, "mini/"))) .ForMember(dest => dest.FileId, opt => opt.MapFrom(src => src.File.Id)) .ForMember(dest => dest.FileName, opt => opt.MapFrom(src => src.File.NameFile)); cfg.CreateMap<ChatRoom, ChatRoomViewModels>() .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.User.UserName)) .ForMember(dest => dest.Users, opt => opt.MapFrom(src => src.Users)) .ForMember(dest => dest.Messages, opt => opt.MapFrom(src => src.Messages)); }); }
static AutoMapperConfiguration() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Client, Client>() .ForMember(m => m.ID, x => x.Ignore()) .AfterMap((source, dest) => { if (dest.Review != null) { if (dest.Review.ID == 0 && dest.ID > 0) dest.Review.ID = dest.ID; // fix on-to-one relationship ID matching dest.Review.Client = dest; } }); // ignore object fields, will be reassigned //cfg.CreateMap<Job, Job>() // .ForMember(m => m.Appointment, // x => x.ResolveUsing((result, job) => AppointmentsRepository.Instance.CreateOrUpdate(job.Appointment))) // .ForMember(m => m.Clerk, // x => x.ResolveUsing((result, job) => UsersRepository.Instance.CreateOrUpdate(job.Clerk))) // .ForMember(m => m.Invoice, // x => x.ResolveUsing((result, job) => InvoicesRepository.Instance.CreateOrUpdate(job.Invoice))) // .ForMember(m => m.JobType, // x => x.ResolveUsing((result, job) => JobTypeRepository.Instance.CreateOrUpdate(job.JobType))) // .ForMember(m => m.PropertyType, // x => x.ResolveUsing((result, job) => PropertyTypeRepository.Instance.CreateOrUpdate(job.PropertyType))) // .ForMember(m => m.Status, // x => x.ResolveUsing((result, job) => StatusRepository.GetStatusById(job.StatusID))) // ; }); configuration = config; }
protected override void Establish_context() { _configuration = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); }
public void AutoMapper_DomainToDataMappingTest() { var config = new MapperConfiguration(cfg => { DomainToDataMapping.CreateMaps(cfg); }); config.AssertConfigurationIsValid(); }
public TodoListService(IUnitOfWork uow,ITodoListRepository todoListRepository) { _todoListRepository = todoListRepository; db = uow; var config = new MapperConfiguration(cfg => { cfg.CreateMap<TodoListEntity, TodoListDTO>(); }); _mapper = config.CreateMapper(); }
public static void Initialize() { MapperConfig = new MapperConfiguration(mapper => { mapper.CreateMap<ParentTouristSite, FullTouristSiteResponseModel>() .ForMember( m => m.Type, opts => opts.MapFrom(p => (int)p.Type)); ; mapper.CreateMap<TouristSite, TouristSiteResponseModel>() .ForMember( m => m.Rating, opts => opts.MapFrom(t => t.Ratings.Count > 0 ? t.Ratings.Sum(r => r.Value) / t.Ratings.Count : 0)) .ForMember( m => m.Status, opts => opts.MapFrom(t => (int)t.Status)); mapper.CreateMap<TouristSite, SimpleTouristSiteResponseModel>(); mapper.CreateMap<ParentTouristSite, SimpleParentTouristSiteResponseModel>(); mapper.CreateMap<User, ScoreboardResponseModel>().ForMember( m => m.Rating, opts => opts.MapFrom(u => u.CalculatedRating)); mapper.CreateMap<User, FullUserResponseModel>(); mapper.CreateMap<Badge, BadgeResponseModel>().ForMember( m => m.Title, opts => opts.MapFrom(b => Enum.GetName(typeof(BadgeTitle), b.Title))); }); MapperConfig.AssertConfigurationIsValid(); }
public void Install(IWindsorContainer container, IConfigurationStore store) { // register value resolvers container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn(typeof(IValueResolver<,,>))); // register profiles container.Register(Types.FromThisAssembly().BasedOn<Profile>().WithServiceBase().Configure(c => c.Named(c.Implementation.FullName)).LifestyleTransient()); var profiles = container.ResolveAll<Profile>(); var config = new MapperConfiguration(cfg => { foreach (var profile in profiles) { cfg.AddProfile(profile); } }); container.Register(Component.For<MapperConfiguration>() .UsingFactoryMethod(() => config)); container.Register( Component.For<IMapper>().UsingFactoryMethod(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper(ctx.Resolve))); var mapper = container.Resolve<IMapper>(); mapper.ConfigurationProvider.AssertConfigurationIsValid(); }
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); }
public static void Configure() { Config = new MapperConfiguration(cfg =>{}); var profileConfig = (IConfiguration) Config; AutoMapperConfiguration.Configure(profileConfig); }
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); }
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; }
public void Example() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Entity, EntityViewModel>() .ForMember(m => m.SubEntityNames, o => o.MapFrom(f => f.SubEntities.Select(e => e.Name))); }); var expression = config.ExpressionBuilder.CreateMapExpression<Entity, EntityViewModel>(); var entity = new Entity { EntityID = 1, SubEntities = { new SubEntity {Name = "First", Description = "First Description"}, new SubEntity {Name = "Second", Description = "First Description"}, }, Title = "Entities" }; var viewModel = expression.Compile()(entity); Assert.Equal(viewModel.EntityID, entity.EntityID); Assert.Contains("First", viewModel.SubEntityNames.ToArray()); Assert.Contains("Second", viewModel.SubEntityNames.ToArray()); }
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(); }
static EntitiesMap() { Config = new MapperConfiguration(cfg => { cfg.CreateMap<IdentityScope, IdentityServer3.Core.Models.Scope>(MemberList.Destination) .ForMember(x => x.Claims, opts => opts.MapFrom(src => src.ScopeClaims.Select(x => x))) .ForMember(x => x.ScopeSecrets, opts => opts.MapFrom(src => src.ScopeSecrets.Select(x => x))); cfg.CreateMap<IdentityServer3.EntityFramework.Entities.ScopeClaim, IdentityServer3.Core.Models.ScopeClaim>(MemberList.Destination); cfg.CreateMap<IdentityServer3.EntityFramework.Entities.ScopeSecret, IdentityServer3.Core.Models.Secret>(MemberList.Destination) .ForMember(dest => dest.Type, opt => opt.Condition(srs => srs.Value != null)); cfg.CreateMap<IdentityServer3.EntityFramework.Entities.ClientSecret, IdentityServer3.Core.Models.Secret>(MemberList.Destination) .ForMember(dest => dest.Type, opt => opt.Condition(srs => srs.Value != null)); cfg.CreateMap<IdentityClient, IdentityServer3.Core.Models.Client>(MemberList.Destination) .ForMember(x => x.UpdateAccessTokenClaimsOnRefresh, opt => opt.MapFrom(src => src.UpdateAccessTokenOnRefresh)) .ForMember(x => x.AllowAccessToAllCustomGrantTypes, opt => opt.MapFrom(src => src.AllowAccessToAllGrantTypes)) .ForMember(x => x.AllowedCustomGrantTypes, opt => opt.MapFrom(src => src.AllowedCustomGrantTypes.Select(x => x.GrantType))) .ForMember(x => x.RedirectUris, opt => opt.MapFrom(src => src.RedirectUris.Select(x => x.Uri))) .ForMember(x => x.PostLogoutRedirectUris, opt => opt.MapFrom(src => src.PostLogoutRedirectUris.Select(x => x.Uri))) .ForMember(x => x.IdentityProviderRestrictions, opt => opt.MapFrom(src => src.IdentityProviderRestrictions.Select(x => x.Provider))) .ForMember(x => x.AllowedScopes, opt => opt.MapFrom(src => src.AllowedScopes.Select(x => x.Scope))) .ForMember(x => x.AllowedCorsOrigins, opt => opt.MapFrom(src => src.AllowedCorsOrigins.Select(x => x.Origin))) .ForMember(x => x.Claims, opt => opt.MapFrom(src => src.Claims.Select(x => new Claim(x.Type, x.Value)))); }); }
public void fix() { using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { // ad info if (!newthreadcontext.TemplateDB.Any()) { var adinfo = migrateDB.TemplatesDB.Include("RecommendedInfo"); foreach (var i in adinfo) { var t = newthreadcontext.TemplateDB.Add(new AdInfoTemplate() { TemplateName = i.TemplateName, RecommendedInfo = new List <AdInfoString>() }); foreach (var x in i.RecommendedInfo) { t.RecommendedInfo.Add(new AdInfoString() { Name = x.Name }); } } newthreadcontext.SaveChanges(); } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.MiscInfoDB.Any()) { var make = migrateDB.MakeDB.ToList(); foreach (var i in make) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleMake" }); } var adtype = migrateDB.TypesDB.ToList(); foreach (var i in adtype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Value, Name = i.Name, Descriptor = "AdType" }); } var bodytype = migrateDB.BodyTypeDB.ToList(); foreach (var i in bodytype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Type, Descriptor = "VehicleBodyType" }); } var transmission = migrateDB.TransmissionDB.ToList(); foreach (var i in transmission) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleTransmission" }); } var drivetrain = migrateDB.DrivetrainDB.ToList(); foreach (var i in drivetrain) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleDrivetrain" }); } var condition = migrateDB.ConditionDB.ToList(); foreach (var i in condition) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleCondition" }); } var fueltype = migrateDB.FuelDB.ToList(); foreach (var i in fueltype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleFuelType" }); } var priceinfo = migrateDB.PriceInfoDB.ToList(); foreach (var i in priceinfo) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "PriceInfo" }); } newthreadcontext.SaveChanges(); } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.CategoryDB.Any()) { var cat = migrateDB.CategoryDB.Include("SubCategories.AdInfoTemplate").ToList(); foreach (var i in cat) { var currentcat = newthreadcontext.CategoryDB.Add(new Category() { Name = i.Name, TotalClassifiedAdsCount = i.TotalClassifiedAdsCount }); List <SubCategory> scl = new List <SubCategory>(); foreach (var j in i.SubCategories) { if (j.AdInfoTemplate != null) { var template = newthreadcontext.TemplateDB.SingleOrDefault(x => x.TemplateName.Equals(j.AdInfoTemplate.TemplateName)); scl.Add(new SubCategory() { Category = currentcat, Name = j.Name, stringId = j.stringId, AdInfoTemplate = template }); } else { scl.Add(new SubCategory() { Category = currentcat, Name = j.Name, stringId = j.stringId }); } } newthreadcontext.SubCategoryDB.AddRange(scl); } newthreadcontext.SaveChanges(); } } } if (!RoleManager.RoleExists("Admin")) { RoleManager.Create(new IdentityRole() { Name = "Admin" }); } if (!RoleManager.RoleExists("Banned")) { RoleManager.Create(new IdentityRole() { Name = "Banned" }); } if (!RoleManager.RoleExists("Moderator")) { RoleManager.Create(new IdentityRole() { Name = "Moderator" }); } if (!RoleManager.RoleExists("Premium")) { RoleManager.Create(new IdentityRole() { Name = "Premium" }); } if (!RoleManager.RoleExists("User")) { RoleManager.Create(new IdentityRole() { Name = "User" }); } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.CountryDB.Any()) { var trinidad = newthreadcontext.CountryDB.Add(new Country() { Name = "Trinidad" }); var tobago = newthreadcontext.CountryDB.Add(new Country() { Name = "Tobago" }); newthreadcontext.SaveChanges(); } if (!newthreadcontext.RegionDB.Any()) { var trinidad = newthreadcontext.CountryDB.SingleOrDefault(x => x.Name.Equals("Trinidad")); List <Region> trinR = new List <Region>() { new Region() { Country = trinidad, Name = "Port of Spain" }, new Region() { Country = trinidad, Name = "San Fernando" }, new Region() { Country = trinidad, Name = "Marabella" }, new Region() { Country = trinidad, Name = "Chaguanas" }, new Region() { Country = trinidad, Name = "Cunupia" }, new Region() { Country = trinidad, Name = "Endeavour" }, new Region() { Country = trinidad, Name = "Felicity" }, new Region() { Country = trinidad, Name = "Montrose" }, new Region() { Country = trinidad, Name = "Arima" }, new Region() { Country = trinidad, Name = "Point Fortin" }, new Region() { Country = trinidad, Name = "Guapo" }, new Region() { Country = trinidad, Name = "Techier" }, new Region() { Country = trinidad, Name = "Claxton Bay" }, new Region() { Country = trinidad, Name = "Diego Martin" }, new Region() { Country = trinidad, Name = "Maraval" }, new Region() { Country = trinidad, Name = "Westmoorings" }, new Region() { Country = trinidad, Name = "Penal" }, new Region() { Country = trinidad, Name = "Debe" }, new Region() { Country = trinidad, Name = "Moruga" }, new Region() { Country = trinidad, Name = "Princes Town" }, new Region() { Country = trinidad, Name = "Mayaro" }, new Region() { Country = trinidad, Name = "Rio Claro" }, new Region() { Country = trinidad, Name = "Guayaguayare" }, new Region() { Country = trinidad, Name = "Barataria" }, new Region() { Country = trinidad, Name = "Laventille" }, new Region() { Country = trinidad, Name = "Morvant" }, new Region() { Country = trinidad, Name = "St. Joseph" }, new Region() { Country = trinidad, Name = "San Juan" }, new Region() { Country = trinidad, Name = "Guaico" }, new Region() { Country = trinidad, Name = "Sangre Grande" }, new Region() { Country = trinidad, Name = "Toco" }, new Region() { Country = trinidad, Name = "Valencia" }, new Region() { Country = trinidad, Name = "Cedros" }, new Region() { Country = trinidad, Name = "Fyzabad" }, new Region() { Country = trinidad, Name = "La Brea" }, new Region() { Country = trinidad, Name = "Santa Flora" }, new Region() { Country = trinidad, Name = "Siparia" }, new Region() { Country = trinidad, Name = "Arouca" }, new Region() { Country = trinidad, Name = "Curepe" }, new Region() { Country = trinidad, Name = "Piarco" }, new Region() { Country = trinidad, Name = "St Augustine" }, new Region() { Country = trinidad, Name = "Trincity" }, new Region() { Country = trinidad, Name = "Tunapuna" }, new Region() { Country = trinidad, Name = "Couva" }, new Region() { Country = trinidad, Name = "Talparo" }, new Region() { Country = trinidad, Name = "Tabaquite" }, new Region() { Country = trinidad, Name = "Point Lisas" }, new Region() { Country = trinidad, Name = "Caroni" }, new Region() { Country = trinidad, Name = "Santa Cruz" }, new Region() { Country = trinidad, Name = "Freeport" } }; trinidad.Regions = trinR; trinidad.RegionCount = trinR.Count; newthreadcontext.SaveChanges(); var tobago = newthreadcontext.CountryDB.SingleOrDefault(x => x.Name.Equals("Tobago")); List <Region> tobaR = new List <Region>() { new Region() { Country = tobago, Name = "Charlotteville" }, new Region() { Country = tobago, Name = "Roxborough" }, new Region() { Country = tobago, Name = "Scarborough" }, new Region() { Country = tobago, Name = "Canaan" }, new Region() { Country = tobago, Name = "Plymouth" }, new Region() { Country = tobago, Name = "Moriah" } }; tobago.Regions = tobaR; tobago.RegionCount = tobaR.Count; newthreadcontext.SaveChanges(); } } } using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!UserManager.Users.Any()) { var userwithad = migrateDB.UserProfiles.ToList(); foreach (var user in userwithad) { ApplicationUser newuser = new ApplicationUser() { Email = user.Email, UserName = !String.IsNullOrEmpty(user.UserName) ? user.Email.Split('@').First() : user.UserName, StringId = user.StringId, PhoneNumber = user.ContactNumber }; var result = UserManager.Create(newuser); if (result.Succeeded) { string query = "SELECT green_kappakappa.webpages_Roles.RoleName FROM(green_kappakappa.webpages_Roles INNER JOIN green_kappakappa.webpages_UsersInRoles ON green_kappakappa.webpages_Roles.RoleId = green_kappakappa.webpages_UsersInRoles.RoleId) INNER JOIN UserProfile ON green_kappakappa.webpages_UsersInRoles.UserId = " + user.UserId; var role = migrateDB.Database.SqlQuery <string>(query).ToList(); UserManager.AddToRole(newuser.Id, role.First()); } } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { ICollection <ClassifiedAdOld> ads = new List <ClassifiedAdOld>(); using (MigrationDbContext migrateDB = new MigrationDbContext()) { ads = migrateDB.ClassifiedDB.Include("UserCreator").Include("Country").Include("Region").Include("AdInfo").Include("AdPhotos").Include("Category").Include("SubCategory").Include("Reports").ToList(); } if (!newthreadcontext.ClassifiedDB.Any()) { var config = new MapperConfiguration(r => { r.CreateMap <CategoryOld, Category>(); r.CreateMap <SubCategoryOld, SubCategory>() .ForMember(dest => dest.ClassifiedAds, opt => opt.Ignore()); r.CreateMap <InfoOld, Info>(); r.CreateMap <PhotoOld, Photo>(); r.CreateMap <AdPromotionOld, AdPromotion>(); }); IMapper mapper = config.CreateMapper(); foreach (var ad in ads) { var i = newthreadcontext.ClassifiedDB.Add(new ClassifiedAd()); i.AdType = ad.AdType; i.StringId = ad.StringId; i.ContactPrivacy = ad.ContactPrivacy; i.Description = ad.Description; i.EditCount = ad.EditCount; i.EditTimeStamp = ad.EditTimeStamp; i.FeaturedAdStatus = ad.FeaturedAdStatus; i.HtmlFreeDescription = ad.HtmlFreeDescription; i.MyProperty = ad.MyProperty; i.Price = ad.Price; i.PriceInfo = ad.PriceInfo; i.TimeStamp = ad.TimeStamp; i.Title = ad.Title; i.UrgentAdStatus = ad.UrgentAdStatus; i.UserContactEmail = ad.UserContactEmail; i.UserContactName = ad.UserContactName; i.UserContactPhone = ad.UserContactPhone; i.UserContactPhone2 = ad.UserContactPhone2; i.UserContactPhone3 = ad.UserContactPhone3; i.Views = ad.Views; var sc = newthreadcontext.SubCategoryDB.Include("Category").FirstOrDefault(x => x.stringId.Equals(ad.SubCategory.stringId)); i.SubCategory = sc; i.Category = sc.Category; var user = newthreadcontext.Users.FirstOrDefault(x => x.Email.Equals(ad.UserCreator.Email)); i.UserCreator = user; var region = newthreadcontext.RegionDB.Include("Country").FirstOrDefault(x => ad.Region.Name.Contains(x.Name)); i.Region = region; i.Country = region.Country; foreach (var ap in ad.AdPhotos) { var pho = new Photo() { AdListThumbnail = ap.AdListThumbnail, ClassifiedAd = i, ContentType = ap.ContentType, CountNum = ap.CountNum, FileName = ap.FileName, SetThumbnail = ap.SetThumbnail, StringId = ap.StringId }; pho.ClassifiedAd.AdPhotos.Add(pho); } foreach (var ai in ad.AdInfo) { var inf = new Info() { ClassifiedAd = i, Description = ai.Description, Name = ai.Name, IntDescription = ai.IntDescription }; inf.ClassifiedAd.AdInfo.Add(inf); } foreach (var rep in ad.Reports) { var crep = new ClassifiedAdReport() { ClassifiedAd = i, CreatedDate = rep.CreatedDate, OpenRequest = rep.OpenRequest, ReasonDescription = rep.ReasonDescription, ReasonTitle = rep.ReasonTitle, ReportingUser = rep.ReportingUser, Status = rep.Status }; crep.ClassifiedAd.Reports.Add(crep); } if (ad.Status == 0) { i.SubCategory.ClassifiedAdsCount++; i.Category.TotalClassifiedAdsCount++; } newthreadcontext.SaveChanges(); } } } using (MigrationDbContext migrateDB = new MigrationDbContext()) { var query = "SELECT green_kappakappa.webpages_OAuthMembership.Provider, green_kappakappa.webpages_OAuthMembership.ProviderUserId, UserProfile.Email FROM UserProfile INNER JOIN green_kappakappa.webpages_OAuthMembership ON UserProfile.UserId = green_kappakappa.webpages_OAuthMembership.UserId"; var logins = migrateDB.Database.SqlQuery <login>(query).ToList(); foreach (var login in logins) { var user = UserManager.FindByEmail(login.Email); UserManager.AddLogin(user.Id, new UserLoginInfo(login.Provider, login.ProviderUserId)); } } }
public IEnumerable<SelectionDTO> GetTable() { var mapper = new MapperConfiguration(cfg => cfg.CreateMap<Selection, SelectionDTO>()).CreateMapper(); return mapper.Map<IEnumerable<Selection>, IEnumerable<SelectionDTO>>(Database.Selections.GetAll()); }
public static void AddMapper(this IServiceCollection serviceCollection) { var mapper = new MapperConfiguration(cfg => cfg.AddApi().AddDal()); serviceCollection.AddSingleton(mapper.CreateMapper()); }
/// <summary> /// 使用AutoMapper将从源对象到现有目标对象的映射 /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Source object</param> /// <param name="config">The configuration.</param> /// <returns>TDestination.</returns> public static TDestination MapTo <TSource, TDestination>(this TSource source, MapperConfiguration config) { if (source == null) { return(default(TDestination)); } var mapper = config.CreateMapper(); return(mapper.Map <TDestination>(source)); }
public void AutoMapper_Configuration_IsValid() { var config = new MapperConfiguration(cfg => cfg.AddProfile <MappingProfile>()); config.AssertConfigurationIsValid(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddTransient <IRoleMasterRepository, RoleMasterRepository>(); services.AddTransient <IRoleMasterService, RoleMasterService>(); services.AddScoped <IActivityLogRepository, ActivityLogRepository>(); services.AddScoped <IActivityLogService, ActivityLogService>(); services.AddScoped <IUserMasterRepository, UserMasterRepository>(); services.AddScoped <IUserMasterService, UserMasterService>(); services.AddScoped <IDashboardRepository, DashboardRepository>(); services.AddScoped <IDashboardService, DashboardService>(); services.AddScoped <ICoreRepository, CoreRepository>(); services.AddCors(c => { c.AddPolicy("AllowOrigin", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(option => { option.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("my top secret key")), ValidateIssuer = false, ValidateAudience = false }; }); services.AddDbContext <WebDbContext>(opt => { opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); }); //Auto Mapper var mapperConfig = new MapperConfiguration(_mapper => { _mapper.AddProfile(new WebMapper()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); }
private static IServiceProvider Register(IServiceCollection builder, IConfigurationRoot config) { // These registrations of the functions themselves are just for the DebugQueue. Ideally we don't want these registered in production if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") { builder.AddScoped <OnDataDefinitionChanges>(); builder.AddScoped <OnDatasetEvent>(); builder.AddScoped <OnDatasetValidationEvent>(); builder.AddScoped <OnDatasetEventFailure>(); builder.AddScoped <OnDatasetValidationEventFailure>(); builder.AddScoped <OnMapFdzDatasetsEventFired>(); builder.AddScoped <OnMapFdzDatasetsEventFiredFailure>(); builder.AddScoped <OnDeleteDatasets>(); builder.AddScoped <OnDeleteDatasetsFailure>(); } builder.AddSingleton <IDateTimeProvider, DateTimeProvider>(); builder.AddSingleton <IUserProfileProvider, UserProfileProvider>(); builder .AddSingleton <IDefinitionsService, DefinitionsService>(); builder .AddSingleton <IProvidersApiClient, ProvidersApiClient>(); builder.AddSingleton <IProviderSourceDatasetRepository, ProviderSourceDatasetRepository>(ctx => new ProviderSourceDatasetRepository(CreateCosmosDbSettings(config, "providerdatasets"))); builder .AddSingleton <IDatasetService, DatasetService>(); builder .AddSingleton <IDatasetDataMergeService, DatasetDataMergeService>(); builder .AddSingleton <IJobManagement, JobManagement>(); builder .AddSingleton <IDeadletterService, DeadletterService>(); builder .AddScoped <IProcessDatasetService, ProcessDatasetService>(); builder .AddSingleton <IValidator <CreateNewDatasetModel>, CreateNewDatasetModelValidator>(); builder .AddSingleton <IValidator <DatasetVersionUpdateModel>, DatasetVersionUpdateModelValidator>(); builder .AddSingleton <IValidator <DatasetMetadataModel>, DatasetMetadataModelValidator>(); builder .AddSingleton <IValidator <GetDatasetBlobModel>, GetDatasetBlobModelValidator>(); builder .AddSingleton <IValidator <CreateDefinitionSpecificationRelationshipModel>, CreateDefinitionSpecificationRelationshipModelValidator>(); builder .AddSingleton <IExcelDatasetWriter, DataDefinitionExcelWriter>(); builder .AddSingleton <IValidator <ExcelPackage>, DatasetWorksheetValidator>(); builder .AddSingleton <IValidator <DatasetDefinition>, DatasetDefinitionValidator>(); builder .AddSingleton <IDefinitionChangesDetectionService, DefinitionChangesDetectionService>(); builder .AddScoped <IDatasetDefinitionNameChangeProcessor, DatasetDefinitionNameChangeProcessor>(); builder .AddSingleton <IValidator <CreateDatasetDefinitionFromTemplateModel>, CreateDatasetDefinitionFromTemplateModelValidator>(); builder .AddSingleton <IPolicyRepository, PolicyRepository>(); builder .AddSingleton <IBlobClient, BlobClient>((ctx) => { BlobStorageOptions storageSettings = new BlobStorageOptions(); config.Bind("AzureStorageSettings", storageSettings); storageSettings.ContainerName = "datasets"; IBlobContainerRepository blobContainerRepository = new BlobContainerRepository(storageSettings); return(new BlobClient(blobContainerRepository)); }); builder .AddSingleton <LocalIBlobClient, LocalBlobClient>((ctx) => { AzureStorageSettings storageSettings = new AzureStorageSettings(); config.Bind("AzureStorageSettings", storageSettings); storageSettings.ContainerName = "datasets"; return(new LocalBlobClient(storageSettings)); }); builder.AddSingleton <IProviderSourceDatasetsRepository, ProviderSourceDatasetsRepository>(ctx => new ProviderSourceDatasetsRepository(CreateCosmosDbSettings(config, "providerdatasets"))); builder.AddSingleton <IDatasetRepository, DataSetsRepository>(ctx => { return(new DataSetsRepository(CreateCosmosDbSettings(config, "datasets"))); }); builder.AddSingleton <IDatasetSearchService, DatasetSearchService>(); builder.AddSingleton <IProviderSourceDatasetVersionKeyProvider, ProviderSourceDatasetVersionKeyProvider>(); builder.AddSingleton <IDatasetDefinitionSearchService, DatasetDefinitionSearchService>(); builder .AddSingleton <IDefinitionSpecificationRelationshipService, DefinitionSpecificationRelationshipService>(); builder .AddSingleton <IExcelDatasetReader, ExcelDatasetReader>(); builder .AddSingleton <ICalcsRepository, CalcsRepository>(); builder.AddTransient <IValidator <DatasetUploadValidationModel>, DatasetUploadValidationModelValidator>(); MapperConfiguration dataSetsConfig = new MapperConfiguration(c => { c.AddProfile <DatasetsMappingProfile>(); c.AddProfile <CalculationsMappingProfile>(); c.AddProfile <ProviderMappingProfile>(); }); builder .AddSingleton(dataSetsConfig.CreateMapper()); builder.AddSingleton <IVersionRepository <ProviderSourceDatasetVersion>, VersionRepository <ProviderSourceDatasetVersion> >(ctx => new VersionRepository <ProviderSourceDatasetVersion>(CreateCosmosDbSettings(config, "providerdatasets"), new NewVersionBuilderFactory <ProviderSourceDatasetVersion>())); builder.AddSingleton <IDatasetsAggregationsRepository, DatasetsAggregationsRepository>(ctx => new DatasetsAggregationsRepository(CreateCosmosDbSettings(config, "datasetaggregations"))); builder.AddScoped <IUserProfileProvider, UserProfileProvider>(); builder.AddCalculationsInterServiceClient(config, handlerLifetime: Timeout.InfiniteTimeSpan); builder.AddSpecificationsInterServiceClient(config, handlerLifetime: Timeout.InfiniteTimeSpan); builder.AddJobsInterServiceClient(config, handlerLifetime: Timeout.InfiniteTimeSpan); builder.AddProvidersInterServiceClient(config, handlerLifetime: Timeout.InfiniteTimeSpan); builder.AddPoliciesInterServiceClient(config, handlerLifetime: Timeout.InfiniteTimeSpan); builder.AddSearch(config); builder .AddSingleton <ISearchRepository <DatasetIndex>, SearchRepository <DatasetIndex> >(); builder .AddSingleton <ISearchRepository <DatasetDefinitionIndex>, SearchRepository <DatasetDefinitionIndex> >(); builder .AddSingleton <ISearchRepository <DatasetVersionIndex>, SearchRepository <DatasetVersionIndex> >(); builder.AddServiceBus(config, "datasets"); builder.AddCaching(config); builder.AddApplicationInsightsTelemetryClient(config, "CalculateFunding.Functions.Datasets"); builder.AddApplicationInsightsServiceName(config, "CalculateFunding.Functions.Datasets"); builder.AddLogging("CalculateFunding.Functions.Datasets"); builder.AddTelemetry(); builder.AddFeatureToggling(config); PolicySettings policySettings = ServiceCollectionExtensions.GetPolicySettings(config); DatasetsResiliencePolicies resiliencePolicies = CreateResiliencePolicies(policySettings); builder.AddSingleton <IDatasetsResiliencePolicies>(resiliencePolicies); builder.AddSingleton <IJobManagementResiliencePolicies>((ctx) => { AsyncBulkheadPolicy totalNetworkRequestsPolicy = ResiliencePolicyHelpers.GenerateTotalNetworkRequestsPolicy(policySettings); return(new JobManagementResiliencePolicies() { JobsApiClient = ResiliencePolicyHelpers.GenerateRestRepositoryPolicy(totalNetworkRequestsPolicy) }); }); builder.AddSingleton <IVersionBulkRepository <ProviderSourceDatasetVersion>, VersionBulkRepository <ProviderSourceDatasetVersion> >((ctx) => { CosmosDbSettings settings = new CosmosDbSettings(); config.Bind("CosmosDbSettings", settings); settings.ContainerName = "providerdatasets"; CosmosRepository cosmos = new CosmosRepository(settings, new CosmosClientOptions { AllowBulkExecution = true }); return(new VersionBulkRepository <ProviderSourceDatasetVersion>(cosmos, new NewVersionBuilderFactory <ProviderSourceDatasetVersion>())); }); builder.AddSingleton <IProviderSourceDatasetBulkRepository, ProviderSourceDatasetBulkRepository>((ctx) => { CosmosDbSettings settings = new CosmosDbSettings(); config.Bind("CosmosDbSettings", settings); settings.ContainerName = "providerdatasets"; CosmosRepository cosmos = new CosmosRepository(settings, new CosmosClientOptions { AllowBulkExecution = true }); return(new ProviderSourceDatasetBulkRepository(cosmos)); }); return(builder.BuildServiceProvider()); }
/// <summary> /// 使用AutoMapper将从源对象到现有目标对象的映射 /// </summary> /// <typeparam name="TSource">The type of the t source.</typeparam> /// <typeparam name="TDestination">The type of the t destination.</typeparam> /// <param name="source">The source.</param> /// <param name="config">The configuration.</param> /// <returns>IEnumerable<TDestination>.</returns> public static IEnumerable <TDestination> MapTo <TSource, TDestination>(this IEnumerable <TSource> source, MapperConfiguration config) { if (source == null) { return(default(IEnumerable <TDestination>)); } var mapper = config.CreateMapper(); return(mapper.Map <IEnumerable <TDestination> >(source)); }
public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IDalSettings, DalSettings>(); services.AddSingleton <IBookingSettings, BookingSettings>(); services.AddTransient <IUserInfo, UserInfo>(); services.AddSingleton <IAccountUpdatingSettings, AccountUpdatingSettings>(); services.AddSingleton <IProfileCachingSettings, ProfileCachingSettings>(); FrontendFilesSettings frontendFilesSettings = new FrontendFilesSettings(Configuration); services.AddSingleton <IFrontendFilesSettings>(frontendFilesSettings); FilesUploadingSettings filesUploadingSettings = new FilesUploadingSettings(Configuration); services.AddSingleton <IFilesUploadingSettings, FilesUploadingSettings>(); services.AddSingleton <IPaginationSettings, PaginationSettings>(); CorsSettings corsSettings = new CorsSettings(Configuration); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins(corsSettings.AllowedOrigins) .AllowAnyHeader() .AllowAnyMethod(); }); }); MapperConfiguration mappingConfig = new MapperConfiguration(config => { WebAPIMapping.Initialize(config); BlMapping.Initialize(config); DalMapping.Initialize(config); }); mappingConfig.CompileMappings(); services.AddSingleton <IMapper>(mappingConfig.CreateMapper()); services.AddControllers(); DalModule.Register(services); BlModule.Register(services); WebAPIModule.Register(services); Serilog.ILogger logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .CreateLogger(); services.AddLogging((builder) => { builder.AddSerilog(logger, dispose: true); }); JwtSettings jwtSettings = new JwtSettings(Configuration); services.AddSingleton <IJwtSettings>(jwtSettings); byte[] key = Encoding.UTF8.GetBytes(jwtSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = false; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, ValidIssuer = jwtSettings.Issuer, ValidateAudience = true, ValidAudiences = corsSettings.AllowedOrigins }; }); services.AddHttpContextAccessor(); services.Configure <FormOptions>(options => { // converting to bytes options.MultipartBodyLengthLimit = filesUploadingSettings.MaxMbSize * 1024 * 1024; }); services.AddMemoryCache(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = Path.Combine(frontendFilesSettings.StoragePath); }); }
/// <summary> /// AutoMapper提供者 /// </summary> /// <param name="mapperConfiguration">mapper配置</param> public AutoMapperProvider(MapperConfiguration mapperConfiguration) { _configuration = mapperConfiguration; _mapper = _configuration.CreateMapper(); }
public QueryHandler(BrickstoreContext db, MapperConfiguration config) { _db = db; _config = config; }
public IEnumerable <ProjectDTO> GetTable() { var mapper = new MapperConfiguration(cfg => cfg.CreateMap <Project, ProjectDTO>()).CreateMapper(); return(mapper.Map <IEnumerable <Project>, IEnumerable <ProjectDTO> >(Database.Projects.GetAll())); }
public static IMapper Create <T, T2>() { MapperConfiguration config = new MapperConfiguration(cfg => cfg.CreateMap <T, T2>()); return(config.CreateMapper()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var mapping = new MapperConfiguration(conf => { conf.AddProfile(new AutoMapperProfile()); }); IMapper map = mapping.CreateMapper(); services.AddSingleton(map); services.AddDbContext <RepositoryContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowAnyOrigin()); }); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddMvc(option => option.EnableEndpointRouting = false) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); services.AddScoped <IRepositoryWrapper, RepositoryWrapper>(); services.AddScoped <IProductService, ProductManager>(); services.AddScoped <ICategoryService, CategoryManager>(); services.AddScoped <ICustomerService, CustomerManager>(); services.AddScoped <IAuth, AuthManager>(); services.AddTransient <IProductsToCustomer, ProductsToCustomerManager>(); services.AddScoped <IProductDetailsService, ProductDetailsManager>(); }
static ApiScopeMappers() { Mapper = new MapperConfiguration(cfg => cfg.AddProfile <ApiResourceMapperProfile>()) .CreateMapper(); }
public IEnumerable <CommentDto> GetComments() { var mapper = new MapperConfiguration(cfg => cfg.CreateMap <Comment, CommentDto>()).CreateMapper(); return(mapper.Map <IEnumerable <Comment>, List <CommentDto> >(db.Comments.GetAll())); }
static ClientMappers() { Mapper = new MapperConfiguration(cfg => cfg.AddProfile <ClientMapperProfile>()) .CreateMapper(); }
private IMapper CreateMapper() { var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile(typeof(MapperProfileSqliteRepos))); return mapperConfig.CreateMapper(); }
public AssetSettingsListServiceTests() { _customerUid = Guid.NewGuid(); _userUid = Guid.NewGuid(); _assetUIDs = new List <Guid>(); _stubLoggingService = Substitute.For <ILoggingService>(); _stubCustomerRepository = Substitute.For <ICustomerRepository>(); _stubLoggingService.CreateLogger(typeof(AssetSettingsListService)); _assetSettingsListValidators = new List <IRequestValidator <AssetSettingsListRequest> > { new AssetSettingsListPageValidator(_stubLoggingService), new AssetSettingsFilterValidator(_stubLoggingService), new AssetSettingsSortColumnValidator(_stubLoggingService) }; _serviceRequestParametersValidators = new List <IRequestValidator <IServiceRequest> > { new CustomerUidValidator(_stubCustomerRepository, _stubLoggingService), new UserUidValidator(_stubLoggingService) }; for (int i = 0; i < 10; i++) { _assetUIDs.Add(Guid.NewGuid()); } _stubParameterAttributeCache = Substitute.For <IParameterAttributeCache>(); _stubAssetSettingsListRepository = Substitute.For <IAssetSettingsListRepository>(); _stubAssetSettingsListRepository.FetchEssentialAssets(Arg.Any <AssetSettingsListRequestDto>()).Returns( x => { var request = (AssetSettingsListRequestDto)x[0]; if (request.CustomerUid == _customerUid.ToString("N") && request.UserUid == _userUid.ToString("N")) { if ((_assetUIDs.Count / request.PageSize) < request.PageNumber) { return(new Tuple <int, IList <AssetSettingsListDto> >(0, new List <AssetSettingsListDto>())); } return(new Tuple <int, IList <AssetSettingsListDto> >(_assetUIDs.Count, _assetUIDs.Select(y => new AssetSettingsListDto { AssetUIDString = y.ToString("N"), AssetName = y.ToString("N") }).ToList())); } else { return(new Tuple <int, IList <AssetSettingsListDto> >(0, new List <AssetSettingsListDto>())); } }); _stubAssetSettingsListRepository.FetchDeviceTypesByAssetUID(Arg.Any <AssetDeviceTypeRequest>()).Returns(x => { var request = (AssetDeviceTypeRequest)x[0]; return(Tuple.Create <int, IEnumerable <DeviceTypeDto> >(3, new List <DeviceTypeDto>() { new DeviceTypeDto() { DeviceType = "PL121", AssetCount = 120 }, new DeviceTypeDto() { DeviceType = "PL142", AssetCount = 24 }, new DeviceTypeDto() { DeviceType = "PL132", AssetCount = 100 } })); }); var mapperconfig = new MapperConfiguration(cfg => { cfg.CreateMap <AssetSettingsListDto, AssetSettingsDetails>(); }); this._stubConfigurations = Options.Create <Configurations>(Substitute.For <Configurations>()); _mapper = mapperconfig.CreateMapper(); _assetSettingsListService = new AssetSettingsListService(_stubAssetSettingsListRepository, _assetSettingsListValidators, _serviceRequestParametersValidators, _stubParameterAttributeCache, _mapper, _stubLoggingService, _stubConfigurations); }
public ConfigurationRegistry() { var configuration = new MapperConfiguration(cfg => cfg.CreateMap <Source, Destination>()); For <IMapper>().Use(ctx => new Mapper(configuration, ctx.GetInstance)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApplicationContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection"))); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddIdentity <User, IdentityRole>(opt => { opt.Password.RequiredLength = 4; opt.Password.RequireDigit = false; opt.Password.RequireUppercase = false; opt.Password.RequireNonAlphanumeric = false; opt.User.RequireUniqueEmail = true; opt.SignIn.RequireConfirmedEmail = true; opt.Tokens.EmailConfirmationTokenProvider = "emailconfirmation"; opt.Lockout.AllowedForNewUsers = true; opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2); opt.Lockout.MaxFailedAccessAttempts = 3; }) .AddEntityFrameworkStores <ApplicationContext>() .AddDefaultTokenProviders() .AddTokenProvider <EmailConfirmationTokenProvider <User> >("emailconfirmation") .AddPasswordValidator <CustomPasswordValidator <User> >(); services.AddScoped <IUserClaimsPrincipalFactory <User>, CustomClaimsFactory>(); services.ConfigureApplicationCookie(o => o.LoginPath = "/Authentication/Login"); var emailConfig = Configuration.GetSection("EmailConfiguration").Get <EmailConfiguration>(); services.AddSingleton(emailConfig); services.AddScoped <IEmailSender, EmailSender>(); services.Configure <FormOptions>(o => { o.ValueLengthLimit = int.MaxValue; o.MultipartBodyLengthLimit = int.MaxValue; o.MemoryBufferThreshold = int.MaxValue; }); services.Configure <DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromHours(2)); services.Configure <EmailConfirmationTokenProverOptions>(opt => opt.TokenLifespan = TimeSpan.FromDays(1)); services.AddAuthentication() .AddGoogle("google", opt => { var googleAuth = Configuration.GetSection("Authentication:Google"); opt.ClientId = googleAuth["ClientId"]; opt.ClientSecret = googleAuth["ClientSecret"]; opt.SignInScheme = IdentityConstants.ExternalScheme; }); services.AddControllersWithViews(); }
public async Task <List <TareasModel> > Consultar(CriteriosTareas input) { try { var config = new MapperConfiguration(cfg => { cfg.CreateMap <List <Tareas>, List <TareasModel> >(); }); IMapper iMapper = config.CreateMapper(); //Se parametrizan los predicados var inner = PredicateBuilder.False <Tareas>(); //OR var outer = PredicateBuilder.True <Tareas>(); //AND if (input.ConsultarSoloMisTareas) { ClaimsIdentity claimsIdentity = new ClaimsIdentity("UserData"); var jsonUserInfo = claimsIdentity.Claims.FirstOrDefault().Value; var usuarioActual = JsonConvert.DeserializeObject <UsuarioModel>(jsonUserInfo); //Suponiendo que el usuario es unico var usuarioInfo = (from usuario in await _usuariosRepositorio.GetAllAsync() where usuario.Usuario == usuarioActual.Usuario select usuario).FirstOrDefault(); /* * var listaTareasInfo = (from tarea in await _tareasRepositorio.GetAllAsync() * where tarea.UsuarioRefId == usuarioInfo.Id * select tarea).ToList(); */ outer = outer.And(t => t.UsuarioRefId == usuarioInfo.Id); //return iMapper.Map<List<TareasModel>>(listaTareasInfo); } if (input.ConsultarTareasPendientes) {/* * var listaTareasInfo = (from tarea in await _tareasRepositorio.GetAllAsync() * where tarea.EstadoTarea == "Pendiente" * select tarea).ToList(); */ inner = inner.Or(t => t.EstadoTarea == "Pendiente"); //return iMapper.Map<List<TareasModel>>(listaTareasInfo); } if (input.ConsultarTareasFinalizadas) {/* * var listaTareasInfo = (from tarea in await _tareasRepositorio.GetAllAsync() * where tarea.EstadoTarea == "Finalizado" * select tarea).ToList();*/ inner = inner.Or(t => t.EstadoTarea == "Finalizado"); //return iMapper.Map<List<TareasModel>>(listaTareasInfo); } outer = outer.And(inner); if (input.OrdenarConsultaPorFechaVencimiento) { /* * var listaTareasInfo = (from tarea in await _tareasRepositorio.GetAllAsync() * orderby tarea.FechaVencimiento * select tarea).ToList();*/ var listaTareasOrdenadas = (await _tareasRepositorio.GetAllAsync()).Where(outer).OrderBy(s => s.FechaVencimiento); return(iMapper.Map <List <TareasModel> >(listaTareasOrdenadas)); //return iMapper.Map<List<TareasModel>>(listaTareasInfo); } var listaTareas = (await _tareasRepositorio.GetAllAsync()).Where(outer).ToList(); return(iMapper.Map <List <TareasModel> >(listaTareas)); } catch (Exception) { throw new Exception("Error en consulta"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); // DB connection string (My SQL Server) services.AddDbContext<DbContextDTO>(opt => opt.UseSqlServer(Configuration.GetConnectionString("VehicleAppraisal"))); // Validator // automapper var config = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperConfigure()); }); IMapper mapper = config.CreateMapper(); services.AddSingleton(mapper); // add DI services.AddScoped<IMakeService, MakeService>(); services.AddScoped<IModelService, ModelService>(); services.AddScoped<ICustomerService, CustomerService>(); services.AddScoped<IVehicleService, VehicleService>(); services.AddScoped<IConditionService, ConditionService>(); services.AddScoped<IVehicleAppraisalService, VehicleAppraisalService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IUserRoleService, UserRoleService>(); services.AddScoped<IAccountService, AccountService>(); services.AddScoped<IEmailService, EmailService>(); services.AddScoped<IVehicleCrawlDataService, VehicleCrawlDataService>(); // authentication services.AddAuthentication(option => { option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(Opt => { var secretKey = new SymmetricSecurityKey(UTF8Encoding.UTF8.GetBytes(Configuration["JWT:SecretKey"])); Opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, IssuerSigningKey = secretKey, ValidIssuer = Configuration["JWT:Issuer"], ValidAudience = Configuration["JWT:Audience"], ValidateLifetime = true }; }); // swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Api", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\nExample: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "Bearer", Name = "Bearer", In = ParameterLocation.Header, }, new List<string>() } }); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) // add fluent validation .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<RegisterValidator>()); }
private static void InitializeMapper() { var mapperConfiguration = new MapperConfiguration(cfg => cfg.AddProfile <ProductShopProfile>()); mapper = new Mapper(mapperConfiguration); }
public static void AddGeneralConfigurations(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext <ApplicationDbContext>(options => { options.EnableDetailedErrors(true); options.UseMySQL(configuration.GetValue <string>("ConnectionStrings:DefaultConnection")); options.UseSnakeCaseNamingConvention(); }); services.AddIdentity <User, IdentityRole>().AddEntityFrameworkStores <ApplicationDbContext>(); var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); //DI services.AddSingleton(mapper); services.AddTransient <IAuthenticationService, AuthenticationService>(); services.AddTransient <UserManager <User>, UserManager <User> >(); services.AddTransient <IDepartmentRepository, DepartmentRepository>(); services.AddTransient <IStaffRepository, StaffRepository>(); services.AddDistributedMemoryCache(); var jwtSection = configuration.GetSection("JWT"); services.Configure <JwtOptions>(jwtSection); var appSettings = jwtSection.Get <JwtOptions>(); services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.SaveToken = true; o.RequireHttpsMetadata = false; o.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = appSettings.ValidAudience, ValidIssuer = appSettings.ValidIssuer, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"])) }; }); services.AddControllersWithViews(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Api", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"Example Token: 'Bearer {Token}'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oath2", Name = "Bearer", In = ParameterLocation.Header }, new List <string>() } }); }); }
static SystemVariableMapper() { Mapper = new MapperConfiguration(cfg => cfg.AddProfile <SystemVariableMapperProfile>()) .CreateMapper(); }
static PersistedGrantMappers() { Mapper = new MapperConfiguration(cfg =>cfg.AddProfile<PersistedGrantMapperProfile>()) .CreateMapper(); }
public IMapper Mapper() { var config = new MapperConfiguration(cfg => cfg.AddProfile <AutoMapping>()); return(config.CreateMapper()); }
public void TestProfileIsValid() { var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile <TicketProfile>()); mapperConfig.AssertConfigurationIsValid(); }
static PageService() { var config = new MapperConfiguration(cfg => cfg.CreateMap <PageContent, PageDetails>()); _mapFromContentToDetails = config.CreateMapper(); }