コード例 #1
0
ファイル: Global.asax.cs プロジェクト: bodoi304/EIV
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //Cầu hình cho log4net
            log4net.Config.XmlConfigurator.Configure();

            //Cấu hình Automapper
            AutoMapperConfiguration.Configure();

            //Cấu hình đa ngôn ngữ
            String culture       = ConfigurationManager.AppSettings["culture"];
            String ForderCulture = ConfigurationManager.AppSettings["ForderCulture"];

            ConfigMultiLanguage.Configure(culture, ForderCulture);

            //Cấu hình dependence injection
            // Create the container as usual.
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            // Register your types, for instance using the scoped lifestyle:
            //Lifestyle:
            //Singleton trong suốt vòng đời ứng dụng chỉ có 1 instance duy nhất
            //Scoped: Chỉ tồn tại 1 instance trong 1 lần request (mỗi request là 1 scope).
            //Transient: Một instance mới luôn được tạo, mỗi khi được yêu cầu.
            container.Register <IInvoiceCategorys, InvoiceCategorysService>(Lifestyle.Scoped);
            container.Register <IInvoice, InvoiceService>(Lifestyle.Scoped);
            container.Register <IAuthentication, AuthenticationService>(Lifestyle.Scoped);

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
コード例 #2
0
        static void Main(string[] args)
        {
            AutoMapperConfiguration.Configure();

            StudentManager studentManager = new StudentManager();
            // Save

            // Update
            int success = studentManager.Update(1, new CoreLibrary.Models.Student
            {
                Id           = 1,
                Name         = "Mr B",
                DepartmentId = 1,
                Address      = "Dinajpur",
                Code         = "02",
                Roll         = "0222"
            });

            System.Console.WriteLine(success);
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <LiveGameContext>(options => options.UseInMemoryDatabase());
            // Repositories
            services.AddScoped <IMatchRepository, MatchRepository>();
            services.AddScoped <IFeedRepository, FeedRepository>();

            // Automapper Configuration
            AutoMapperConfiguration.Configure();

            // Add framework services.
            services
            .AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver =
                                new DefaultContractResolver());

            services.AddSignalR(options => options.Hubs.EnableDetailedErrors = true);

            services.AddTask <FeedEngine>();
        }
コード例 #4
0
ファイル: Global.asax.cs プロジェクト: pzapata87/BigBag
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            Database.SetInitializer(new ContextInitializer());
            Database.SetInitializer <DbContextBase>(null);

            PersistenceConfigurator.Configure("DefaultConnection", typeof(Usuario).Assembly, typeof(ConnectionFactory).Assembly);
            StructuremapMvc.Start();


            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            AutoMapperConfiguration.Configure();

            XmlConfigurator.Configure();

            ModelMetadataProviders.Current = new ConventionalModelMetadataProvider(true, typeof(Master));
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json",
                                  "Holdprint");
            });

            ConfigureGlobalExceptionHandler(app);

            AutoMapperConfiguration.Configure();
        }
コード例 #6
0
ファイル: RoleControllerTest.cs プロジェクト: KateKov/Game
 public RoleControllerTest()
 {
     AutoMapperConfiguration.Configure();
     _mockAuth    = new Mock <IAuthenticationManager>();
     _roleService = new Mock <INamedService <RoleDTO, RoleDTOTranslate> >();
     _user        = new UserModel
     {
         Username = "******",
         IsBanned = false,
         Roles    =
             new List <UserRole>
         {
             UserRole.Administrator,
             UserRole.Guest,
             UserRole.Manager,
         }
     };
     _mockAuth.Setup(x => x.CurrentUser).Returns(new UserProvider(_user));
     _controller = new RolesController(_roleService.Object, _mockAuth.Object);
 }
コード例 #7
0
ファイル: Startup.cs プロジェクト: EdgarMondragon/UnitOfWork
        // 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 http://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "User Settings API", Version = "v1"
                });
            });
            services.AddMvc(con => {
                con.Filters.Add(new GlobalFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            // Enables controllers to be resolved by DryIoc, OTHERWISE resolved by infrastructure
            .AddControllersAsServices();
            services.AddScoped <AuthorizationFilter>();
            //services.AddIdentityCore<IdentityUser>();
            services.AddCors();
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            var config  = builder.Build();

            DbProviderManager.LoadConfiguration(config);
            services.AddSingleton <IConfiguration>(config);
            // DryIOC
            var container = new Container().WithDependencyInjectionAdapter(services);

            container.Register <IApplicationContext, ApplicationContext>();
            container.Register <IUserSettings, UserSettingsMemoryRepo>();
            container.Register <IConnectionFactory, ConnectionFactory>();
            container.Register <IUnitOfWork, UnitOfWork.UnitOfWork>();
            container.Register <IUserSettingsRepository, UserSettingsRepository>();
            container.Register <IOnDutiesRepository, OnDutiesRepository>();
            container.Register <IUserSessionInfoRepository, UserSessionInfoRepository>();
            container.Register <IMemberPreferences, MemberPreferencesRepository>();
            container.Register <IResponderRepository, ResponderRepository>();
            var serviceProvider = container.Resolve <IServiceProvider>();

            // Automapper Configuration
            AutoMapperConfiguration.Configure();

            return(serviceProvider);
        }
コード例 #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app,
                                    IHostingEnvironment env,
                                    ILoggerFactory loggerFactory,
                                    IConfiguration configuration)
        {
            loggerFactory.AddConsole(configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("ServerPolicy");

            app.UseDeveloperExceptionPage();

            app.UseAuthentication();
            app.UseIdentityServer();


            app.UseMvc();
            app.UseStaticFiles();

            AutoMapperConfiguration.Configure();
        }
コード例 #9
0
ファイル: Startup.cs プロジェクト: sobhardwaj/CoreDataStore
        private void AppConfig(IApplicationBuilder app)
        {
            AutoMapperConfiguration.Configure();

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseResponseHeaderMiddleware();

            app.UseHealthChecks($"/health");
            app.UseHealthChecksUI();

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                var swaggerDocument = $"/swagger/v1/swagger.json";
                options.SwaggerEndpoint(swaggerDocument, "CoreDataStore.Web");
            });

            app.UseMvc(ConfigureRoutes);
        }
コード例 #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddDbContext <TodoContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

            services.AddScoped <ITodoService, TodoService>();
            services.AddScoped <ITodoAdapter, TodoAdapter>();
            services.AddScoped <ITodoPointAdapter, TodoPointAdapter>();
            services.AddScoped <ITodoPointService, TodoPointService>();
            services.AddScoped <ITodoContext, TodoContext>();
            services.AddSingleton(AutoMapperConfiguration.Configure());

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
コード例 #11
0
        public void ShouldMapEntityToModel()
        {
            AutoMapperConfiguration.Configure();

            const string Id = "My Id";

            var entity = new BasketEntity
            {
                Id    = Id,
                Items = new[] { new ProductEntity {
                                    Id = 42, Name = "Name", Cost = new MoneyEntity(4200, SE.ISOCurrencySymbol)
                                } }
            };

            var model = AutoMapperConfiguration.Mapper.Map <Basket>(entity);

            Assert.Equal(Id, model.Id);
            Assert.Single(model.Products);
            Assert.Equal(1, model.Count);
            Assert.Equal(new Money(42.0, SE), model.Total);
        }
コード例 #12
0
        public CatServiceFixture()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables()
                          .Build();

            var dbConnection = builder.GetConnectionString("DbConnection");

            // AutoMapper Configuration
            AutoMapperConfiguration.Configure();

            var serviceProvider = new ServiceCollection()
                                  .AddSingleton <ICatRepository>(new CatRepository(dbConnection))
                                  .AddScoped <ICatService, CatService>()
                                  .BuildServiceProvider();

            serviceProvider.GetRequiredService <ICatRepository>();
            CatService = serviceProvider.GetRequiredService <ICatService>();
        }
コード例 #13
0
            public void ShouldExposeAllProperties()
            {
                AutoMapperConfiguration.Configure();
                var document = new Document
                {
                    Id           = Guid.NewGuid(),
                    CandidateId  = Guid.NewGuid(),
                    Filename     = "MyCV.pdf",
                    DocumentType = DocumentType.BusinessPlan,
                    ReviewerId   = Guid.NewGuid()
                };
                var documentVm = Mapper.Map <Document, DocumentViewModel>(document);

                Assert.Equal(document.Id, documentVm.Id);
                Assert.Equal(document.CandidateId, documentVm.CandidateId);
                Assert.Equal(document.Filename, documentVm.Filename);
                Assert.Equal(document.FileExtension, documentVm.FileExtension);
                Assert.Equal((int)document.DocumentType, documentVm.DocumentType);
                Assert.Equal(document.ReviewerId, documentVm.ReviewerId);
                Assert.Equal(document.CreationDate, documentVm.CreationDate);
            }
コード例 #14
0
        public void DeveAdicionarMarcaComSucesso()
        {
            try
            {
                AutoMapperConfiguration.Configure();

                var repository  = new MarcaRepository(new MeuPatrimonioContext());
                var validation  = new MarcaValidation(repository);
                var service     = new MarcaService(validation, repository);
                var application = new MarcaApplication(service);
                var marca       = application.Add(new MarcaDTO {
                    Nome = "CCE"
                });

                Assert.IsNotNull(marca);
            }
            catch (ValidacaoException exc)
            {
                Assert.Fail(exc.InvalidMessages[0].Texto);
            }
        }
コード例 #15
0
ファイル: StartUp.cs プロジェクト: esilantiev/BackEndService
        public void Configuration(IAppBuilder app)
        {
            AutoMapperConfiguration.Configure();

            ApplicationContext.HostName = "ises";

            app.UseRequestLogger();

            app.UseExceptionHandler();

            app.UseCors(CorsOptions.AllowAll);

            var container = LoadContainer();

            app.UseAutofacMiddleware(container);

            var config = new ApiConfiguration(container);

            app.UseWebApi(config);
            app.UseAutofacWebApi(config);
        }
コード例 #16
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //LogManager.GetCurrentClassLogger().Info("Started Raccon Blog");

            // Work around nasty .NET framework bug
            try
            {
                new Uri("http://fail/first/time?only=%2bplus");
            }
            catch (Exception)
            {
            }

            RegisterGlobalFilters(GlobalFilters.Filters);
            InitializeDocumentStore();
            new RouteConfigurator(RouteTable.Routes).Configure();
            ModelBinders.Binders.Add(typeof(CommentCommandOptions), new RemoveSpacesEnumBinder());
            ModelBinders.Binders.Add(typeof(Guid), new GuidBinder());

            DataAnnotationsModelValidatorProviderExtensions.RegisterValidationExtensions();

            AutoMapperConfiguration.Configure();

            RavenController.DocumentStore = DocumentStore;
            TaskExecutor.DocumentStore    = DocumentStore;

            // In case the versioning bundle is installed, make sure it will version
            // only what we opt-in to version
            using (var s = DocumentStore.OpenSession())
            {
                s.Store(new
                {
                    Exclude = true,
                    Id      = "Raven/Versioning/DefaultConfiguration",
                });
                s.SaveChanges();
            }
        }
コード例 #17
0
ファイル: Startup.cs プロジェクト: johnfredrik/MicrobrewitApi
        public void Configuration(IAppBuilder app)
        {
            //HttpConfiguration config = new HttpConfiguration();
            // Add this code, if not present.
            // Add this code, if not present.
            AreaRegistration.RegisterAllAreas();

            //GlobalConfiguration.Configuration.AddJsonpFormatter();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            //GlobalConfiguration.Configuration.EnableCors();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AutoMapperConfiguration.Configure();

            // HttpConfiguration config = new HttpConfiguration();

            //HttpConfiguration.AddJsonpFormatter();

            HttpConfiguration.EnableCors();

            var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;

            //xml.Indent = true;
            xml.UseXmlSerializer = true;
            //xml.SetSerializer<Hop>(new XmlSerializer(typeof(Hop)));


            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<MicrobrewitContext, Configuration>());
            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<AuthContext, Model.AuthMigration.Configuration>());
            ConfigureOAuth(app);
            //WebApiConfig.Register(HttpConfiguration);
            //WebApiConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(HttpConfiguration);
            //app.UseWebApi(config);
        }
コード例 #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // this will serve up wwwroot
            app.UseFileServer();

            // this will serve up node_modules
            var provider = new PhysicalFileProvider(
                Path.Combine(_contentRootPath, "node_modules")
                );
            var _fileServerOptions = new FileServerOptions();

            _fileServerOptions.RequestPath = "/node_modules";
            _fileServerOptions.StaticFileOptions.FileProvider = provider;
            _fileServerOptions.EnableDirectoryBrowsing        = true;
            app.UseFileServer(_fileServerOptions);

            AutoMapperConfiguration.Configure();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true
            });

            // Custom authentication middleware
            //app.UseMiddleware<AuthMiddleware>();

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                //routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });

            DbInitializer.Initialize(app.ApplicationServices, _applicationPath);
        }
コード例 #19
0
        protected void Application_Start()
        {
            //Todo: L'environnment dev devrait aussi être en HTTPS
            if (ConfigurationManager.AppSettings["environment"] == "prod")
            {
                GlobalFilters.Filters.Add(new RequireHttpsAttribute());
            }

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // C'est dans NinjectWebCommon.cs que la dépendance (sur EFDatabaseHelper) est gérée
            var dbInitializer = DependencyResolver.Current.GetService <IDatabaseHelper>();

            dbInitializer.DropCreateDatabaseIfModelChanges();

            AutoMapperConfiguration.Configure();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
コード例 #20
0
        public CoreDataStoreDbFixture()
        {
            var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";

            Console.WriteLine("ENV:" + env);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env}.json", optional: true)
                          .AddEnvironmentVariables()
                          .Build();

            DbConnection = builder.GetConnectionString("SqlServer");

            var serviceProvider = new ServiceCollection()
                                  .AddDbContext <NycLandmarkContext>(options => options.UseSqlServer(DbConnection))
                                  .AddScoped <ILandmarkRepository, LandmarkRepository>()
                                  .AddScoped <ILpcLamppostRepository, LpcLamppostRepository>()
                                  .AddScoped <ILpcLocationRepository, LpcLocationRepository>()
                                  .AddScoped <ILpcReportRepository, LpcReportRepository>()
                                  .AddScoped <IPlutoRepository, PlutoRepository>()
                                  .AddScoped <ILpcReportService, LpcReportService>()
                                  .AddScoped <ILandmarkService, LandmarkService>()
                                  .BuildServiceProvider();

            DbContext = serviceProvider.GetRequiredService <NycLandmarkContext>();

            LandmarkRepository    = serviceProvider.GetRequiredService <ILandmarkRepository>();
            LpcLamppostRepository = serviceProvider.GetRequiredService <ILpcLamppostRepository>();
            LpcLocationRepository = serviceProvider.GetRequiredService <ILpcLocationRepository>();
            LpcReportRepository   = serviceProvider.GetRequiredService <ILpcReportRepository>();
            PlutoRepository       = serviceProvider.GetRequiredService <IPlutoRepository>();

            LPCReportService = serviceProvider.GetRequiredService <ILpcReportService>();
            LandmarkService  = serviceProvider.GetRequiredService <ILandmarkService>();

            AutoMapperConfiguration.Configure();
        }
コード例 #21
0
        public ActionResult GetAllProduct(int page = 1, string sort = "")
        {
            int pageSize = int.Parse(ConfigHelper.GetByKey("PageSize"));
            int totalRow = 0;

            var listProduct = _productService.GetAllByPaging(page, sort, pageSize, out totalRow);

            IMapper mapper        = AutoMapperConfiguration.Configure();
            var     listProductVm = mapper.Map <IEnumerable <ProductViewModel> >(listProduct);

            int totalPage     = (int)Math.Ceiling((double)totalRow / pageSize);
            var paginationSet = new PaginationSet <ProductViewModel>()
            {
                Items      = listProductVm,
                MaxPage    = int.Parse(ConfigHelper.GetByKey("MaxPage")),
                Page       = page,
                TotalCount = totalRow,
                TotalPages = totalPage
            };

            return(View(paginationSet));
        }
コード例 #22
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            config.Formatters.JsonFormatter.SerializerSettings.Formatting        = Formatting.Indented;

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            AutoMapperConfiguration.Configure();

            var cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);
        }
コード例 #23
0
        public HttpResponseMessage Delete(HttpRequestMessage request, int id)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;
                if (!ModelState.IsValid)
                {
                    response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
                }
                else
                {
                    var oldProduct = _productService.Delete(id);
                    _productService.Save();

                    IMapper _mapper = AutoMapperConfiguration.Configure();
                    var responseData = _mapper.Map <ProductViewModel>(oldProduct);
                    response = request.CreateResponse(HttpStatusCode.Created, responseData);
                }

                return response;
            }));
        }
コード例 #24
0
ファイル: SyncFunctions.cs プロジェクト: ankur-soni/Utilities
        public void SyncData()
        {
            try
            {
                AutoMapperConfiguration.Configure();
                using (var enableContext = new EnableDevEntities())
                    using (var utilityContainerContext = new UtilityContainerEntities())
                    {
                        enableContext.Configuration.AutoDetectChangesEnabled = false;
                        enableContext.Configuration.ValidateOnSaveEnabled    = false;

                        _logger.Log("Sync started");
                        //Master data
                        SyncClients(enableContext, utilityContainerContext);
                        SyncEngagementTypes(enableContext, utilityContainerContext);
                        SyncDepartments(enableContext, utilityContainerContext);
                        //SyncLocations(enableContext, utilityContainerContext);
                        //SyncResourceTypes(enableContext, utilityContainerContext);
                        SyncSkills(enableContext, utilityContainerContext);

                        // Data
                        SyncTitles(enableContext, utilityContainerContext);
                        SyncUsers(enableContext, utilityContainerContext);
                        SyncEngagements(enableContext, utilityContainerContext);
                        //SyncEngagementTaskTypes(enableContext, utilityContainerContext);
                        SyncResources(enableContext, utilityContainerContext);
                        SyncResourceHistories(enableContext, utilityContainerContext);
                        //SyncResourceSkillLevels(enableContext, utilityContainerContext);
                        SyncEngagementRoles(enableContext, utilityContainerContext);
                        //SyncCompanies(enableContext, utilityContainerContext);

                        _logger.Log("Sync finished");
                    }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
            }
        }
コード例 #25
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 http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string sqlConnectionString = Configuration["Data:SchedulerConnection:ConnectionString"];
            bool   useInMemoryProvider = bool.Parse(Configuration["Data:SchedulerConnection:InMemoryProvider"]);

            services.AddDbContext <SchedulerContext>(options => {
                switch (useInMemoryProvider)
                {
                case true:
                    options.UseInMemoryDatabase();
                    break;

                default:
                    options.UseSqlServer(Configuration["Data:SchedulerConnection:ConnectionString"],
                                         b => b.MigrationsAssembly("Scheduler.Api"));
                    break;
                }
            });


            // Repositories
            services.AddScoped <IScheduleRepository, ScheduleRepository>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IAttendeeRepository, AttendeeRepository>();

            // Automapper Configuration
            AutoMapperConfiguration.Configure();

            // Enable Cors
            services.AddCors();

            // Add MVC services to the services container.
            services.AddMvc()
            .AddJsonOptions(opts =>
            {
                // Force Camel Case to JSON
                opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }
コード例 #26
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EntityFramework's Identity support.
            services.AddEntityFramework();

            // Add ApplicationDbContext's DbSeeder
            services.AddSingleton <DbSeeder>();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration["Data:Configurator:ConnectionString"],
                                                             b => b.MigrationsAssembly("NGL")));

            services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail         = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequiredLength         = 3;
                config.Password.RequireDigit           = false;
                config.Password.RequireLowercase       = false;
                config.Password.RequireUppercase       = false;
                config.Cookies.ApplicationCookie.AutomaticChallenge = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc()
            .AddMvcOptions(options =>
            {
                options.CacheProfiles.Add("NoCache", new CacheProfile
                {
                    NoStore  = true,
                    Duration = 0
                });
            });

            // Automapper Configuration
            AutoMapperConfiguration.Configure();
        }
コード例 #27
0
ファイル: RoleTests.cs プロジェクト: munciuz/Batonezas
        public RoleTests()
        {
            AutoMapperConfiguration.Configure();

            var mockTagRepository = new Mock <ITagRepository>();

            mockTagRepository.Setup(m => m.CreateQuery()).Returns(TagData.CreateQuery);
            mockTagRepository.Setup(m => m.Get(1)).Returns(TagData.Get);
            mockTagRepository.Setup(m => m.Update(TagData.Get()));
            mockTagRepository.Setup(m => m.Insert(TagData.Get()));

            var mockDishTagRepository = new Mock <IDishTagRepository>();

            var mockUserRepository = new Mock <IUserRepository>();

            mockUserRepository.Setup(m => m.Get(1)).Returns(new User {
                UserName = "******"
            });

            tagService    = new TagService(mockTagRepository.Object, mockDishTagRepository.Object, mockUserRepository.Object);
            tagController = new TagController(tagService);
        }
コード例 #28
0
ファイル: Startup.cs プロジェクト: ecodi/multi-micro-web
        public void ConfigureDependencies(IServiceCollection services)
        {
            var stabilityPolicies = new List <string>();

            services.AddSingleton <IAuthorizationHandler, ApiKeyAuthorizationHandler>()
            .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddTransient <IWebClient, HttpWebClient>()
            .AddTransient <IFailureHandler, PollyFailureHandler>()
            .AddScoped <ICacheManager, PerRequestCacheManager>()
            .AddScoped <IWorkContext, WorkContext>()
            .AddScoped <IDocumentRepository, DocumentRepository>()
            .AddScoped <IDocumentsService, DocumentsService>();

            var modulePolicyName = Configuration["Services:ModulesService:StabilityPolicy"];

            if (!string.IsNullOrWhiteSpace(modulePolicyName))
            {
                stabilityPolicies.Add(modulePolicyName);
            }
            services.AddModulesService(options =>
            {
                options.Endpoint        = Configuration["Services:ModulesService:Endpoint"];
                options.Timeout         = TimeSpan.FromMilliseconds(Convert.ToInt32(Configuration["Services:ModulesService:TimeoutMilliseconds"]));
                options.StabilityPolicy = modulePolicyName;
            });
            services.AddPollyPolicyProvider(options =>
            {
                options.PoliciesOptions = stabilityPolicies.ToDictionary(name => name, name => new PollyPolicyOptions
                {
                    BreakOnNumberOfExceptions = Convert.ToInt32(Configuration[$"StabilityPolicies:{name}:BreakOnNumberOfExceptions"]),
                    BreakedCircuitPeriod      = TimeSpan.FromSeconds(Convert.ToInt32(Configuration[$"StabilityPolicies:{name}:BreakCircuitForSeconds"])),
                    NumberOfRetriesPerRequest = Convert.ToInt32(Configuration[$"StabilityPolicies:{name}:NumberOfRetriesPerRequest"])
                });
            });

            ConfigureServiceBus(services);

            AutoMapperConfiguration.Configure();
        }
コード例 #29
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            ConfigureAutofac(app);
            app.MapSignalR();
            AutoMapperConfiguration.Configure();
            MarketplaceMVCHangfire.ConfigureHangfire(app);

            GlobalConfiguration.Configuration
            .UseSqlServerStorage("DefaultConnection");

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("ru");



            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new MyAuthorizationFilter() }
            });

            app.UseHangfireServer();
        }
コード例 #30
0
        public LPCReportServiceTest()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .Build();

            var dbonnection = builder.GetConnectionString("SqlServer");

            var serviceProvider = new ServiceCollection()
                                  .AddDbContext <NYCLandmarkContext>(options => options.UseSqlServer(dbonnection))
                                  .AddScoped <ILPCReportRepository, LPCReportRepository>()
                                  .AddScoped <ILPCReportService, LPCReportService>()
                                  .BuildServiceProvider();

            serviceProvider.GetRequiredService <NYCLandmarkContext>();
            serviceProvider.GetRequiredService <ILPCReportRepository>();

            _lpcReportService = serviceProvider.GetRequiredService <ILPCReportService>();

            AutoMapperConfiguration.Configure();
        }