public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); Startup.MyLoggerFactory = loggerFactory; try { var catalogContext = services.GetRequiredService <CatalogContext>(); CatalogContextSeed.SeedAsync(catalogContext, loggerFactory) .Wait(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); AppIdentityDbContextSeed.SeedAsync(userManager).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var serviceProvider = scope.ServiceProvider; var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger(typeof(Program)); try { logger.LogInformation("Migrate databases..."); var storeContext = serviceProvider.GetRequiredService <CatalogContext>(); storeContext.Database.Migrate(); logger.LogInformation("Seeding data into databases if needed..."); await CatalogContextSeed.SeedAsync(storeContext, loggerFactory); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Configure logs loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("CorsPolicy"); app.UseMvcWithDefaultRoute(); app.UseSwagger() .UseSwaggerUi(); var context = (CatalogContext)app .ApplicationServices.GetService(typeof(CatalogContext)); WaitForSqlAvailability(context, loggerFactory); //Seed Data CatalogContextSeed.SeedAsync(app, loggerFactory) .Wait(); var integrationEventLogContext = new IntegrationEventLogContext( new DbContextOptionsBuilder <IntegrationEventLogContext>() .UseSqlServer(Configuration["ConnectionString"], b => b.MigrationsAssembly("Catalog.API")) .Options); integrationEventLogContext.Database.Migrate(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Configure logs if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("CorsPolicy"); app.UseMvcWithDefaultRoute(); app.UseSwagger() .UseSwaggerUi(); var context = (CatalogContext)app .ApplicationServices.GetService(typeof(CatalogContext)); WaitForSqlAvailability(context, loggerFactory); //Seed Data CatalogContextSeed.SeedAsync(app, loggerFactory) .Wait(); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var serviceConfig = services.GetService <IConfiguration>(); var catalogContext = services.GetRequiredService <CatalogContext>(); CatalogContextSeed.StorageAccountConnStr = GetAppSettingsConfigValue(serviceConfig, "appsettings.Development.json", "eShopStorageAccountCS"); var dbSeed = services.GetRequiredService <IDbSeed>(); CatalogContextSeed.SeedAsync(catalogContext, loggerFactory, dbSeed).Wait(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); AppIdentityDbContextSeed.SeedAsync(userManager).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var catalogContext = services.GetRequiredService <CatalogContext>(); await CatalogContextSeed.SeedAsync(catalogContext, loggerFactory); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occured seeding the DB"); } } host.Run(); }
public CatalogContext(IConfiguration configuration) { var client = new MongoClient(configuration.GetValue <string>("DatabaseSettings:ConnectionString")); var database = client.GetDatabase(configuration.GetValue <string>("DatabaseSettings:DatabaseName")); Products = database.GetCollection <Product>(configuration.GetValue <string>("DatabaseSettings:CollectionName")); _ = CatalogContextSeed.SeedData(Products); }
public CatalogContext(ICatalogDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); Products = database.GetCollection <Product>(settings.CollectionName); CatalogContextSeed.SeedData(Products); }
public async Task <IEnumerable <Product> > GetProducts() { CatalogContextSeed.SeedData(_context.Products); return(await _context .Products .Find(p => true) .ToListAsync()); }
private async Task WaitForSqlAvailabilityAsync(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env, int retries = 0) { var logger = loggerFactory.CreateLogger(nameof(Startup)); var policy = CreatePolicy(retries, logger, nameof(WaitForSqlAvailabilityAsync)); await policy.ExecuteAsync(async() => { await CatalogContextSeed.SeedAsync(app, env, loggerFactory); }); }
// 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, UserManager <ApplicationUser> userManager) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.Map("/allservices", builder => builder.Run(async context => { var sb = new StringBuilder(); sb.Append("<h1>All Services</h1>"); sb.Append("<table><thead>"); sb.Append("<tr><th>Type</th><th>Lifetime</th><th>Instance</th></tr>"); sb.Append("</thead><tbody>"); foreach (var svc in _services) { sb.Append("<tr>"); sb.Append($"<td>{svc.ServiceType.FullName}</td>"); sb.Append($"<td>{svc.Lifetime}</td>"); sb.Append($"<td>{svc.ImplementationType?.FullName}</td>"); sb.Append("</tr>"); } sb.Append("</tbody></table>"); await context.Response.WriteAsync(sb.ToString()); })); } else { app.UseExceptionHandler("/Catalog/Error"); } app.UseSession(); app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Catalog}/{action=Index}/{id?}"); }); //Seed Data CatalogContextSeed.SeedAsync(app, loggerFactory) .Wait(); var defaultUser = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; userManager.CreateAsync(defaultUser, "Pass@word1").Wait(); }
public Start MigrationDataBase() { _serverOrder.Host .ErasureDatabase <OrderContext>() .CreateDataBase <OrderContext>((context, services) => { }); _serverCatalog.Host .CreateDataBase <CatalogContext>((context, services) => { CatalogContextSeed.Start(context); }); return(this); }
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 <CatalogContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); services.AddDbContext <AppIdentityDbContext>(options => { options.UseInMemoryDatabase("Identity"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <CatalogContext>(); var loggerFactory = scopedServices.GetRequiredService <ILoggerFactory>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. CatalogContextSeed.SeedAsync(db, loggerFactory).Wait(); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); }
private void InitializeDatabase(IApplicationBuilder app, IHostingEnvironment env) { using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) { var settings = serviceScope.ServiceProvider.GetRequiredService <IOptions <CatalogSettings> >(); var logger = serviceScope.ServiceProvider.GetRequiredService <ILogger <CatalogContextSeed> >(); var context = serviceScope.ServiceProvider.GetRequiredService <CatalogContext>(); CatalogContextSeed configurationDbContextSeed = new CatalogContextSeed(); configurationDbContextSeed.SeedAsync(context, env, settings, logger).Wait(); } }
// 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.Map("/allservices", builder => builder.Run(async context => { var sb = new StringBuilder(); sb.Append("<h1>All Services</h1>"); sb.Append("<table><thead>"); sb.Append("<tr><th>Type</th><th>Lifetime</th><th>Instance</th></tr>"); sb.Append("</thead><tbody>"); foreach (var svc in _services) { sb.Append("<tr>"); sb.Append($"<td>{svc.ServiceType.FullName}</td>"); sb.Append($"<td>{svc.Lifetime}</td>"); sb.Append($"<td>{svc.ImplementationType?.FullName}</td>"); sb.Append("</tr>"); } sb.Append("</tbody></table>"); await context.Response.WriteAsync(sb.ToString()); })); } else { app.UseExceptionHandler("/Catalog/Error"); } app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Catalog}/{action=Index}/{id?}"); }); //Seed Data CatalogContextSeed.SeedAsync(app, loggerFactory) .Wait(); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) using (var dbContext = scope.ServiceProvider.GetRequiredService <CatalogContext>()) { var services = scope.ServiceProvider; var googleOptions = services.GetRequiredService <IOptionsMonitor <GoogleApiOptions> >(); dbContext.Database.Migrate(); var seeder = new CatalogContextSeed(new System.Net.Http.HttpClient(), googleOptions, dbContext); seeder.SeedDataAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } host.Run(); }
private static void SeedDatabase(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var aspnetRunContext = services.GetRequiredService <CatalogContext>(); CatalogContextSeed.SeedAsync(aspnetRunContext, loggerFactory).Wait(); } catch (Exception exception) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(exception, "An error occurred seeding the DB."); } } }
public static async Task SeedDatabase(IServiceScope serviceScope) { IServiceProvider serviceProvider = serviceScope.ServiceProvider; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); try { CatalogContext catalogContext = serviceProvider.GetRequiredService <CatalogContext>(); await CatalogContextSeed.SeedAsync(catalogContext, loggerFactory); //var userManager = services.GetRequiredService<UserManager<ApplicationUser>>(); //var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>(); //await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager); } catch (Exception ex) { ILogger <Program> logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } }
// 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(); app.UseCors("CorsPolicy"); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); app.UseSwagger() .UseSwaggerUi(); var context = app.ApplicationServices.GetService <CatalogContext>(); //WaitForSqlAvailability(context, loggerFactory); // Seed Data CatalogContextSeed.SeedAsync(app, loggerFactory).Wait(); }
// 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()) { CatalogContextSeed.SeedAsync(app).Wait(); app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Catalog Api v1"); }); app.UseHttpsRedirection(); app.UseMvc(); }
public async Task LogsInSampleUser() { var services = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase(); services.AddDbContext <CatalogContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); }); var serviceProvider = new ServiceCollection() .BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (AppIdentityDbContext). using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; try { // seed sample user data var userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >(); CatalogContextSeed.UserManagerSeedAsync(userManager).Wait(); var signInManager = scopedServices.GetRequiredService <SignInManager <ApplicationUser> >(); var email = "*****@*****.**"; var password = "******"; var result = await signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure : false); Assert.True(result.Succeeded); } catch (Exception ex) { } } }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var catalogContext = services.GetRequiredService <CatalogContext>(); await CatalogContextSeed.SeedAsync(catalogContext, loggerFactory); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } await host.RunAsync(); }
public void SetUp() { var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new CatalogProfile()); }); _mapper = mapperConfig.CreateMapper(); repository = new Mock <IProductRepository>(); List <Product> products = (List <Product>)CatalogContextSeed.GetPreConfiguredProducts(); productDto = new ProductDto { Id = 1, Name = "Test Product" }; product = _mapper.Map <Product>(productDto); repository.Setup(m => m.GetAllAsync()).ReturnsAsync(products); repository.Setup(m => m.GetByIdAsync(1)).ReturnsAsync(product); repository.Setup(m => m.UpdateAsync(It.IsAny <Product>())).Returns (Task.FromResult(1)); repository.Setup(m => m.AddAsync(It.IsAny <Product>())).ReturnsAsync(product); repository.Setup(m => m.DeleteAsync(It.IsAny <Product>())).Returns(Task.FromResult(1)); catalogController = new CatalogController(repository.Object, _mapper); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); // cuando inicia el servidor verifica si hay registros en la base de datos using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var catalogContext = services.GetRequiredService <CatalogContext>(); CatalogContextSeed.SeedAsync(catalogContext, loggerFactory).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var storageService = services.GetRequiredService <IStorageService>(); ProductImagesSeed.SeedAsync(storageService, "images", "products", loggerFactory).Wait(); var catalogContext = services.GetRequiredService <CatalogContext>(); catalogContext.Database.EnsureCreated(); CatalogContextSeed.SeedAsync(catalogContext, loggerFactory).Wait(); var salesContext = services.GetRequiredService <SalesContext>(); salesContext.Database.EnsureCreated(); SalesContextSeed.SeedAsync(catalogContext, salesContext, loggerFactory).Wait(); var identityContext = services.GetRequiredService <AppIdentityDbContext>(); identityContext.Database.EnsureCreated(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); AppIdentityDbContextSeed.SeedAsync(userManager).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <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, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("CorsPolicy"); app.UseMvcWithDefaultRoute(); app.UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); var context = app.ApplicationServices.GetService(typeof(CatalogContext)) as CatalogContext; WaitForSqlAvailabilityAsync(context, loggerFactory, app, env).Wait(); ConfigureEventBus(app); //Seed Data CatalogContextSeed.SeedAsync(app, env, loggerFactory).Wait(); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { services.AddScoped(typeof(IDbSeed), typeof(InMemoryDbSeed)); services.AddEntityFrameworkInMemoryDatabase(); // Create a new service provider. var provider = services .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (ApplicationDbContext) using an in-memory // database for testing. services.AddDbContext <CatalogContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(provider); }); services.AddDbContext <AppIdentityDbContext>(options => { options.UseInMemoryDatabase("Identity"); options.UseInternalServiceProvider(provider); }); services.AddIdentity <ApplicationUser, IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores <AppIdentityDbContext>() .AddDefaultTokenProviders(); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <CatalogContext>(); var loggerFactory = scopedServices.GetRequiredService <ILoggerFactory>(); var dbSeed = sp.GetRequiredService <IDbSeed>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. CatalogContextSeed.SeedAsync(db, loggerFactory, dbSeed).Wait(); // seed sample user data var userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >(); AppIdentityDbContextSeed.SeedAsync(userManager).Wait(); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); }
public ProductRepository(IConfiguration configuration) { connectionString = configuration["CatalogDatabaseSettings:ConnectionString"].ToString(); CatalogContextSeed.SeedData(new MongoClient(connectionString).GetDatabase(DatabaseName).GetCollection <Product>("Products")); }