public async Task SeedAsync(int retry = 0) { try { dbContext.Database.Migrate(); if (!await dbContext.Customers.AnyAsync()) { dbContext.Customers.AddRange(CustomerSeed.GetTestData()); } if (!await dbContext.Countries.AnyAsync()) { dbContext.Countries.AddRange(CountrySeed.GetTestData()); } if (!await dbContext.Cities.AnyAsync()) { dbContext.Cities.AddRange(CitySeed.GetTestData()); } await dbContext.SaveChangesAsync(); } catch (Exception) { if (retry > 0) { await SeedAsync(retry - 1); } } }
/// <summary> /// Config the application. /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="customerSeed"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CustomerSeed customerSeed) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); } //customerSeed.SeedCustomers(); app.UseMiddleware <ExceptionHandleMiddleware>(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseCustomSwagger(); }
static void Main(string[] args) { try { Console.WriteLine("Creating table dbo.Customers and seeding data"); CustomerSeed.Initialize(); DapperDemo.Run(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Removing Existing Registrations var registrationsTypeToRemove = new List <Type> { typeof(DbContextOptions <CustomerMngtContext>) }; RemoveRegistrations(services, registrationsTypeToRemove); // CreateAsync a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlite() .BuildServiceProvider(); // Add a database context (AppDbContext) using an in-memory database for testing. services.AddDbContext <CustomerMngtContext>(options => { options.UseSqlite(_connectionString); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var buildServiceProvider = services.BuildServiceProvider(); // CreateAsync a scope to obtain a reference to the database contexts using var scope = buildServiceProvider.CreateScope(); var scopedServices = scope.ServiceProvider; var dbContext = scopedServices.GetRequiredService <CustomerMngtContext>(); var logger = scopedServices.GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); // Ensure the database is created. dbContext.Database.EnsureCreated(); try { // Seed the database with some specific test data. Task.FromResult(CustomerSeed.Populate(dbContext)); } catch (Exception ex) { logger.LogError( "An error occurred seeding the database with test messages. Error: {ex.Message}, {ex}", ex.Message, ex); } }); }
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var service = scope.ServiceProvider; try { var context = service.GetRequiredService <CustomerContext>(); CustomerSeed.SeedSync(context).Wait(); } catch (Exception ex) { var logger = service.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "Error occured while seeding data to Databsae"); } } host.Run(); }
static async Task Main(string[] args) { var bus = BusConfiguration.ConfigureMassTransit(); await bus.StartAsync(); Console.WriteLine("Press enter to seed customers"); Console.ReadLine(); await CustomerSeed.Publish(bus); Console.WriteLine("Press enter to seed vehicles"); Console.ReadLine(); await VehicleSeed.Publish(bus); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); await bus.StopAsync(); }
public async Task SeedAsync(int retry = 0) { try { dbContext.Database.Migrate(); if (await dbContext.Customers.CountAsync() == 0) { foreach (var customer in CustomerSeed.Seed()) { dbContext.Customers.Add(customer); } } await dbContext.SaveChangesAsync(); } catch (Exception) { if (retry > 0) { await SeedAsync(retry - 1); } } }
public async Task SeedAsync(int retry = 0) { try { dbContext.Database.Migrate(); if (await dbContext.Customers.CountAsync() == 0) { dbContext.Customers.AddRange(CustomerSeed.GetCustomers()); await dbContext.SaveChangesAsync(); } } catch (Exception ex) { log.LogError("Error Occured while migrating/seeding.", ex); if (retry > 0) { log.LogError("Retrying"); await SeedAsync(retry - 1); } } }
static Task SeedCustomers() => CustomerSeed.Publish(_bus);
public static void Run() { var done = false; while (!done) { switch (GetUserChoice()) { case 1: { IEnumerable <string> customerIds; var stopWatch = new Stopwatch(); if (useCache) { stopWatch.Start(); customerIds = cache.DataTypeManager.GetList <string>( "Customer:CustomerID:All", new ReadThruOptions { Mode = ReadMode.ReadThru }); stopWatch.Stop(); } else { stopWatch.Start(); customerIds = CustomerRepository.GetCustomerIDs(); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); if (customerIds.Count() == 0) { Console.WriteLine("No customers in database"); } else { PrintCustomerIDs(customerIds); } } break; case 2: { var customerID = GetCustomerID(); var stopWatch = new Stopwatch(); if (!string.IsNullOrWhiteSpace(customerID)) { Customer customer; if (useCache) { stopWatch.Start(); customer = cache.Get <Customer>( $"Customer:CustomerID:{customerID}", new ReadThruOptions( ReadMode.ReadThru)); stopWatch.Stop(); } else { stopWatch.Start(); customer = CustomerRepository.GetCustomer(customerID); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); PrintCustomerDetails(customer); } } break; case 3: { var customerID = GetCustomerID(); if (!string.IsNullOrWhiteSpace(customerID)) { if (useCache) { cache.Remove( $"Customer:CustomerID:{customerID}", null, null, new WriteThruOptions( WriteMode.WriteThru)); } else { CustomerRepository.DeleteCustomer(customerID); } } } break; case 4: { var customer = CustomerSeed.SeedCustomers() .Generate(); Console.WriteLine("New customer:\n"); PrintCustomerDetails(customer); if (useCache) { cache.Add( $"Customer:CustomerID:{customer.CustomerID}", new CacheItem(customer) { Dependency = GetCustomerSqlDependency( customer.CustomerID), ResyncOptions = new ResyncOptions(true) }, new WriteThruOptions { Mode = WriteMode.WriteThru }); } else { CustomerRepository.SaveCustomer(customer); } } break; case 5: { var customerID = GetCustomerID(); Customer oldCustomer = null; if (!string.IsNullOrWhiteSpace(customerID)) { if (useCache) { oldCustomer = cache.Get <Customer>( $"Customer:CustomerID:{customerID}", new ReadThruOptions { Mode = ReadMode.ReadThru }); } else { oldCustomer = CustomerRepository.GetCustomer(customerID); } } if (oldCustomer == null) { Console.WriteLine( $"No customer with ID {customerID} exists " + $"in database"); } else { var newCustomer = CustomerSeed.SeedCustomers() .Generate(); newCustomer.CustomerID = customerID; Console.WriteLine("Updated customer:\n"); PrintCustomerDetails(newCustomer); if (useCache) { cache.Insert( $"Customer:CustomerID:{customerID}", new CacheItem(newCustomer) { Dependency = GetCustomerSqlDependency( customerID), ResyncOptions = new ResyncOptions(true) }, new WriteThruOptions { Mode = WriteMode.WriteThru }); } else { CustomerRepository.UpdateCustomer(newCustomer); } } } break; case 6: { var country = GetCustomerCountry(); if (!string.IsNullOrWhiteSpace(country)) { IEnumerable <string> customerIds; var stopWatch = new Stopwatch(); if (useCache) { stopWatch.Start(); customerIds = cache.DataTypeManager.GetList <string>( $"Customer:Country:{country}", new ReadThruOptions { Mode = ReadMode.ReadThru }); stopWatch.Stop(); } else { stopWatch.Start(); customerIds = CustomerRepository.GetCustomerIDsByCountry( country); stopWatch.Stop(); } var ms = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Total operation time: {ms} ms"); if (customerIds.Count() == 0) { Console.WriteLine( $"No customers in database with country " + $" {country}"); } else { PrintCustomerIDs(customerIds); } } } break; case 7: { done = true; } break; } } }