示例#1
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);
        }
示例#2
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>();
        }
示例#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, 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);
        }
示例#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);
        }
示例#5
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);
        }
        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");
        }
        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);
        }
示例#8
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();
        }
示例#9
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();
        }
示例#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);
        }
示例#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();
        }
示例#12
0
        static void Main(string[] args)
        {
            var factory = new NorthwindDbContextFactory();

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

            Console.WriteLine("Hello World!");
        }
示例#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();
        }
示例#14
0
        public List <Product> SetupProducts()
        {
            int            _counter = new int();
            List <Product> _prods   = NorthwindInitializer.GetProducts();

            foreach (Product _product in _prods)
            {
                _product.ProductID = ++_counter;
            }

            return(_prods);
        }
示例#15
0
        public void Setup()
        {
            _randomOrders    = NorthwindInitializer.GetOrders();
            _orderRepository = SetupOrderRepository();

            _randomProducts    = SetupProducts();
            _productRepository = SetupProductRepository();

            _randomCustomers    = NorthwindInitializer.GetCustomers();
            _customerRepository = SetupCustomerRepository();

            _unitOfWork = new Mock <IUnitOfWork>().Object;
        }
示例#16
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);
        }
示例#17
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            //config.MessageHandlers.Add(new HeaderAppenderHandler());
            //config.MessageHandlers.Add(new EndRequestHandler());
            //config.Filters.Add(new ArticlesReversedFilter());

            //config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.MapHttpAttributeRoutes();

            // Autofac configuration
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(typeof(ProductsController).Assembly);

            // Unit of Work
            var _unitOfWork = new Mock <IUnitOfWork>();

            builder.RegisterInstance(_unitOfWork.Object).As <IUnitOfWork>();

            //Repositories
            var _prodRepository = new Mock <ProductRepository>();

            _prodRepository.Setup(x => x.GetAll()).Returns(
                NorthwindInitializer.GetProducts()
                );
            builder.RegisterInstance(_prodRepository.Object).As <IProductRepository>();

            // Services
            builder.RegisterAssemblyTypes(typeof(ProductService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterInstance(new ProductService(_prodRepository.Object, _unitOfWork.Object));
            //builder.RegisterInstance(new BlogService(_blogsRepository.Object, _unitOfWork.Object));

            IContainer container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            appBuilder.UseWebApi(config);
        }
        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");
        }
示例#19
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);
        }
示例#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, 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);
        }
示例#21
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.");
            }
        }
        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);
        }
示例#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, 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);
        }
        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"));
        }
示例#25
0
        public void Setup()
        {
            _unitOfWork = new Mock <IUnitOfWork>().Object;

            _randomProducts    = SetupProducts();
            _productRepository = SetupProductRepository();

            _randomOrders    = NorthwindInitializer.GetOrders();
            _orderRepository = SetupOrderRepository();

            _randomCustomers    = NorthwindInitializer.GetCustomers();
            _customerRepository = SetupCustomerRepository();

            _productService  = new ProductService(_productRepository, _unitOfWork);
            _orderService    = new OrderService(_orderRepository, _unitOfWork);
            _customerService = new CustomerService(_customerRepository, _unitOfWork);

            _dummyAddress = "http://test.com/";
        }
        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");
            }
        }
示例#27
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");
            }
        }
示例#29
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);
 }