Exemple #1
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .BuildServiceProvider();

                services.AddStreetwoodContextForTests(serviceProvider);

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var dbContext      = scopedServices.GetRequiredService <IDbContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <InMemoryWebApplicationFactory <TStartup> > >();

                    dbContext.EnsureDatabaseCreated();

                    try
                    {
                        DbInitialization.InitDb(dbContext);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"An error occurred seeding the database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            if (HttpContext.Current.IsDebuggingEnabled)
            {
                DbInitialization.Initialize(300);
            }
        }
Exemple #3
0
        public static void Main(string[] args)
        {
            //BuildWebHost(args).Run();

            // WITH THIS:
            // var host = BuildWebHost(args);
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context     = services.GetRequiredService <ApplicationDbContext>();
                    var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();

                    //var dbInitializerLogger = services.GetRequiredService<ILogger<DbInitializer>>();

                    //DbInitializer.Initialize(context, userManager, roleManager, dbInitializerLogger).Wait();

                    DbInitialization.SeedDB(context, userManager, roleManager).Wait();

                    SchoolContext context1 = services.GetRequiredService <SchoolContext>();

                    DbInitialization.SeedContosoUniversity(context1);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }
Exemple #4
0
 public NotificationManager(string rssFeedUrl)
 {
     this.rssFeedUrl = rssFeedUrl;
     DbInitialization.Initialize();
     
 }
Exemple #5
0
 /// <summary>
 /// Initializes the singleton application object.  This is the first line of authored code
 /// executed, and as such is the logical equivalent of main() or WinMain().
 /// </summary>
 public App()
 {
     this.InitializeComponent();
     this.Suspending += OnSuspending;
     DbInitialization.Initialize();
 }
Exemple #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            #region Serilog Logging
            var logWarning = new Serilog.LoggerConfiguration()
                             .MinimumLevel.Error()
                             .WriteTo.RollingFile(
                pathFormat: env.MapPath("Error/Exception.log"),
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}{NewLine}{NewLine}"
                ).CreateLogger();

            loggerFactory.AddSerilog(logWarning);
            #endregion

            app.UseIISPlatformHandler();

            app.UseApplicationInsightsRequestTelemetry();

            // Add Application Insights exceptions handling to the request pipeline.
            app.UseApplicationInsightsExceptionTelemetry();

            //before UseMvc
            app.UseCors("AllowAllOrigin");


            #region OAuth2.0 Token授权
            #region IdentityServer3
            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            //app.UseJwtBearerAuthentication(options =>
            //{
            //    options.Authority = "http://localhost:30466";
            //    options.Audience = "http://localhost:30466/resources";
            //    options.RequireHttpsMetadata = false;
            //    options.AutomaticAuthenticate = true;
            //});
            //app.UseMiddleware<RequiredScopesMiddleware>(new List<string> { "dpcontrolapiscope" });
            #endregion
            #region IdentityServer4
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseIdentityServerAuthentication(options =>
            {
                options.Authority             = Configuration["IdentityServer:AuthorizationServerBaseAddress"];
                options.ScopeName             = Configuration["IdentityServer:APIScopeName"];
                options.ScopeSecret           = Configuration["IdentityServer:APIScopeSecret"];
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge    = true;
            });
            #endregion
            #endregion

            //Response Compression:ZGip, before any other middlewares,
            app.UseMiddleware <CompressionMiddleware>(new MiddlewareOptions()
            {
                Path = _apiPath //for api
            });
            //捕获全局异常消息
            app.UseExceptionHandler(errorApp => new GlobalExceptionBuilder(loggerFactory).ExceptionBuilder(errorApp));
            //X-HTTP-Method-Override
            app.UseMiddleware <XHttpHeaderOverrideMiddleware>(new MiddlewareOptions()
            {
                Path = _apiPath //for api
            });

            //Identity
            app.UseIdentity();

            app.UseStaticFiles();

            //app.UseMvc();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Default}/{id?}");
            });

            app.UseSwaggerGen();

            app.UseSwaggerUi();



            DbInitialization.Initialize(app.ApplicationServices);
        }