public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var serviceProvider = scope.ServiceProvider; var userManager = serviceProvider.GetRequiredService <UserManager <IdentityUser> >(); var dbContext = serviceProvider.GetRequiredService <ApplicationDbContext>(); DataInitializer.SeedData(dbContext, userManager); } host.Run(); }
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var serviceProvider = scope.ServiceProvider; var r = serviceProvider.GetRequiredService <ApplicationDbContext>(); var initializer = new DataInitializer(); initializer.InitializeDatabase(r); } host.Run(); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <AppDbContext>(); DataInitializer.Seed(context); } host.Run(); }
public void PostOrders_ShouldReturnOK() { //Arrange var mockOrderService = new Mock <IOrderService>(); var mockCartService = new Mock <ICartService>(); mockOrderService.Setup(x => x.AddOrderDetails(It.IsAny <Order>())).Returns(true); var orderController = new OrderController(mockOrderService.Object, mockCartService.Object); //Act var result = orderController.Post(DataInitializer.GetCartItems()); //Assert Assert.IsInstanceOfType(result, typeof(OkResult)); }
public static void Main(string[] args) { var webHost = CreateHostBuilder(args).Build(); using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <ApplicationContext>(); if (!context.Categories.Any()) { DataInitializer.InitializeData(context); } } webHost.Run(); }
public ProductServiceTest() { MapperHelper.SetUpMapper(); _productDomains = DataInitializer.GetProductFromTextFile(); _attrType = DataInitializer.GetAllTypeAttributeTypeDomains(); _attrValue = DataInitializer.GetAttributeValueDomains(); _productDetail = DataInitializer.GetaProductAttributeHeaders(); _productRepository = SetUpMockHelper.SetUpProductRepository(); _attributeTypeService = SetUpMockHelper.GetAttributeTypeService(); _attributeValueService = SetUpMockHelper.GetAttributeValueService(); }
public MetaData GetMetaData(int level, int stage) { string id = DataInitializer.FormatStageId(level, stage); foreach (MetaData data in this.metaData) { string metaId = DataInitializer.FormatStageId(data.level, data.stage); if (metaId == id) { return(data); } } return(new MetaData()); }
public void GetBooks_ShouldReturnBook() { //Arrange var mock = new Mock <IBookService>(); mock.Setup(x => x.GetBook(It.IsAny <int>())).Returns(DataInitializer.GetBooks().First()); var booksController = new BooksController(mock.Object); //Act IHttpActionResult result = booksController.Get(1); var resultBook = result as OkNegotiatedContentResult <Book>; //Assert Assert.AreEqual(1, resultBook.Content.ID); }
public void GetProductsTest(int length) { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase($"Get_{length}_products") .Options; using (var context = new ApplicationDbContext(options)) { var dataInitializer = new DataInitializer(context); var service = new ProductService(context); dataInitializer.InitializeData(length); Assert.Equal(length, service.GetAllProducts().Count()); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); var context = app.ApplicationServices.GetService <SalesDbContext>(); DataInitializer.Initialize(context); appLifetime.ApplicationStopping.Register(() => endpoint.Stop().GetAwaiter().GetResult()); }
public void TestInit() { if (_appHost == null) { LogManager.LogFactory = new ConsoleLogFactory(); _appHost = new BasicAppHost(); _appHost.Init(); var store = NewDocumentStore(); DataInitializer.InitializerWithDefaultValuesIfEmpty(store); _appHost.Container.RegisterAutoWired <ConfigurationService>(); } }
public static void Main(string[] args) { string pathLog = Path.Combine(AppContext.BaseDirectory, "Logs"); if (!Directory.Exists(pathLog)) { Directory.CreateDirectory(pathLog); } Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .WriteTo.RollingFile(Path.Combine(pathLog, "log-{Date}.txt")) .CreateLogger(); try { var host = CreateHostBuilder(args).Build(); // Création du répertoire pour la base de donnée string pathDatabase = Path.Combine(AppContext.BaseDirectory, "database"); if (!Directory.Exists(pathDatabase)) { Directory.CreateDirectory(pathDatabase); } var scopeFactory = host.Services.GetRequiredService <IServiceScopeFactory>(); using (var scope = scopeFactory.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); var roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var userManager = scope.ServiceProvider.GetRequiredService <UserManager <IdentityUser> >(); // Vrai si la base de données est créée, false si elle existait déjà. if (db.Database.EnsureCreated()) { DataInitializer.InitData(roleManager, userManager).Wait(); } } host.Run(); } catch (Exception ex) { Log.Error(ex, "Erreur dans Main"); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataInitializer dataInitializer) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } app.UseAuthentication(); app.UseMvc(); if (env.IsDevelopment()) { dataInitializer.Seed().Wait(); } }
public void PostCartItem_ShouldReturnItem() { //Arrange var mock = new Mock <ICartService>(); mock.Setup(x => x.AddItemToCart(It.IsAny <CartItem>())).Returns(true); var cartController = new CartController(mock.Object); var result = cartController.Post(new CartItem() { BookID = DataInitializer.GetCartItems().FirstOrDefault().ID }); var resultCartItem = result as OkNegotiatedContentResult <CartItem>; Assert.IsNotNull(resultCartItem); Assert.AreEqual(1, resultCartItem.Content.BookID); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private org.neo4j.helpers.collection.Pair<java.io.File, KeyValueStoreFile> initialState(DataInitializer<EntryUpdater<Key>> initializer) throws java.io.IOException internal virtual Pair <File, KeyValueStoreFile> InitialState(DataInitializer <EntryUpdater <Key> > initializer) { long version = initializer.InitialVersion(); using (ActiveState <Key> creation = StateFactory.open(ReadableState.Empty(KeyFormat(), version), null, VersionContextSupplier)) { try (EntryUpdater <Key> updater = creation.resetter(new ReentrantLock(), () => { } )) { initializer.Initialize(updater); } return(Rotation.create(KeyFormat().filter(creation.dataProvider()), initializer.InitialVersion())); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // This automatically migrates DB // Code to create migration in Package manager console: // PM> add-migration <name> -project MovieStore.DataAccess // Migration will be applied automatically! using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService <MovieStoreContext>(); context.Database.Migrate(); DataInitializer.Initialize(context); } app.UseCors(builder => builder.WithOrigins(Configuration.GetSection("ReactAppUrl").Value) .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // Swagger is here: localhost/swagger/index.html //app.UseSwagger(); //app.UseSwaggerUI(c => //{ // c.SwaggerEndpoint("/swagger/MovieStore/swagger.json", "MovieStore API"); //}); // For the wwwroot folder app.UseStaticFiles(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext, ILoggerFactory loggerFactory, UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager, IOptions <UserApi> userApiOption, IOptions <TokenDescriptor> tokenDescriptor) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseCors(builder => { builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.AllowCredentials(); builder.AllowAnyOrigin(); }); env.ConfigureNLog("nlog.config"); loggerFactory.AddNLog(); app.AddNLogWeb(); } else if (env.IsProduction()) { //TODO: Configure that properly app.UseCors( optCors => optCors.WithOrigins("http://localhost:4200/").AllowAnyMethod()); loggerFactory.AddAzureWebAppDiagnostics(); // loggerFactory.AddApplicationInsights(app.ApplicationServices); } app.UseAuthentication(); app.UseMiddleware(typeof(ErrorHandlerMiddleware)); app.UseMvc(); app.UseStaticFiles(); dbContext.Database.EnsureCreated(); //setup data initializer ILogger logger = loggerFactory.CreateLogger(GetType().Namespace); var usersSeed = new List <UserViewModel>(); Configuration.GetSection("Logins").Bind(usersSeed); DataInitializer.SeedData(logger, userManager, roleManager, usersSeed, userApiOption, tokenDescriptor); //Multi-languages var optLanguages = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >(); app.UseRequestLocalization(optLanguages.Value); }
private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <MonitoringContext>(); DataInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred creating the DB."); } } }
public void Add_RepositoryType() { //_repositoryTypeService.Setup(r=>r.Add((It.IsAny<RepositoryType>()))) // .Callback(new Action<RepositoryType>()) _repositoryTypes = DataInitializer.GetAllRepositoryTypes(); _repositoryTypeService.Setup(p => p.GetAll()).Returns(_repositoryTypes); IList <RepositoryType> list = _repositoryTypeService.Object.GetAll(); List <RepositoryType> repList = new List <RepositoryType> { DataInitializer.repsitoryTypeEntity }; _repositoryTypeService.Object.Add(DataInitializer.repsitoryTypeEntity); //ASSERT NUnit.Framework.Assert.AreEqual(4, list.Count + 1); }
/// <summary> /// Website startup point. /// </summary> /// <param name="args">Arguments.</param> public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var migrationsRunner = scope.ServiceProvider.GetService <IDatabaseMigrationsRunner>(); migrationsRunner.RunMigrations(); var dataInitializer = new DataInitializer(scope.ServiceProvider); await dataInitializer.EnsureRequiredContentsAvailableAsync(); await dataInitializer.EnsureInitialUserAvailableAsync(); } host.Run(); }
// 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(); #region Scoping using (var scope = app.ApplicationServices.CreateScope()) { var ctx = scope.ServiceProvider.GetService <PetAppDBContext>(); ctx.Database.EnsureDeleted(); ctx.Database.EnsureCreated(); var petRepository = scope.ServiceProvider.GetRequiredService <IPetRepository>(); var ownerRepository = scope.ServiceProvider.GetRequiredService <IOwnerRepository>(); var typeRepository = scope.ServiceProvider.GetRequiredService <ITypePetRepository>(); var userRepository = scope.ServiceProvider.GetRequiredService <IUserRepository>(); var authenticationHelper = scope.ServiceProvider.GetRequiredService <IAuthenticationHelper>(); var dataInitializer = new DataInitializer(petRepository, ownerRepository, typeRepository, userRepository, authenticationHelper); dataInitializer.InitData(); } #endregion #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); #endregion app.UseCors("AllowEverything"); app.UseAuthentication(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
public static async Task Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var services = host.Services.CreateScope()) { var db = services.ServiceProvider.GetService <PhoneBookDbContext>(); db.Database.EnsureCreated(); var countOfContacts = await db.Contacts.CountAsync(); if (countOfContacts == 0) { var contactService = services.ServiceProvider.GetService <IContactsService>(); await DataInitializer.Initialize(contactService); } } 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 context = serviceProvider.GetRequiredService <ApplicationContext>(); var userManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); await DataInitializer.Initialize(context); await RolesInitializer.Initialize(userManager, roleManager); } host.Run(); }
public static IHost InitializeData(this IHost host) { // https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-5.0 using var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; try { var context = services.GetRequiredService <AddressDbContext>(); DataInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <AddressDbContext> >(); logger.LogError(ex, "An error occurred creating the DB."); } return(host); }
private static void SeedData(IWebHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { // Requires using RazorPagesMovie.Models; DataInitializer.Seed(services).Wait(); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } } }
private void FormationMatrix(TriangleNetHandler triangleNetHandler, List <Point> points, Canvas canvas, Equation equation) { ///////////FEM var dataInitializer = new DataInitializer(TriangleNetHandler, points, equation); var femContext = dataInitializer.GetInitialData(); fem = new FEMSolver.FEMSolver(femContext); var errorSolver = new ErrorSolver(femContext, TriangleNetHandler, points, equation); var errorsContext = new ErrorContext { ErrorL2 = errorSolver.NormaErrorL2(Functions.U, femContext), ErrorW2 = errorSolver.NormaErrorW2(Functions.U, Functions.DU, femContext), NormL2 = errorSolver.NormaL2(femContext), NormW2 = errorSolver.NormaW2(femContext), pL2 = errorSolver.PL2(), pW2 = errorSolver.PW2(), pAitkenL2 = errorSolver.PAitkenL2(), pAitkenW2 = errorSolver.PAitkenW2(), TrianglesNumber = femContext.Data.NT.Length }; errorContextForGrid.Add(errorsContext); ErrorGrid.ItemsSource = from v in errorContextForGrid select new { v.TrianglesNumber, v.NormL2, v.NormW2, v.ErrorL2, v.ErrorW2, v.pL2, v.pW2, v.pAitkenL2, v.pAitkenW2 }; // DrawInMatlab(x1, x2, z); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataInitializer stackoverflowdatainitializer) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseCors("AllowAllOrigins"); app.UseHttpsRedirection(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseMvc(); app.UseSwaggerUi3(); app.UseSwagger(); stackoverflowdatainitializer.InitializeData().Wait(); }
public static void Main(string[] args) { //1. Get the IWebHost which will host this application. var host = BuildWebHost(args); //2. Find the service layer within our scope. using (var scope = host.Services.CreateScope()) { //3. Get the instance of BoardGamesDBContext in our services layer var services = scope.ServiceProvider; var context = services.GetRequiredService <SchoolDbContext>(); //4. Call the DataGenerator to create sample data DataInitializer.Initialize(services); } //Continue to run the application host.Run(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataInitializer dataInitializer) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseOpenApi(); app.UseSwaggerUi3(); app.UseCors("AllowAllOrigins"); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); dataInitializer.initializeData().Wait(); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Geo Position API V1"); }); // Ensures Product database is created and fully-populated using (var serviceScope = app.ApplicationServices.CreateScope()) { DataInitializer.InitializeDatabaseAsync(serviceScope); } }
protected void btnConfigure_Click(object sender, EventArgs e) { status.Items.Clear(); status.Items.Add("Configuration and Data Initialization Started"); var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); try { var initializer = new DataInitializer(spContext); initializer.Initialize(true); status.Items.Add("Configuration and Data Initialization Complete"); } catch { status.Items.Add("Error initializing the data store. Try running configuration again."); } }