Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                try
                {
                    var context = scope.ServiceProvider.GetService <INorthwindDbContext>();

                    var concreteContext = (NorthwindDbContext)context;

                    concreteContext.Database.Migrate();

                    NorthwindInitializer.Initialize(concreteContext);
                }
                catch (Exception ex)
                {
                    var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while migrating or initializing the database.");
                }
            }

            host.Run();
        }
Ejemplo n.º 2
0
        public async Task ShouldReturnReport()
        {
            UseSqlite();
            var context = GetDbContext();

            NorthwindInitializer.Initialize(context);
            context.Database.GetDbConnection().Execute(@"
                CREATE VIEW viewEmployeesWithManagers(
                        EmployeeFirstName, EmployeeLastName, EmployeeTitle,
                        ManagerFirstName, ManagetLastName, ManagerTitle)
                AS 
                SELECT e.FirstName as EmployeeFirstName, e.LastName as EmployeeLastName, e.Title as EmployeeTitle,
                        m.FirstName as ManagerFirstName, m.LastName as ManagetLastName, m.Title as ManagerTitle
                FROM employees AS e
                JOIN employees AS m ON e.ReportsTo = m.EmployeeID
                WHERE e.ReportsTo is not null");

            var command = new EmployeesWithManagersQueryView(context);


            var result = await command.Execute();

            var doesContainManager    = result.Any(c => c.ManagerTitle == "Vice President, Sales");
            var doesNotContainManager = result.Any(c => c.EmployeeTitle == "Vice President, Sales");

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Count(), 8);
            Assert.IsTrue(doesContainManager);
            Assert.IsFalse(doesNotContainManager);
        }
Ejemplo n.º 3
0
        // 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, NorthwindDbContext dbContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();


            app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, s =>
            {
                s.GeneratorSettings.Title = "Northwind Traders API";
                s.GeneratorSettings.DefaultUrlTemplate          = "{controller}/{action}/{id?}";
                s.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
            });

            app.UseMvc();

            //Redirect non api calls to angular app that will handle routing of the app.
            app.Use(async(context, next) => {
                await next();
                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api/"))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }
            });

            // configure the app to serve index.html from /wwwroot folder
            app.UseDefaultFiles();
            app.UseStaticFiles();
            // configure the app for usage as api
            app.UseMvcWithDefaultRoute();

            NorthwindInitializer.Initialize(dbContext);
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, NorthwindDbContext ctx)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });



            ctx.Database.Migrate();


            NorthwindInitializer.Initialize(ctx);
        }
Ejemplo n.º 5
0
        public TestFixture()
        {
            var builder = new WebHostBuilder()
                          .UseEnvironment("Testing")
                          .UseStartup <CleanArchitecture.Web.Startup>();

            builder.ConfigureServices(services =>
            {
                // Create a new service provider.
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .BuildServiceProvider();

                // Add a database context (ApplicationDbContext) using an in-memory
                // database for testing.
                services.AddDbContext <NorthwindDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                    options.UseInternalServiceProvider(serviceProvider);
                });
            });


            var server = new TestServer(builder);

            Context = server.Host.Services.GetService(typeof(NorthwindDbContext)) as NorthwindDbContext;
            Client  = server.CreateClient();

            NorthwindInitializer.Initialize(Context);
            Context.SaveChanges();
        }
Ejemplo n.º 6
0
        private TestContext()
        {
            var builder = new DbContextOptionsBuilder <NorthwindDbContext>();

            builder.UseSqlServer(
                "Data Source=(LocalDb)\\mssqllocaldb;Initial Catalog=Northwind_loadtest;Integrated Security=SSPI;",
                b => b.MigrationsAssembly("Northwind.EF.Persistence.MSSQL"));

            // use a different dbcontext to perform setup
            using (var initContext = new MsSqlNorthwindDbContext(builder.Options))
            {
                initContext.Database.EnsureDeleted();
                initContext.Database.Migrate();
                NorthwindInitializer.Initialize(initContext);

                var fakeCustomers = new TestCustomerGenerator().Generate();

                // todo: try bulkinsert again after release of ef core 3
                //NorthwindDbContext.BulkInsert<Customer>(fakeCustomers.ToList());

                try
                {
                    initContext.Customers.AddRange(fakeCustomers);
                    initContext.SaveChanges();
                }
                catch (DbUpdateException ex)
                {
                    throw ex.InnerException ?? ex;
                }
            }

            NorthwindDbContext = new MsSqlNorthwindDbContext(builder.Options);
        }
        public async Task ShouldReturnReport()
        {
            var context = GetDbContext(useSqlLite: true);

            NorthwindInitializer.Initialize(context);

            context.Database.GetDbConnection().Execute(@"
CREATE VIEW viewEmployeesWithManagers(
        EmployeeFirstName, EmployeeLastName, EmployeeTitle,
        ManagerFirstName, ManagerLastName, ManagerTitle)
AS
SELECT e.FirstName as EmployeeFirstName, e.LastName as EmployeeLastName, e.Title as EmployeeTitle,
        m.FirstName as ManagerFirstName, m.LastName as ManagerLastName, m.Title as ManagerTitle
FROM employees AS e
JOIN employees AS m ON e.ReportsTo = m.EmployeeID
WHERE e.ReportsTo is not null");

            var query        = new EmployeesWithManagersViewQuery();
            var queryHandler = new EmployeesWithManagersViewQueryHandler(context);
            var result       = await queryHandler.Handle(query, CancellationToken.None);

            Assert.NotEmpty(result);
            Assert.Equal(8, result.Count());
            Assert.Contains(result, r => r.ManagerTitle == "Vice President, Sales");
            Assert.DoesNotContain(result, r => r.EmployeeTitle == "Vice President, Sales");
        }
Ejemplo n.º 8
0
        // 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, NorthwindContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly,
                             settings =>
            {
                settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
            });

            app.UseMvc();
            NorthwindInitializer.Initialize(context);
        }
Ejemplo n.º 9
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Add AutoMapper
            builder.Services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly });

            // Add framework services.
            builder.Services.AddTransient <INotificationService, NotificationService>();
            builder.Services.AddTransient <IDateTime, MachineDateTime>();

            // Add MediatR
            builder.Services.AddMediatR(typeof(GetProductQueryHandler).GetTypeInfo().Assembly);
            builder.Services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehaviour <,>));
            builder.Services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>));

            // Add DbContext using SQL Server Provider
            string SqlConnection = Environment.GetEnvironmentVariable("SqlConnectionString");

            builder.Services.AddDbContext <INorthwindDbContext, NorthwindDbContext>(options =>
                                                                                    options.UseSqlServer(SqlConnection));

            var concreteContext = (NorthwindDbContext)builder.Services.BuildServiceProvider().GetService <INorthwindDbContext>();

            concreteContext.Database.Migrate();
            NorthwindInitializer.Initialize(concreteContext);

            //add fluent validation
            //TODO: Add helper method when available e.g. .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<CreateCustomerCommandValidator>());
            //see https://github.com/JeremySkinner/FluentValidation/issues/1205

            builder.Services.AddTransient <IValidator <CreateCustomerCommand>, CreateCustomerCommandValidator>();
            builder.Services.AddTransient <IValidator <DeleteCustomerCommand>, DeleteCustomerCommandValidator>();
            builder.Services.AddTransient <IValidator <UpdateCustomerCommand>, UpdateCustomerCommandValidator>();
            builder.Services.AddTransient <IValidator <GetCustomerDetailQuery>, GetCustomerDetailQueryValidator>();
        }
Ejemplo n.º 10
0
        // 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, NorthwindContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            NorthwindInitializer.Initialize(context);
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindDbContext db)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                db.Database.Migrate();
                NorthwindInitializer.Initialize(db);
            }

            app.UseMvc();
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            var factory = new NorthwindDbContextFactory();

            using (var context = factory.CreateDbContext(null))
            {
                NorthwindInitializer.Initialize(context);
            }

            Console.WriteLine("Hello World!");
        }
Ejemplo n.º 13
0
        public static void Main(string[] args)
        {
            using (var context = new NorthwindContext())
            {
                NorthwindInitializer.Initialize(context);

                DisplayCustomers(context);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Ejemplo n.º 14
0
        // 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,
                              NorthwindContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, new SwaggerUiSettings
            {
                DefaultUrlTemplate = "{controller}/{action}/{id?}"
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.MapWhen(a => !a.Request.Path.Value.StartsWith("/swagger"), builder =>
                        builder.UseMvc(routes =>
            {
                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            })
                        );

            // app.UseSwagger();

            // app.UseSwaggerUI(c =>
            // {
            //     c.SwaggerEndpoint("/swagger/v1/swagger.json", "Northwind API V1");
            // });

            NorthwindInitializer.Initialize(context);
        }
Ejemplo n.º 15
0
        // 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, NorthwindContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Northwind API V1");
            });

            NorthwindInitializer.Initialize(context);
        }
        public async Task ShouldReturnReport()
        {
            var context = GetDbContext(useSqlLite: true);

            NorthwindInitializer.Initialize(context);

            var query        = new EmployeesWithManagersQuery();
            var queryHandler = new EmployeesWithManagersQueryHandler(context);
            var result       = await queryHandler.Handle(query, CancellationToken.None);

            Assert.NotEmpty(result);
            Assert.Equal(8, result.Count());
            Assert.Contains(result, r => r.ManagerTitle == "Vice President, Sales");
            Assert.DoesNotContain(result, r => r.EmployeeTitle == "Vice President, Sales");
        }
Ejemplo n.º 17
0
        // 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, NorthwindContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();


            app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, s =>
            {
                s.GeneratorSettings.DefaultUrlTemplate          = "{controller}/{action}/{id?}";
                s.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
            });

            app.UseMvc();
            NorthwindInitializer.Initialize(context);
        }
Ejemplo n.º 18
0
        public static NorthwindDbContext Create(bool seedData = true)
        {
            var options = new DbContextOptionsBuilder <NorthwindDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new NorthwindDbContext(options);

            if (seedData)
            {
                NorthwindInitializer.Initialize(db);
                db.SaveChanges();
            }

            return(db);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var config = BuildConfiguration();

            var serviceProvider = BuildServiceProvider(config);

            using (var ctx = serviceProvider.GetService <NorthwindContext>())
            {
                ctx.Database.Migrate();

                NorthwindInitializer.Initialize(ctx);

                var countCompanies = ctx.Customers.Count();
                Console.Out.WriteLine($"DB initialised with {countCompanies} customers.");
            }
        }
Ejemplo n.º 20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseSwaggerUi3(settings =>
            {
                settings.SwaggerUiRoute = "/docs";
                settings.SwaggerRoute   = "/docs/api-specification.json";
            });

            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");
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                }
            });

            // TODO: Review recommendations for EF Core 2.1 seeding, and update.
            NorthwindInitializer.Initialize(context);
        }
Ejemplo n.º 21
0
        public async Task ShouldReturnReport()
        {
            UseSqlite();

            var context = GetDbContext();

            NorthwindInitializer.Initialize(context);
            var command = new EmployeesWithManagersQuery(context);


            var result = await command.Execute();

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Count(), 8);
            Assert.IsTrue(result.Any(c => c.ManagerTitle == "Vice President, Sales"));
            Assert.IsFalse(result.Any(c => c.EmployeeTitle == "Vice President, Sales"));
        }
        public async Task ShouldReturnReport()
        {
            UseSqlite();

            using (var context = GetDbContext())
            {
                // Arrange
                // Use same seed data as production.
                NorthwindInitializer.Initialize(context);

                var query = new EmployeesWithManagersQuery(context);

                // Act
                var result = await query.Execute();

                // Assert
                Assert.NotEmpty(result);
                Assert.Equal(8, result.Count());
                Assert.Contains(result, r => r.ManagerTitle == "Vice President, Sales");
                Assert.DoesNotContain(result, r => r.EmployeeTitle == "Vice President, Sales");
            }
        }
Ejemplo n.º 23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });

            // app.MapWhen(a => !a.Request.Path.Value.StartsWith("/swagger"), builder =>
            //     builder.UseMvc(routes =>
            //     {
            //         routes.MapSpaFallbackRoute(
            //             name: "spa-fallback",
            //             defaults: new { controller = "Home", action = "Index" });
            //     })
            // );

            NorthwindInitializer.Initialize(context);
        }
        public async Task ShouldReturnReport()
        {
            UseSqlite();

            using (var context = GetDbContext())
            {
                // Arrange
                // This view only exists on DB, so we need to create it before querying.
                context.Database.GetDbConnection().Execute(EmployeesWithManagersViewSql);

                NorthwindInitializer.Initialize(context);
                var query = new EmployeesWithManagersViewQuery(context);

                // Act
                var result = await query.Execute();

                // Assert
                Assert.NotEmpty(result);
                Assert.Equal(8, result.Count());
                Assert.Contains(result, r => r.ManagerTitle == "Vice President, Sales");
                Assert.DoesNotContain(result, r => r.EmployeeTitle == "Vice President, Sales");
            }
        }
Ejemplo n.º 25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            NorthwindInitializer.Initialize(context);
        }
 public static void InitializeDbForTests(NorthwindDbContext context)
 {
     NorthwindInitializer.Initialize(context);
 }