public void GetAllWithoutPagingTest(EmployeeSearchModel searchModel, List <SearchFieldMutator <Employee, EmployeeSearchModel> > searchFieldMutators, int resultCount) { using (var context = new EmployeeDbContext(_fixure.DbContextOptions)) { context.Database.OpenConnection(); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); // arrange if (!context.Employees.Any()) { context.AddRange(DBSeeder.GetDummyEmployeeList()); context.SaveChanges(); } var employeeRepository = new EmployeeRepository(context); // act var employees = employeeRepository.GetAll(searchModel, searchFieldMutators)?.ToList(); // assert Assert.NotNull(employees); Assert.NotEmpty(employees); Assert.Equal(resultCount, employees.Count); } }
private HttpClient CreateClient() { return(factory.WithWebHostBuilder(builder => { builder.ConfigureServices(services => { var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <NetCoreAngularCRUDAppContext>(); var logger = scopedServices.GetRequiredService <ILogger <BlogPostControllerIntegrationTests> >(); try { DBSeeder.ReinitializeDbForTests(db); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the database. Error: {Message}", ex.Message); } } }); }) .CreateClient()); }
// 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, IServiceProvider serviceProvider, ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } using (var loggerFactor = LoggerFactory.Create(builder => { builder.AddConsole(); builder.AddDebug(); })) app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseAuthentication(); DBSeeder.SeedDb(context, userManager, roleManager); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); CreateRoles(serviceProvider).Wait(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ClubContext context) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); DBSeeder.SeedDB(context); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public async void Window_Loaded(object sender, RoutedEventArgs e) { //в строчці поточного стану завантаження виводимо повідомлення,відповідно до етапу виконання. tbstatus.Text = "Start load data..."; //починаємо відлік часу для визначеного етапу. Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //виконання задачі-ініціалізовуємо дані про котів. await Task.Run(() => { _context.Cats.Count(); }); //зупинка вдліку часу на ініціалізацію. stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; //визначаємо час ,витрачений на ініціалізацію. string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); //в окремому тексбоксі виводимо час,відповідного етапу виконання задачі. tbtime.Text = elapsedTime; //pbsimple.Value=(_catService.Count()*100)/elapsedTime.Length; //в строчці поточного стану завантаження виводимо повідомлення,відповідно до етапу виконання. tbstatus.Text = "Connect to database... "; //виконання задачі-заповнення даними бази даних. await DBSeeder.SeedDataAsync(_context); // починаємо новий відлік часу для наступного етапу:отримання множини значень з бази даних. stopWatch = new Stopwatch(); stopWatch.Start(); var list = _context.Cats.AsQueryable() .Select(x => new CatVM() { Id = x.Id.ToString(), Name = x.Name, Birthday = x.Birth, Description = x.Description, Gender = x.Gender, Price = x.AppCatPrices.OrderByDescending(x => x.DateCreate).FirstOrDefault().Price, Image = x.Image }).ToList(); //зупинка відліку часу на отримання множини значень. stopWatch.Stop(); ts = stopWatch.Elapsed; elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); //в окремому тексбоксі виводимо час,відповідного етапу виконання задачі. tbtime.Text = elapsedTime; //в строчці поточного стану завантаження виводимо повідомлення,відповідно до етапу виконання. tbstatus.Text = "Successul load database! "; //отриману множину значень з бази даних представляємо у вигляді колекції КетВьюМодел і виводимо в датагрід. _cats = new ObservableCollection <CatVM>(list); dgSimple.ItemsSource = _cats; }
private void MainForm_Load(object sender, EventArgs e) { this.context = new MyContext(); DBSeeder.SeedAll(this.context); Product product = this.context.products.First(); this.pcBox.Image = Image.FromStream(new MemoryStream(product.image)); this.lblNameProduct.Text = product.Name; this.lblProductDescription.Text = product.Description; }
private static void Seed() { IList <Adult> adults = DBSeeder.ReadJsonFromFile("adults.json"); string famSerialized = JsonSerializer.Serialize(adults, new JsonSerializerOptions { WriteIndented = true }); DBSeeder.Seed(adults); }
// 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()) { app.UseDeveloperExceptionPage(); } DBSeeder.Initialize(app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider); app.UseAuthentication(); app.UseMvc(); }
protected override void Seed(RosterContext context) { if (Debugger.IsAttached == false) { Debugger.Launch(); } // This method will be called after migrating to the latest version. DBSeeder.SeedClubs(context); DBSeeder.SeedIdentities(context); DBSeeder.SeedDuties(context); }
private static void CreateAndSeed() { IList <Family> families = new FamilyGenerator().GenerateFamilies(500); string famSerialized = JsonSerializer.Serialize(families, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText("families.txt", famSerialized); DBSeeder.Seed(families); }
// 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()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } DBSeeder.Seed(app); app.UseHttpsRedirection(); app.UseCors("AllowAll"); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product Management API v1")); //app.UseAuthentication(); app.UseMvc(); DBSeeder.PopulateDB(app); }
// 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()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); // Create a service scope to get an ApplicationDbContext instance using DI using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>(); // Create the Db if it doesn't exist and applies any pending migration. dbContext.Database.Migrate(); // Seed the Db. DBSeeder.Seed(dbContext); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager <IdentityRole> roleManager, UserManager <User> userManager, TechschoolContext context) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/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(); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); DBSeeder.Seed(roleManager, userManager, context).Wait(); }
public static IEnumerable <object[]> GetTestDataForGetAllWithoutPagingTest() { var searchModel = new EmployeeSearchModel() { FirstName = "Foo", LastName = "Bar" }; var searchFieldMutators = new List <SearchFieldMutator <Employee, EmployeeSearchModel> >(); searchFieldMutators.Add(new SearchFieldMutator <Employee, EmployeeSearchModel>(search => true, (query, search) => query.Where(e => e.FirstName.Contains(search.FirstName)))); searchFieldMutators.Add(new SearchFieldMutator <Employee, EmployeeSearchModel>(search => true, (query, search) => query.Where(e => e.LastName.Contains(search.LastName)))); yield return(new object[] { searchModel, searchFieldMutators, 1 }); var searchFieldMutators2 = new List <SearchFieldMutator <Employee, EmployeeSearchModel> >(); yield return(new object[] { searchModel, searchFieldMutators2, DBSeeder.GetDummyEmployeeList().Count }); }
private static void SeedDatabase(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDBContext>(); DBSeeder.Initialize(context, services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError("An error occurred while seeding the database"); } } }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <EmployeeDbContext>(); DBSeeder.Seed(context); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); }
private static void SeedUsers() { IList <User> users = new[] { new User { UserName = "******", Password = "******", Securitylevel = 4 }, new User { UserName = "******", Password = "******", Securitylevel = 3 }, new User { UserName = "******", Password = "******", Securitylevel = 2 } }.ToList(); DBSeeder.SeedUsers(users); }
protected override void Seed(Raisins.Data.RaisinsContext context) { var seeder = new DBSeeder(); seeder.Seed(context); }
public void GetEmployeesTest() { // arrange var mockRepo = new Mock <IEmployeeRepository>(); var mockAutoMapper = new Mock <IMapper>(); mockRepo.Setup(x => x.GetAll(It.IsAny <EmployeeSearchModel>(), It.IsAny <List <SearchFieldMutator <Employee, EmployeeSearchModel> > >())).Returns(DBSeeder.GetDummyEmployeeList()); mockRepo.Setup(x => x.GetAll(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <EmployeeSearchModel>(), It.IsAny <List <SearchFieldMutator <Employee, EmployeeSearchModel> > >())).Returns(DBSeeder.GetDummyEmployeeList()); mockAutoMapper.Setup(y => y.Map <List <EmployeeDto> >(It.IsAny <IEnumerable <Employee> >())).Returns(new List <EmployeeDto> { new EmployeeDto() }); var sut = new EmployeeService(mockRepo.Object, mockAutoMapper.Object); // act var employeeList = sut.GetEmployees(1, new EmployeeSearchModel { FirstName = "Foo", LastName = "Bar" }); // assert Assert.NotNull(employeeList); Assert.NotEmpty(employeeList); Assert.Single(employeeList); }
// 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()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); // global cors policy app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthentication(); app.UseMvc(routes => { //routes.SetTimeZoneInfo(TimeZoneInfo.Utc); routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); /*app.UseMvc(b=>{ * b.SetTimeZoneInfo(TimeZoneInfo.Utc); * b.MapODataServiceRoute(....); * })*/ app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); //spa.UseAngularCliServer(npmScript: "mobil"); } }); // Create a service scope to get an ApplicationDbContext instance using DI using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var dbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>(); // Create the Db if it doesn't exist and applies any pending migration. dbContext.Database.Migrate(); // Seed the Db. DBSeeder.Seed(dbContext); } }
private void MainForm_Load(object sender, EventArgs e) { DBSeeder.SeedAll(_context); }