public void Seed_ShouldInitializeDatabase() { var stores = 10; var persons = 10; var transactions = 10; var productsPerStore = 100; var purchasesPerTransaction = 10; var options = new DbContextOptionsBuilder <DummyContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; using var context = new DummyContext(options); var initializer = new ContextInitializer(persons, stores, productsPerStore, purchasesPerTransaction, transactions); initializer.Seed(context); Assert.AreEqual(persons, context.Persons.Count()); Assert.AreEqual(stores, context.Stores.Count()); Assert.AreEqual(productsPerStore, context.Stores.First().Products.Count()); Assert.AreEqual(productsPerStore, context.Stores.Last().Products.Count()); Assert.AreEqual(purchasesPerTransaction, context.Transactions.Include(o => o.Purchases).First().Purchases.Count()); Assert.AreEqual(purchasesPerTransaction, context.Transactions.Include(o => o.Purchases).Last().Purchases.Count()); Assert.AreEqual(transactions, context.Persons.First().Transactions.Count()); Assert.AreEqual(transactions, context.Persons.Last().Transactions.Count()); }
protected override void Load(ContainerBuilder builder) { var connection = Environment.GetEnvironmentVariable("GRAPHQL_CONN"); builder.RegisterAssemblyTypes(typeof(InfrastructureException).Assembly) .Where(type => type.Namespace.Contains("PostgresDataAccess")) .AsImplementedInterfaces() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(typeof(InfrastructureException).Assembly) .Where(t => t.Namespace.Contains("PostgresDataAccess") && typeof(Profile).IsAssignableFrom(t) && !t.IsAbstract && t.IsPublic) .As <Profile>(); builder.Register(c => new MapperConfiguration(cfg => { foreach (var profile in c.Resolve <IEnumerable <Profile> >()) { cfg.AddProfile(profile); } })).AsSelf().SingleInstance(); builder.Register(c => c.Resolve <MapperConfiguration>() .CreateMapper(c.Resolve)) .As <IMapper>() .InstancePerLifetimeScope(); if (!string.IsNullOrEmpty(connection)) { using (var context = new Context()) { context.Database.Migrate(); ContextInitializer.Seed(context); } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ContextInitializer seeder) { loggerFactory.AddConsole(_config.GetSection("Logging")); loggerFactory.AddDebug(); loggerFactory.AddFile("Logs/userControl-{Date}.txt"); app.UseCors(config => config.AllowAnyHeader() .AllowAnyMethod() .WithOrigins(_config["Tokens:Issuer"]) ); app.UseIdentity(); app.UseJwtBearerAuthentication(new JwtBearerOptions() { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = _config["Tokens:Issuer"], ValidAudience = _config["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])), ValidateLifetime = true } }); app.UseFacebookAuthentication(new FacebookOptions { AppId = _config["Authentication:Facebook:AppId"], AppSecret = _config["Authentication:Facebook:AppSecret"], //CallbackPath = new PathString("/api/auth/signinFacebook") }); app.UseMvc(); seeder.Seed().Wait(); if (env.IsDevelopment()) { Debug.WriteLine("DEVELOPMENT MODE."); Debug.WriteLine("\tConnectionString=" + _config.GetSection("ConnectionString").Value); var authMessage = _config.GetSection("AuthMessageSenderOptions").Get <AuthMessageSenderOptions>(); Debug.WriteLine("\tSendGrid:User="******"\tTokens:Issuer=" + _config.GetSection("Tokens:Issuer").Value); Debug.WriteLine("\tTokens:Audience=" + _config.GetSection("Tokens:Audience").Value); Debug.WriteLine("\tAdminUser:Name=" + _config["AdminUser:Name"]); Debug.WriteLine("\tAdminUser:Email=" + _config["AdminUser:Email"]); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ContextInitializer dbInitializer) { 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(); app.UseSpaStaticFiles(); app.UseAuthentication(); 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"); } }); dbInitializer.Seed().Wait(); }
// This method gets called by the runtime. Use this method to add services to the container. //public void ConfigureServices(IServiceCollection services) //{ // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ContextInitializer seeder) { var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "wwwroot/index.html"; await next(); } }) .UseCors("AllowAll") .UseMvc() .UseDefaultFiles(options) .UseStaticFiles(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } seeder.Seed().Wait(); //app.UseHttpsRedirection(); //app.UseMvc(); }
static void Main(string[] args) { // seed data var initializer = new ContextInitializer(); initializer.Seed(new Context()); var genreRepository = new GenreRepository(); // load a genre inside a context var genre = genreRepository.FindById(1); // modify the 'genre' entity genreRepository.Update(genre, "new description"); // reload the updated entity var updatedGenre = genreRepository.FindById(1); // result will be false : the entity has not been updated ! var updateSuccessful = updatedGenre.Description == genre.Description; if (!updateSuccessful) { throw new Exception("The updatedGenre has not been stored in database, because it was out of context"); } // --------------------------------------------------------------------------------------- // 1st (BAD) way: one method to do FindById and Update at the same time genreRepository.FindAndUpdate(1, "bla bla bla"); // --------------------------------------------------------------------------------------- // 2nd (GOOD) way: still use FindById method and improve the Update method // with playing with entities status var secondGenre = genreRepository.FindById(1); // attach entity to the context and change his status in one line genreRepository.UpdateByChangingEntityStatusFirstWay(secondGenre, "the new description"); // another way to attach and change the status of the entity - the same as above, in two lines //genreRepository.UpdateByChangingEntityStatusSecondWay(secondGenre, "the new description"); // reload the updated entity var reloadSecondGenre = genreRepository.FindById(1); // result will be true : the entity has been modified updateSuccessful = reloadSecondGenre.Description == secondGenre.Description; if (!updateSuccessful) { throw new Exception("The exception will be never thrown !"); } // --------------------------------------------------------------------------------------- // create a new 'genre' from scratch with an existing Id var newGenreFromScratch = new Genre(2); // update the descritpion genreRepository.UpdateByChangingEntityStatusSecondWay(newGenreFromScratch, "Modified"); var reloadedGenreFromScratch = genreRepository.FindById(2); var resultUpdateFromScratch = (newGenreFromScratch.Description == reloadedGenreFromScratch.Description); if (!resultUpdateFromScratch) { throw new Exception("The exception will be never thrown !"); } // --------------------------------------------------------------------------------------- // add a new genre with generic repository var newGenre = new Genre("Horror"); var genericRepository = new GenericRepository(); genericRepository.GenericWayToAddAnEntity(newGenre); // load new added genre from GenreRepository var newGenreAdded = genreRepository.FindById(newGenre.Id); // compare the two loaded entities var addResult = (newGenre.Description == newGenreAdded.Description); if (!addResult) { throw new Exception("The exception will be never thrown !"); } genericRepository.GenericWayToDeleteAnEntity(newGenre); // --------------------------------------------------------------------------------------- // miscellaneous manipulations using (var ctx = new Context()) { // retrieve simply all borrowers var borrowers = ctx.Borrowers.ToList(); // retrieve books from General catalog var books = ctx.Catalogs .Where(c => c.Type == CatalogType.General) .Select(c => c.Items.OfType <Book>()) .ToList(); // retrieve all available items var availableItems = ctx.LibraryItems .Where(i => i.Status == ItemStatus.Available) .ToList(); // the list of borrowers who borrowed an item var borrower = ctx.Borrowers .Include(b => b.Loans) .First(); // an inline SQL query var borrowersCount = ctx.Database.SqlQuery <int>("SELECT COUNT(0) FROM emprunteur").First(); // all DVD from any catalogs var dvd = ctx.LibraryItems.OfType <Dvd>().First(); // use a stored procedure var legacyRepository = new LegacyRepository(ctx); var borrowersWithDVD = legacyRepository.FindBorrowersWhoOwnsArticlesByType("DVD"); } Console.WriteLine("The End"); Console.Read(); }
public async Task EnsureSeedData(bool isProduction) { ContextInitializer initializer = new ContextInitializer(); await initializer.Seed(this, isProduction); }