public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); // Initialize the database var scopeFactory = host.Services.GetRequiredService <IServiceScopeFactory>(); using (var scope = scopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); var roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var userManager = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >(); if (context.Database.EnsureCreated()) { SeedUsers.Initialize(roleManager, userManager); SeedResume.Initialize(context); SeedHireinator.Initialize(context); SeedAbout.Initialize(context); SeedSettings.Initialize(context); SeedContact.Initialize(context); } } host.Run(); }
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); // After Build has been called, all services have been registered (by running Startup) // By using a scope for the services to be requested below, we limit their lifetime to this set of calls. // See: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#call-services-from-main using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { // Get the IConfiguration service that allows us to query user-secrets and // the configuration on Azure var config = host.Services.GetRequiredService <IConfiguration>(); // Set password with the Secret Manager tool, or store in Azure app configuration // dotnet user-secrets set SeedUserPW <pw> var testUserPw = config["SeedUserPW"]; var adminPw = config["SeedAdminPW"]; SeedUsers.Initialize(services, SeedData.UserSeedData, testUserPw).Wait(); SeedUsers.InitializeAdmin(services, "*****@*****.**", "admin", adminPw, "The", "Admin").Wait(); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } } // Go ahead and run the app, everything should be ready host.Run(); }
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <AuthDbContext>(); context.Database.Migrate(); // requires using Microsoft.Extensions.Configuration; var config = host.Services.GetRequiredService <IConfiguration>(); // Set password with the Secret Manager tool. // dotnet user-secrets set SeedUserPW <pw> SeedUsers.Initialize(services).Wait(); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); SeedRoles.Initialize(serviceProvider).GetAwaiter().GetResult(); SeedUsers.Initialize(serviceProvider).GetAwaiter().GetResult(); }
// 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(); // Redirect all http requests to https var options = new RewriteOptions().AddRedirectToHttps(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentity(); // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715 // Add cookie middleware to the configure an identity request and persist it to a cookie. app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", LoginPath = new PathString("/Account/Login/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true, //ExpireTimeSpan = TimeSpan.FromSeconds(10), ExpireTimeSpan = TimeSpan.FromHours(10), SlidingExpiration = true, }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); SeedUsers.Initialize(app.ApplicationServices); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var hostname = Environment.GetEnvironmentVariable("SQLSERVER_HOST") ?? "localhost"; var password = Environment.GetEnvironmentVariable("SQLSERVER_SA_PASSWORD") ?? "123..abc"; var connString = $"Data Source={hostname};Initial Catalog=filmdesigners.at;User ID=sa;Password={password};"; //add framework services. services.AddDbContext <ApplicationDbContext>(options => //Old LocalDB Config //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // NEW DOCKER SQL SERVER options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc")); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Require SSL // TODO: Enable RequireHttps again (disabled for development on Mac) services.Configure <MvcOptions>(options => { options.Filters.Add(new RequireHttpsAttribute()); }); //add framework services. //services.AddDbContext<ApplicationDbContext>(options => //Old LocalDB Config //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // NEW DOCKER SQL SERVER //options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc")); } // Require SSL // TODO: Enable RequireHttps again (disabled for development on Mac) services.Configure <MvcOptions>(options => { //options.Filters.Add(new RequireHttpsAttribute()); }); //add framework services. services.AddDbContext <ApplicationDbContext>(options => //Old LocalDB Config //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // NEW DOCKER SQL SERVER options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc")); services.AddIdentity <ApplicationUser, IdentityRole>(config => { config.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient <IEmailSender, EmailSender>(); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.Configure <AuthMessageSenderOptions>(Configuration); //AuthorizationHandlers services.AddScoped <IAuthorizationHandler, MemberIsOwnerAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, MemberAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, MemberManagerAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, ChapterAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, EnrollmentAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, EventsAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, JobsAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, NewslettersAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, RolesAdministratorAuthorizationHandler>(); services.AddSingleton <IAuthorizationHandler, UsersAdministratorAuthorizationHandler>(); var serviceProvider = services.BuildServiceProvider(); var dbContext = serviceProvider.GetService <ApplicationDbContext>(); SeedUsers.Initialize(serviceProvider); //SeedJobs.Initialize(serviceProvider); //SeedMembers.Initialize(serviceProvider); return(serviceProvider); }