Exemple #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, CodeMatchContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 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.UseCors("MyPolicy");

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc();

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

            DBInitializer.Initialize(context);
        }
Exemple #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              UserManager <ApplicationUser> userManager,
                              RoleManager <ApplicationRole> roleManager,
                              ApplicationDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            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.UseCookiePolicy();

            app.UseAuthentication();

            DBInitializer.SeedData(context, userManager, roleManager);

            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #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, DBContext dbcontext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod());

            app.UseMvc();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            DBInitializer.Initialize(dbcontext);

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{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, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var ctx = scope.ServiceProvider.GetService <PetshopAppContext>();
                    DBInitializer.SeedDB(ctx);
                }
            }

            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //Error Handling Middleware
            app.UseMiddleware <ErrorHandlingMiddleware>();


            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

            //Seed DB if table is empty
            DBInitializer.Seed(serviceProvider.GetRequiredService <ApplicationContext>());
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, FoosballContext context)
        {
            app.UseSwagger();

            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "Foosball API");
            });

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("MyPolicy");

            app.UseAuthentication();

            app.UseAuthorization();

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

            DBInitializer.Initialize(context);
        }
Exemple #7
0
        // 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();
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var ctx = scope.ServiceProvider.GetService <PetStoreAppContext>();
                    DBInitializer.SeedDB(ctx);
                }
            }
            else
            {
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var ctx = scope.ServiceProvider.GetService <PetStoreAppContext>();
                    ctx.Database.EnsureCreated();
                }
                app.UseHsts();
            }

            //Enable CORS(før MVC)
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseAuthentication();
            //app.UseHttpsRedirection();
            app.UseMvc();
        }
Exemple #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, LibraryContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            DBInitializer.Initialize(context);

            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()

                        );

            //?
            //app.UseMvc();

            app.UseAuthentication();

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

            /*else
             * {
             *  app.UseExceptionHandler("/Error");
             *  app.UseHsts();
             * }
             *
             * app.UseHttpsRedirection();
             * app.UseStaticFiles();
             * app.UseSpaStaticFiles();
             *
             * 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");
             * }
             * });*/
        }
Exemple #9
0
 public static void CreateDbIfNotExists(IHost host)
 {
     using (IServiceScope scope = host.Services.CreateScope())
     {
         AcmeCorporationContext context = scope.ServiceProvider.GetRequiredService <AcmeCorporationContext>();
         DBInitializer.Init(context);
     }
 }
Exemple #10
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DBInitializer.CreateAndInitializeDatabase();
 }
 public void TestDBInitialize()
 {
     DBInitializer.InsertGroups(connectionString);
     DBInitializer.InsertSubjects(connectionString);
     DBInitializer.InsertStudents(connectionString);
     DBInitializer.InsertExams(connectionString);
     DBInitializer.InsertResults(connectionString);
 }
Exemple #12
0
        public CompanyControllerTest()
        {
            context = new ApplicationDbContext(dbContextOptions);
            DBInitializer _db = new DBInitializer();

            _db.Seed(context);

            //repository = new PostRepository(context);
        }
Exemple #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              DatabaseContext context, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //Configure Swagger only for development not for production app.
                //app.UseSwaggerDocumentation();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            DBInitializer.Initialize(context);

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();

            #region OLD Working code for Swagger Configuration

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAdmin API V1");
                //Reference document: https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=visual-studio
                //To serve the Swagger UI at the app's root (http://localhost:<port>/), set the RoutePrefix property to an empty string:
                c.RoutePrefix = string.Empty;
            });

            #endregion

            app.UseRouting();

            app.UseCors("CorsPolicy");
            //app.UseCors(
            //    options => options.SetIsOriginAllowed(x => _ = true)
            //    .AllowAnyMethod()
            //    .AllowAnyHeader()
            //    .AllowCredentials()
            //);

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                //endpoints.MapControllerRoute(
                //               name: "default",
                //               pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #14
0
        public static async Task <IServiceProvider> InitializeAsync(ApplicationArguments args)
        {
            IServiceProvider services = ConfigureServices(loggingBuilder =>
            {
                _ = loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                _ = loggingBuilder.AddNLog(SetupNLogConfig());
            });

            DiscordSocketClient client = services.GetService <DiscordSocketClient>();
            string token = (await DiscordClientConfiguration.LoadAsync().ConfigureAwait(false)).Token;
            await client.LoginAsync(TokenType.Bot, token).ConfigureAwait(false);

            await client.StartAsync().ConfigureAwait(false);

            CommandManager manager = services.GetService <CommandManager>();
            await manager.StartAsync().ConfigureAwait(false);

            MonkeyDBContext dbContext = services.GetRequiredService <MonkeyDBContext>();
            await DBInitializer.InitializeAsync(dbContext).ConfigureAwait(false);

            IAnnouncementService announcements = services.GetService <IAnnouncementService>();
            await announcements.InitializeAsync().ConfigureAwait(false);

            SteamGameServerService steamGameServerService = services.GetService <SteamGameServerService>();

            steamGameServerService.Initialize();

            MineCraftGameServerService minecraftGameServerService = services.GetService <MineCraftGameServerService>();

            minecraftGameServerService.Initialize();

            IGameSubscriptionService gameSubscriptionService = services.GetService <IGameSubscriptionService>();

            gameSubscriptionService.Initialize();

            IRoleButtonService roleButtonsService = services.GetService <IRoleButtonService>();

            roleButtonsService.Initialize();

            IFeedService feedService = services.GetService <IFeedService>();

            feedService.Start();

            IBattlefieldNewsService battlefieldNewsService = services.GetService <IBattlefieldNewsService>();

            battlefieldNewsService.Start();

            if (args != null && args.BuildDocumentation)
            {
                await manager.BuildDocumentationAsync().ConfigureAwait(false); // Write the documentation

                await Console.Out.WriteLineAsync("Documentation built").ConfigureAwait(false);
            }

            return(services);
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                DBInitializer.Initialize(scope.ServiceProvider.GetRequiredService <SurveyDataContext>());
            }
            host.Run();
        }
Exemple #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, LibraryContext context)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseCors("AllowAllMethods");
     DBInitializer.Initialize(context);
     app.UseMvc();
 }
Exemple #17
0
        public static void InitializeDatabaseAsync()
        {
            DBInitializer.Init();

            DBInitializer.RegisterDocumentCollection(Specimen.collectionName);
            DBInitializer.RegisterDocumentCollection(Requestor.collectionName);
            DBInitializer.RegisterDocumentCollection(Patient.collectionName);
            DBInitializer.RegisterDocumentCollection(Case.collectionName);
            DBInitializer.RegisterDocumentCollection(Slide.collectionName);
        }
        protected void Application_Start()
        {
            var init = new DBInitializer();

            Database.SetInitializer(init);
            init.InitializeDatabase(new DB.BDContext());
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
Exemple #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, LibraryContext libContext)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseMvc();
     app.UseCors("AllowAllHeaders");
     DBInitializer.Initialize(libContext);
 }
Exemple #20
0
        public AssigneeControllersTests()
        {
            var           context = new TodoContext(dbContextOptions);
            DBInitializer db      = new DBInitializer();

            db.SeedDB(context);

            aRepo    = new AssigneeRepo(context);
            aService = new AssigneeService(aRepo);
        }
Exemple #21
0
        public TaskControllersTests()
        {
            var           context = new TodoContext(dbContextOptions);
            DBInitializer db      = new DBInitializer();

            db.SeedDB(context);

            tRepository = new TaskRepo(context);
            taskService = new TaskService(tRepository);
        }
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                await DBInitializer.Initialize(scope.ServiceProvider);
            }
            host.Run();
        }
        protected override void Seed(WP_Project.Models.ApplicationDbContext context)
        {
            var dbInit = new DBInitializer();
            //dbInit.SeedCategory(context);
            //dbInit.SeedItem(context);

            //dbInit.SeedCustomField(context);
            //dbInit.SeedCustomFieldValue(context);
            //dbInit.SeedCustomFieldItems(context);
        }
Exemple #24
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <WebStoreContext>();
                    DBInitializer.Initialize(context);

                    var roleStore   = new RoleStore <IdentityRole>(context);
                    var roleManager = new RoleManager <IdentityRole>(roleStore,
                                                                     new IRoleValidator <IdentityRole>[] { },
                                                                     new UpperInvariantLookupNormalizer(),
                                                                     new IdentityErrorDescriber(), null);
                    if (!roleManager.RoleExistsAsync(WebStoreConstants.Roles.User).Result)
                    {
                        var role   = new IdentityRole(WebStoreConstants.Roles.User);
                        var result = roleManager.CreateAsync(role).Result;
                    }
                    if (!roleManager.RoleExistsAsync(WebStoreConstants.Roles.Admin).Result)
                    {
                        var role   = new IdentityRole(WebStoreConstants.Roles.Admin);
                        var result = roleManager.CreateAsync(role).Result;
                    }

                    var userStore   = new UserStore <User>(context);
                    var userManager = new UserManager <User>(userStore, new OptionsManager <IdentityOptions>(new OptionsFactory <IdentityOptions>(new IConfigureOptions <IdentityOptions>[] { },
                                                                                                                                                  new IPostConfigureOptions <IdentityOptions>[] { })),
                                                             new PasswordHasher <User>(), new IUserValidator <User>[] { }, new IPasswordValidator <User>[] { },
                                                             new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), null, null);
                    if (userStore.FindByEmailAsync("*****@*****.**", CancellationToken.None).Result == null)
                    {
                        var user = new User()
                        {
                            UserName = "******", Email = "*****@*****.**"
                        };
                        var result = userManager.CreateAsync(user, "admin").Result;
                        if (result == IdentityResult.Success)
                        {
                            var roleResult = userManager.AddToRoleAsync(user, WebStoreConstants.Roles.Admin).Result;
                        }
                    }
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app)
 {
     app.UseSession();
     app.UseDeveloperExceptionPage();
     app.UseStatusCodePages();
     app.UseStaticFiles();
     app.UseIdentity();
     app.UseMvcWithDefaultRoute();
     DBInitializer.EnsurePopulated(app);
     IdentitySeedData.EnsurePopulated(app);
 }
Exemple #26
0
        public async Task <ActionResult <IEnumerable <SocialMedia> > > GetSocialMedias()
        {
            DBInitializer.Run();

            if (!Authentication.AuthenticateAsync(Request).Result)
            {
                return(Unauthorized());
            }

            return(await _context.SocialMedias.ToListAsync());
        }
Exemple #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, DBInitializer initializer)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

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

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "911PhoneApp API V1");
                c.RoutePrefix = "swagger"; //swagger to angular
            });

            // Middleware Error Catching
            app.UseMiddleware <ErrorHandlingMiddleware>(!env.IsProduction());

            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");
                }
            });

            // DB Initializator run
            initializer.RunAsync().Wait();
        }
Exemple #28
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetService <AppDBContext>();
                DBInitializer.Seed(dbContext);
            }
            host.Run();
        }
Exemple #29
0
        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            var hostBuilder = new HostBuilder()
                              .ConfigureHostConfiguration(configHost =>
            {
                configHost.SetBasePath(Directory.GetCurrentDirectory());
                configHost.AddJsonFile("hostsettings.json", optional: true);
                configHost.AddJsonFile($"appsettings.json", optional: false);
                configHost.AddEnvironmentVariables();
                configHost.AddEnvironmentVariables("DOTNET_");
                configHost.AddCommandLine(args);
            })
                              .ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: false);
            })
                              .ConfigureServices((hostContext, services) =>
            {
                services.AddTransient <IMessageHandler>((svc) =>
                {
                    var rabbitMQConfigSection = hostContext.Configuration.GetSection("RabbitMQ");
                    string rabbitMQHost       = rabbitMQConfigSection["Host"];
                    string rabbitMQUserName   = rabbitMQConfigSection["UserName"];
                    string rabbitMQPassword   = rabbitMQConfigSection["Password"];
                    return(new RabbitMQMessageHandler(rabbitMQHost, rabbitMQUserName, rabbitMQPassword, "Pitstop", "WorkshopManagement", ""));;
                });

                services.AddTransient <WorkshopManagementDBContext>((svc) =>
                {
                    var sqlConnectionString = hostContext.Configuration.GetConnectionString("WorkshopManagementCN");
                    var dbContextOptions    = new DbContextOptionsBuilder <WorkshopManagementDBContext>()
                                              .UseSqlServer(sqlConnectionString)
                                              .Options;
                    var dbContext = new WorkshopManagementDBContext(dbContextOptions);

                    Policy
                    .Handle <Exception>()
                    .WaitAndRetry(5, r => TimeSpan.FromSeconds(5), (ex, ts) => { Log.Error("Error connecting to DB. Retrying in 5 sec."); })
                    .Execute(() => DBInitializer.Initialize(dbContext));

                    return(dbContext);
                });

                services.AddHostedService <EventHandler>();
            })
                              .UseSerilog((hostContext, loggerConfiguration) =>
            {
                loggerConfiguration.ReadFrom.Configuration(hostContext.Configuration);
            })
                              .UseConsoleLifetime();

            return(hostBuilder);
        }
Exemple #30
0
        public async Task <ActionResult> FillDB()
        {
            Stopwatch     timer       = Stopwatch.StartNew();
            DBInitializer initializer = new DBInitializer();

            initializer.FillDb();
            timer.Stop();

            ViewBag.Time = timer.Elapsed.Seconds;

            return(View());
        }