public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
public static async Task Main(string[] args) { var host = BuildWebHost(args); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } host.Run(); }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); await context.Database.MigrateAsync(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await ApplicationDbContextSeed.SeedDefaultRoleAsync(roleManager); // await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { throw; } } await host.RunAsync(); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.AddFile("logs/homiepagesApi-{Date}.txt"); }).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext> (); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> > (); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> > (); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> > (); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); var configuration = host.Services.GetRequiredService <IConfiguration>(); var myLogFilePath = configuration.GetValue <string>("MyLogFilePath"); var logFilePath = myLogFilePath.IndexOf(":") > 0 ? myLogFilePath : Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, myLogFilePath)); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate) .WriteTo.File( logFilePath, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(5)) .CreateLogger(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
public async static Task Main(string[] args) { SerilogLog.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(LevelSwitch) .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File( "logs/log.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7, rollOnFileSizeLimit: true, shared: true) .CreateLogger(); try { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); context.Database.Migrate(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception exp) { SerilogLog.Error(exp, "An error occurred while migrating or seeding the database."); } } await host.RunAsync(); } catch (System.Exception exp) { SerilogLog.Fatal(exp, "Host terminated unexpectedly"); } finally { SerilogLog.Information("Ending the web host!"); SerilogLog.CloseAndFlush(); } }
public static async Task <IServiceProvider> MigrateAndSeedDatabaseAsync(this IServiceProvider provider) { await using var context = provider.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsMySql()) { await context.Database.MigrateAsync(); } await ApplicationDbContextSeed.SeedSampleDataAsync(context); return(provider); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder .ConfigureServices(async services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (AppDbContext) using an in-memory // database for testing. services.AddDbContext <ApplicationDbContext>(options => { options.UseInMemoryDatabase("LibraryDbTesting"); options.UseInternalServiceProvider(serviceProvider); }); //services.AddScoped<IDomainEventDispatcher, NoOpDomainEventDispatcher>(); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (AppDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var context = scopedServices.GetRequiredService <ApplicationDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); // Ensure the database is created. context.Database.EnsureCreated(); var userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >(); try { await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); // Seed the database with test data. ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + $"database with test messages. Error: {ex.Message}"); } } }); }
public static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile( $"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}.json", true, true) .AddEnvironmentVariables() .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); var host = CreateHostBuilder(args).Build(); Log.Information("Web host built correctly"); try { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { Log.Information("Initializing database"); await context.Database.MigrateAsync(); } await ApplicationDbContextSeed.SeedSampleDataAsync(context); } Log.Information("Starting web host"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Web host failed to start"); } finally { Log.Information("Stopping web host"); Log.CloseAndFlush(); } }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <ApplicationDbContext>(); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } await host.RunAsync(); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsMySql()) { { context.Database.Migrate(); } } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
private async static Task CreateDbIfNotExists(IHost host) { using var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred creating the DB."); } }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (ApplicationDbContext) using an in-memory database for testing. services.AddDbContext <ApplicationDbContext>(options => { options.UseInMemoryDatabase("InMemoryChattyDb"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database contexts using var scope = sp.CreateScope(); var scopedServices = scope.ServiceProvider; var appDb = scopedServices.GetRequiredService <ApplicationDbContext>(); var logger = scopedServices.GetRequiredService <ILogger <WebApiFactoryFixture <TStartup> > >(); // Ensure the database is created. appDb.Database.EnsureCreated(); try { // Seed the database with some specific test data. Task.Run(() => ApplicationDbContextSeed.SeedSampleDataAsync(appDb)).GetAwaiter().GetResult(); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } }); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); Console.Out.WriteLine(ex.StackTrace); var logger = scope.ServiceProvider.GetRequiredService <ILogger>(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext context) { app.UseApiVersioning(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Integrating Swagger"); }); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } ApplicationDbContextSeed.SeedSampleDataAsync(context); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseRouting(); app.UseCors(a => a.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); // migrate the database. Best practice = in Main, using service scope using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); // for demo purposes, delete the database & migrate on startup so // we can start with a clean slate //context.Database.EnsureDeleted(); //context.Database.Migrate(); if (context.Database.IsSqlServer()) { context.Database.Migrate(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager); ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating the database."); } } // run the web app await host.RunAsync(); }
public static async Task <int> Main(string[] args) { var name = Assembly.GetExecutingAssembly().GetName(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .Enrich.WithExceptionDetails() .Enrich.WithMachineName() .Enrich.WithProperty("Assembly", $"{name.Name}") .Enrich.WithProperty("Assembly", $"{name.Version}") .WriteTo.SQLite( Environment.CurrentDirectory + @"/Logs/log.db", restrictedToMinimumLevel: LogEventLevel.Information, storeTimestampInUtc: true) .WriteTo.File( new CompactJsonFormatter(), Environment.CurrentDirectory + @"/Logs/log.json", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Information) .WriteTo.Console() .CreateLogger(); try { Log.Information("Starting host"); var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { await context.Database.MigrateAsync(); } await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database"); throw; } } await host.RunAsync(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
public static async Task Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); try { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { await context.Database.MigrateAsync(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.MSSqlServer(context.Database.GetConnectionString(), new MSSqlServerSinkOptions() { TableName = "Log", AutoCreateSqlTable = true }) .CreateLogger(); } var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } await host.RunAsync(); } catch (Exception ex) { Console.WriteLine(ex); Log.Fatal(ex, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } }
public async static Task Main(string[] args) { AppVersionInfo.InitialiseBuildInfoGivenPath(AppDomain.CurrentDomain.BaseDirectory); var buildInfo = AppVersionInfo.GetBuildInfo(); var baseLoggerConfig = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information) .Enrich.FromLogContext() .Enrich.WithProperty("ApplicationName", APP_NAME) .Enrich.WithProperty(nameof(buildInfo.BuildId), buildInfo.BuildId) .Enrich.WithProperty(nameof(buildInfo.BuildNumber), buildInfo.BuildNumber) .Enrich.WithProperty(nameof(buildInfo.BranchName), buildInfo.BranchName) .Enrich.WithProperty(nameof(buildInfo.CommitHash), buildInfo.CommitHash) .WriteTo.File( @"D:\home\LogFiles\Application\webapi.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code); try { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var env = services.GetService <IWebHostEnvironment>(); var configuration = services.GetService <IConfiguration>(); if (env.IsProduction() && !string.IsNullOrWhiteSpace(configuration.GetValue <string>("APPINSIGHTS_INSTRUMENTATIONKEY"))) { var telemetry = services.GetRequiredService <TelemetryConfiguration>(); baseLoggerConfig = baseLoggerConfig.WriteTo.ApplicationInsights(telemetry, TelemetryConverter.Traces); } Log.Logger = baseLoggerConfig.CreateLogger(); var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogInformation($"BaseDirectory: {AppDomain.CurrentDomain.BaseDirectory}"); try { var context = services.GetRequiredService <ApplicationDbContext>(); if (context.Database.IsSqlServer()) { logger.LogInformation("DataBase migration.."); await context.Database.MigrateAsync(); logger.LogInformation("DataBase migrated"); } logger.LogInformation("DataBase seeding.."); await ApplicationDbContextSeed.SeedSampleDataAsync(context); } catch (Exception ex) { logger.LogError(ex, "An error occurred while migrating or seeding the database."); throw; } } Log.Information("Starting up.."); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }