public void Configure(EntityTypeBuilder<Item> builder) { builder.Property(x => x.DefaultMaxQuantity).HasColumnType("decimal(18,2)"); builder.Property(x => x.DefaultMinQuantity).HasColumnType("decimal(18,2)"); builder.Property(x => x.DefaultPrice).HasColumnType("decimal(18,2)"); builder.HasQueryFilter(x => !x.IsDeleted); builder.HasData(DataSeeding.GetItemSeedData()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataSeeding dataSeeding) { dataSeeding.AddSeedData(env.ContentRootPath); app.UseOpenApi(); app.UseSwaggerUi3(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "AppData")), RequestPath = new PathString("/AppData") }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
// 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(); DataSeeding.Seed(app); } 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.UseSession();//session kullan app.UseAuthorization(); app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); using (var scope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var context = new DataContext(); DataSeeding.EnsureDatabaseSeeded(context); } }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { var dbContextOptionsDescriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <FinanceIdentityDbContext>)); services.Remove(dbContextOptionsDescriptor); services.AddDbContext <FinanceIdentityDbContext>(options => { options.UseSqlite(_sqliteConn); }); var sp = services.BuildServiceProvider(); using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var context = scopedServices.GetRequiredService <FinanceIdentityDbContext>(); context.Database.EnsureCreated(); } var userManager = sp.GetRequiredService <IUserManager>(); DataSeeding.SeedUserAccounts(userManager); }); }
public SegmentControllerRoutePostTests( CustomWebApplicationFactory <Startup> factory, DataSeeding dataSeeding) { this.factory = factory; this.dataSeeding = dataSeeding ?? throw new ArgumentNullException(nameof(dataSeeding)); dataSeeding.AddData(factory).Wait(); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); LoadConfigurations(modelBuilder); DataSeeding.Seeding(modelBuilder); }
public SegmentControllerRouteGetTests(CustomWebApplicationFactory <Startup> factory, DataSeeding dataSeeding) { this.factory = factory; this.dataSeeding = dataSeeding; if (dataSeeding == null) { throw new ArgumentNullException(nameof(dataSeeding)); } dataSeeding.AddData(factory).GetAwaiter().GetResult(); }
public void DeleteCharacterFromDbAlsoDeletesCharStats() { // arrange // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var rand = new RngProvider(); var options = new DbContextOptionsBuilder <ANightsTaleContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new ANightsTaleContext(options)) { context.Database.EnsureCreated(); } // Act // Run the test against one instance of the context using (var context = new ANightsTaleContext(options)) { var charRepo = new CharacterRepository(context); DataSeeding seed = new DataSeeding(context, charRepo); seed.SeedCharacterSupportClasses(); var character = seed.SeedCharacter(); charRepo.AddCharacter(character); charRepo.Save(); var stats = seed.SeedCharStats(character); charRepo.AddCharStats(stats); charRepo.Save(); charRepo.RemoveCharacter(1); charRepo.Save(); // Assert Assert.False(context.CharStats.Any()); } } finally { connection.Close(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ReactivitiesDbContext context, UserManager <AppUser> userManager) { //custom exception handling middleware app.UseMiddleware <ExceptionMiddleware>(); //app.UseXContentTypeOptions(); //app.UseReferrerPolicy(opt => opt.NoReferrer()); //app.UseXXssProtection(opt => opt.EnabledWithBlockMode()); //app.UseXfo(opt => opt.Deny()); //app.UseCspReportOnly(opt => opt // .BlockAllMixedContent() // .StyleSources(s => s.Self()) // .FontSources(s => s.Self()) // .FormActions(s => s.Self()) // .FrameAncestors(s => s.Self()) // .ImageSources(s => s.Self()) // .ScriptSources(s => s.Self()) //); if (env.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ReactivitiesAPI v1")); } //else //{ // app.Use(async (context, next) => // { // context.Response.Headers.Add("Strict-Transport-Security", "max-age-31536000"); // await next.Invoke(); // }); //} app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); DataSeeding.SeedData(context, userManager).Wait(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <ChatHub>("/chat"); }); }
public void SetAppropriateSavingThrows() { // arrange // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var rand = new RngProvider(); var options = new DbContextOptionsBuilder <ANightsTaleContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new ANightsTaleContext(options)) { context.Database.EnsureCreated(); } // Act // Run the test against one instance of the context using (var context = new ANightsTaleContext(options)) { var charRepo = new CharacterRepository(context); DataSeeding seed = new DataSeeding(context, charRepo); seed.SeedCharacterSupportClasses(); var character = seed.SeedCharacter(); var stats = seed.SeedCharStats(character); charRepo.SetSavingThrows(character, stats); // Assert Assert.Equal(-3, stats.STR_Save); Assert.Equal(-1, stats.DEX_Save); Assert.Equal(3, stats.CON_Save); Assert.Equal(2, stats.INT_Save); Assert.Equal(0, stats.WIS_Save); Assert.Equal(-3, stats.CHA_Save); } } finally { connection.Close(); } }
public static void Run() { // For benchmarks to be more accurate, make sure you run the seeding before anything // And then restart the application // Lazy loading is a prime example of being impacted by this inverting the intended results. DataSeeding.SeedDataIfWasntSeededBefore(); // Slow-Faster example pairs // The title does not illustrate which you should pick // It rather illustrates when it becomes a problem. CompareExecTimes(InMemory.ChoosingAClass.Slow, InMemory.ChoosingAClass.Fast, "IEnumerable over IQueryable"); CompareExecTimes(InMemory.MethodChoice.Slow, InMemory.MethodChoice.Fast, "equals over =="); CompareExecTimes(RecklessCompute.Slow, RecklessCompute.Fast, "Reckless compute"); CompareExecTimes(Loading.Lazy, Loading.Eager, "Lazy over Eager loading"); CompareExecTimes(LightweightEf.Default, LightweightEf.AsNoTracking, "AsNoTracking for many readonly entities"); CompareExecTimes(MultipleAddsOrRemoves.Slow, MultipleAddsOrRemoves.Fast, "Add over AddRange"); }
public async Task PostSegmentEndpointsForDefaultArticleRefreshAllReturnCreated() { // Arrange const string url = "/segment"; var documentId = Guid.NewGuid(); var currentOpportunitiesSegmentModel = DataSeeding.GetDummyCurrentOpportunitiesSegmentModel(documentId, documentId.ToString().ToLowerInvariant(), 1); var client = factory.CreateClient(); client.DefaultRequestHeaders.Accept.Clear(); // Act var response = await client.PostAsync(url, currentOpportunitiesSegmentModel, new JsonMediaTypeFormatter()).ConfigureAwait(false); // Assert response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.Created); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var config = services.GetRequiredService <IConfiguration>(); if (config.GetValue("Development:IsDataSeedingEnabled", false)) { var userManager = services.GetRequiredService <UserManager <User> >(); var dbContext = services.GetRequiredService <AppDbContext>(); DataSeeding.Seed(dbContext, userManager); } } host.Run(); }
public void BarbarianProficiencyCalculatedCorrectly() { // arrange // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var rand = new RngProvider(); var options = new DbContextOptionsBuilder <ANightsTaleContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new ANightsTaleContext(options)) { context.Database.EnsureCreated(); } // Act // Run the test against one instance of the context using (var context = new ANightsTaleContext(options)) { var charRepo = new CharacterRepository(context); DataSeeding seed = new DataSeeding(context, charRepo); seed.SeedClass(1); var val = charRepo.GetSavingThrowProficiency(1); // Assert Assert.Equal(new List <bool> { true, false, true, false, false, false }, val); } } finally { connection.Close(); } }
public static void InitializeIdentity(IHost host) { using (var scope = host.Services.CreateScope()) { var serviceProvider = scope.ServiceProvider; try { var userManager = serviceProvider.GetRequiredService <UserManager <User> >(); var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); DataSeeding.SeedIdentity(userManager, roleManager); } catch (Exception ex) { var logger = serviceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occured seeding database"); } } }
// 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(); DataSeeding.Seed(app); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); }); }
public void AddCharacterToDbIsSuccessful() { // arrange // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var options = new DbContextOptionsBuilder <ANightsTaleContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new ANightsTaleContext(options)) { context.Database.EnsureCreated(); } // Act // Run the test against one instance of the context using (var context = new ANightsTaleContext(options)) { var charRepo = new CharacterRepository(context); DataSeeding seed = new DataSeeding(context, charRepo); seed.SeedCharacterSupportClasses(); var character = seed.SeedCharacter(); charRepo.AddCharacter(character); charRepo.Save(); // Assert Assert.Equal("Test", context.Character.First().Name); } } finally { connection.Close(); } }
public async Task DeleteSegmentEndpointsReturnSuccessWhenFound() { // Arrange var documentId = Guid.NewGuid(); const string postUrl = "/segment"; var deleteUri = new Uri($"/segment/{documentId}", UriKind.Relative); var currentOpportunitiesSegmentModel = DataSeeding.GetDummyCurrentOpportunitiesSegmentModel(documentId, documentId.ToString().ToLowerInvariant(), 1); var client = factory.CreateClient(); client.DefaultRequestHeaders.Accept.Clear(); _ = await client.PostAsync(postUrl, currentOpportunitiesSegmentModel, new JsonMediaTypeFormatter()).ConfigureAwait(false); // Act var response = await client.DeleteAsync(deleteUri).ConfigureAwait(false); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); }
public void InvalidClassIdThrowsException(int id) { // arrange // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); try { var rand = new RngProvider(); var options = new DbContextOptionsBuilder <ANightsTaleContext>() .UseSqlite(connection) .Options; // Create the schema in the database using (var context = new ANightsTaleContext(options)) { context.Database.EnsureCreated(); } // Act // Run the test against one instance of the context using (var context = new ANightsTaleContext(options)) { var charRepo = new CharacterRepository(context); DataSeeding seed = new DataSeeding(context, charRepo); seed.SeedClass(3); // Assert Assert.ThrowsAny <ArgumentException>(() => charRepo.GetSavingThrowProficiency(id)); } } finally { connection.Close(); } }
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 <DataContext>(); // only apply the following line for a real db, not a memory-based one // context.Database.Migrate(); DataSeeding.Initialize(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public PagesControllerRouteTests(CustomWebApplicationFactory <DFC.App.Pages.Startup> factory) { this.factory = factory; DataSeeding.SeedDefaultArticles(factory); }
public void Configure(EntityTypeBuilder <NotificationConfiguration> builder) { builder.HasData(DataSeeding.GetNotificationConfigurationSeedData()); builder.HasQueryFilter(x => !x.IsDeleted); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); DataSeeding.Seed(modelBuilder); }
public SegmentControllerRouteTests(CustomWebApplicationFactory <Startup> factory, DataSeeding seeding) { this.factory = factory; seeding?.SeedDefaultArticle(factory).GetAwaiter().GetResult(); }
public ProfileControllerRouteTests(CustomWebApplicationFactory <Startup> factory) { this.factory = factory; DataSeeding.SeedDefaultArticle(factory); }
public SitemapControllerRouteTests(CustomWebApplicationFactory <DFC.App.JobCategories.Startup> factory) { this.factory = factory; DataSeeding.SeedDefaultArticles(factory); }
public void Configure(EntityTypeBuilder <Form> builder) { builder.HasQueryFilter(x => !x.IsDeleted); builder.HasData(DataSeeding.GetFormSeedData()); }
public HomeControllerRouteTests(CustomWebApplicationFactory <DFC.App.ContentPages.Startup> factory) { this.factory = factory; DataSeeding.SeedDefaultArticle(factory, Controllers.PagesController.CategoryNameForHelp, Controllers.PagesController.CategoryNameForAlert); }
public HealthControllerRouteTests(CustomWebApplicationFactory <Startup> factory, DataSeeding seeding) { this.factory = factory; seeding?.AddData(factory).GetAwaiter().GetResult(); }