public bool DoesRawCachedCopyOfMatchExist(SeedData.MatchListing matchListing, string matchId)
        {
            string[] rawfilePathParts = new string[] { _rawMatchDataDirectory, BuildMatchFileName(matchListing, matchId) };
            string filePath = System.IO.Path.Combine(rawfilePathParts);

            return File.Exists(filePath);
        }
        public RiotRestAPI.MatchDTO LoadMatch(SeedData.MatchListing listing, string matchId)
        {
            RiotRestAPI.MatchDTO match = null;

            if (DoesRawCachedCopyOfMatchExist(listing, matchId))
            {
                match = LoadMatchFromRawFile(listing, matchId);
            }
            else
            {
                string rawResponse = "";
                match = LoadMatchFromAPI(listing, matchId, ref rawResponse);

                // Save the raw response file to speed up future queries
                string prettyJSON = JsonPrettyPrinterPlus.PrettyPrinterExtensions.PrettyPrintJson(rawResponse);

                string[] rawfilePathParts = new string[] { _rawMatchDataDirectory, listing.region + "-" + matchId + ".json" };
                string filePath = System.IO.Path.Combine(rawfilePathParts);
                FileStream fstream = new FileStream(filePath, FileMode.Create);
                byte[] data = Encoding.ASCII.GetBytes(prettyJSON);
                fstream.Write(data, 0, data.Length);
                fstream.Close();
            }

            return match;
        }
Ejemplo n.º 3
0
        public void SeedBlogPostTagAndComments()
        {
            var context = new BlogContext();
            var seeder = new SeedData(context);
            var success = seeder.SeedPostTagComments();

            Assert.False(success);
        }
        //mvc
        public static void Main(string[] args)
        {

            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    // Requires using MvcMovie.Models;
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Ejemplo n.º 5
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute("catpage", "{category}/Page{productPage:int}",
                                             new { Controller = "Home", action = "Index" });

                endpoints.MapControllerRoute("page", "Page{productPage:int}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });

                endpoints.MapControllerRoute("category", "{category}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });

                endpoints.MapControllerRoute("pagination",
                                             "Anime/Page{productPage}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });
                endpoints.MapDefaultControllerRoute();
            });
            SeedData.EnsurePopulated(app);
        }
Ejemplo n.º 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Team5_Db db)
        {
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Gallery}/{action=Index}/{id?}");
            });

            db.Database.EnsureDeleted();
            db.Database.EnsureCreated();

            SeedData seed = new SeedData(db);

            seed.Init();
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context  = services.GetRequiredService <ApplicationDbContext>();
                context.Database.Migrate();

                try
                {
                    SeedData.Initialize(services).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                    throw ex;
                }
            }
            host.Run();
        }
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, IWebHostEnvironment env,
                              EFWorkRequestContext requestContext)
        {
            app.UseRequestLocalization();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                SeedData.Seed(requestContext);
            }

            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=ClientRequests}/{action=Index}/{id?}"
                    );
                endpoints.MapDefaultControllerRoute();
            });
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var config   = host.Services.GetRequiredService <IConfiguration>();

                var testUserPW = config["SeedUserPW"];
                try
                {
                    SeedData.Initialize(services, testUserPW).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex.Message, "An error occurred while seeding the initial data");
                }
            }

            host.Run();
        }
Ejemplo n.º 10
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 <ServidorContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                    //DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "Un error a ocurrido cuando se generó la base de datos");
                }
            }

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

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService <JulekalenderContext>();
                    context.Database.Migrate();

                    SeedData.Initialize(services);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            host.Run();
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            //creates a generic host
            var host = CreateHostBuilder(args).Build();

            //Just creates a scope to perform some action
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

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

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService <MovieContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args)
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"node_modules")),
                RequestPath  = "/modules"
            });

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


            SeedData.Seed(app);
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .AddEnvironmentVariables()
                                .Build();

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            try
            {
                var host = CreateHostBuilder(args).Build();

                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;

                    //TODO: apply DB migrations

                    // seed initial admin user
                    SeedData.Initialize(services).Wait();
                }

                Log.Information("Starting web host");
                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
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)
        {
            SeedData.Initial(app);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.Use(async(context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = "/Home";
                    await next();
                }
            });
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Admin",
                    template: "{area:exists}/{controller=Login}/{action=Login}/{id?}"
                    );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Error page returned by environment variable
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // User CSS and JS provided
            app.UseStaticFiles();

            app.UseCookiePolicy();
            app.UseSession();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            // Default routing system
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}"
                    );
            });


            //Creates EasyTagDB if it does not exist and adds default information
            SeedData.EnsurePopulated(app);
            //Creates IdentityUsersEasyTag database if it does not exist and adds default users and roles
            SeedDataIdentiy.EnsurePopulated(app);
        }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

            try
            {
                logger.Debug("init main");
                var host = CreateHostBuilder(args).Build();
                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;

                    try
                    {
                        // Seed data if no data are available
                        SeedData.Initialize(services);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, "Seed data failed.");
                    }
                }

                host.Run();
            }
            catch (Exception ex)
            {
                //NLog: catch setup errors
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }
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, IWebHostEnvironment env, ApplicationContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            SeedData.Seed(context).Wait();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
Ejemplo n.º 21
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, SeedData seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(Builder =>
                {
                    Builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get <IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);

                            var ExceptionDetails = context.Features.Get <IExceptionHandlerPathFeature>();

                            await context.Response.WriteAsync(ExceptionDetails.Error.Message);
                        }
                    });
                });
                // app.UseHsts();
            }
            // app.UseHttpsRedirection();
            seeder.SeedingData();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowCredentials().AllowAnyHeader());
            app.UseAuthentication();
            app.UseSignalR(routes =>
            {
                routes.MapHub <BroadCast>("/notify");
            });
            app.UseMvc();
        }
Ejemplo n.º 22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Users}/{action=Index}/{id?}");
            });

            var anyPendingMigrations = context.Database.GetPendingMigrations().Any();

            Console.WriteLine($"\n\nAny pending migrations? {anyPendingMigrations}");
            if (anyPendingMigrations)
            {
                context.Database.Migrate();
            }

            // Try seeding data
            SeedData.Initialize(context);
        }
        private async Task AddTravelPlanToDatabase(DateTime travelStart, DateTime travelEnd)
        {
            var cars = SeedData.GenerateCars(1);
            await DbContext.AddRangeAsync(cars);

            var car1 = cars[0];

            var locations = SeedData.GenerateLocations(2);
            var locationA = locations[0].LocationId;
            var locationB = locations[1].LocationId;
            await DbContext.AddRangeAsync(locations);

            var employees = SeedData.GenerateEmployees(10);

            var trip = new TravelPlan()
            {
                CarId               = car1.CarId,
                StartLocationId     = locationA,
                EndLocationId       = locationB,
                StartTimeUtc        = travelStart,
                EndTimeUtc          = travelEnd,
                TravelPlanEmployees = new List <TravelPlanEmployees>()
            };

            var addEmployees = employees.Take(3).Select(e => new TravelPlanEmployees()
            {
                EmployeeId = e.EmployeeId,
            });

            addEmployees.ForEach(trip.TravelPlanEmployees.Add);

            await DbContext.Employees.AddRangeAsync(employees);

            await DbContext.AddRangeAsync(trip);

            await DbContext.SaveChangesAsync();
        }
Ejemplo n.º 24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseHttpsRedirection();

            app.UseCors("CorsPolicy");

            SeedData.Seed(userManager, roleManager).Wait();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 25
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsProduction())
            {
                app.UseExceptionHandler("/error");
            }
            else
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages();
            }
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute("catpage",
                                             "{category}/Page{productPage:int}",
                                             new { Controller = "Home", action = "Index" });
                endpoints.MapControllerRoute("page", "Page{productPage:int}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });
                endpoints.MapControllerRoute("category", "{category}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });
                endpoints.MapControllerRoute("pagination",
                                             "Products/Page{productPage}",
                                             new { Controller = "Home", action = "Index", productPage = 1 });
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/admin/{*catchall}", "/Admin/Index");
            });
            SeedData.EnsurePopulated(app);
            IdentitySeedData.EnsurePopulated(app);
        }
Ejemplo n.º 26
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SeedData seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder =>
                {
                    builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        var error = context.Features.Get <IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            //UnComment For Seed User
            //seeder.SeedUser();

            //Baraye Authentication Tartibe In Mavared Mohem Ast.
            app.UseCors(i => i.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 27
0
        // 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();
            }
            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.UseRouting();

            app.UseAuthorization();

            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "products",
                    pattern: "products/{category?}",
                    defaults: new { controller = "Product", action = "List" }
                    );


                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            SeedData.EnsurePopulated(app);
        }
Ejemplo n.º 28
0
        // 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();
            }

            // app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(builder => builder.SetIsOriginAllowed(isOriginAllowed => true)
                        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());

            app.UseAuthorization();

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

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

            //demo only
            // using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            // {
            //     var context = serviceScope.ServiceProvider.GetRequiredService<DataContext>();
            //     context.Database.EnsureCreated();
            // }

            SeedData.EnsurePopulated(app);
            //end demo only
        }
Ejemplo n.º 29
0
        public async Task GetOptionAssignmentAsync_OptionAssignmentIsReturned()
        {
            // Arrange
            var recId = 3;
            List <OptionsQuestionAssignmnents> expectedAssignment = new List <OptionsQuestionAssignmnents>()
            {
                new OptionsQuestionAssignmnents()
                {
                    OptionOrderNum = 1, FormId = 1, QuestionOrderNum = 1, OptionId = 1
                },
                new OptionsQuestionAssignmnents()
                {
                    OptionOrderNum = 2, FormId = 1, QuestionOrderNum = 1, OptionId = 2
                },
                new OptionsQuestionAssignmnents()
                {
                    OptionOrderNum = 3, FormId = 1, QuestionOrderNum = 1, OptionId = 3
                }
            };
            await db.AddRangeAsync(seedAssignments);

            await db.AddRangeAsync(SeedData.GetSeedingOptions());

            await db.AddRangeAsync(SeedData.GetSeedingQuestionsFormAssignment());

            await db.SaveChangesAsync();

            // Act
            var result = await service.Get(recId);

            // Assert
            var actualAssignments = Assert.IsAssignableFrom <List <OptionsQuestionAssignmnents> >(result);

            Assert.Equal(
                expectedAssignment.OrderBy(o => o.QuestionOrderNum).Where(o => o.FormId == recId).Select(o => o.Options.OptionId),
                actualAssignments.OrderBy(o => o.QuestionOrderNum).Select(o => o.Options.OptionId));
        }
Ejemplo n.º 30
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)
        {
            loggerFactory.AddProvider(new FileLogProvider());

            app.UseStatusCodePagesWithReExecute("/Error/{0}");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error/{0}");
            }

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

            app.UseAuthentication();

            //inject hangfire
            app.UseHangfireServer();
            app.UseHangfireDashboard("/hangfire");

            RecurringJob.AddOrUpdate <IHangfireBootstrapper>(
                hangfireStart => hangfireStart.SetJobsWebSites(), Cron.Minutely);

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

            //Add seeddata
            SeedData.Seed(app);
        }
Ejemplo n.º 31
0
        public static void Main(string[] args)
        {
            // Create a host variable to manage the hosting process
            var host = CreateHostBuilder(args).Build();

            // Using the host processs we create an scope for the execution
            using (var scope = host.Services.CreateScope()) {
                // Get the service provider
                var services = scope.ServiceProvider;

                // Initialize the program validating if seeding is needed
                try {
                    SeedData.Initialize(services);
                }
                catch (Exception ex) {
                    // If it is not, we create an instance of the logger and send the error.
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }

                // After all the initialization we run the host manager
                host.Run();
            }
        }
Ejemplo n.º 32
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

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

            app.UseAuthentication();
            app.UseAuthorization();

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

            SeedData.EnsurePopulated(app);
        }
Ejemplo n.º 33
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services       = scope.ServiceProvider;
                var context        = scope.ServiceProvider.GetRequiredService <DatabaseContext>();
                var env            = scope.ServiceProvider.GetService <IHostingEnvironment>();
                var userService    = scope.ServiceProvider.GetService <UserService>();
                var mapper         = scope.ServiceProvider.GetService <IMapper>();
                var profileService = scope.ServiceProvider.GetService <ProfileService>();
                var debateService  = scope.ServiceProvider.GetService <DebateService>();
                var commentService = scope.ServiceProvider.GetService <CommentService>();
                var groupService   = scope.ServiceProvider.GetService <GroupService>();
                context.Database.Migrate();
                if (env.IsDevelopment())
                {
                    var dataSeeder = new SeedData(context, mapper, userService, profileService, debateService, commentService, groupService);
                    dataSeeder.GenerateData();
                }
            }
            host.Run();
        }
 private static string BuildMatchFileName(SeedData.MatchListing matchListing, string matchId)
 {
     return matchListing.region + "-" + matchId + ".json";
 }
        protected RiotRestAPI.MatchDTO LoadMatchFromAPI(SeedData.MatchListing listing, string matchId, ref string rawResponse)
        {
            RiotRestAPI.MatchDTO match = null;

            bool rateLimitHit = true;
            while (rateLimitHit)
            {
                string resource = "/" + listing.region + "/v2.2/match/" + matchId;

                Dictionary<string, string> queryParams = new Dictionary<string, string>();
                queryParams["includeTimeline"] = "true";
                match = _apiConnection.Get<RiotRestAPI.MatchDTO>(resource, queryParams,
                                                                 ref rateLimitHit, ref rawResponse);
                if (match != null)
                {
                    LogProgress("Loaded match " + listing.region + "-" + matchId + " from the API.");
                }
                else if (rateLimitHit)
                {
                    LogProgress("Hit rate limit. Waiting to retry.");
                    System.Threading.Thread.Sleep(RATE_LIMIT_WAIT_IN_MS);
                }
                else
                {
                    LogProgress("Unable to load match: " + listing.region + " - " + matchId);
                }
            }

            return match;
        }
        protected RiotRestAPI.MatchDTO LoadMatchFromRawFile(SeedData.MatchListing matchListing, string matchId)
        {
            RiotRestAPI.MatchDTO match = null;

            string[] rawfilePathParts = new string[] { _rawMatchDataDirectory, BuildMatchFileName(matchListing, matchId) };
            string filePath = System.IO.Path.Combine(rawfilePathParts);
            FileStream fstream = new FileStream(filePath, FileMode.Open);
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RiotRestAPI.MatchDTO));
            object objResponse = null;
            try
            {
                objResponse = jsonSerializer.ReadObject(fstream);
            }
            catch (System.Xml.XmlException ex)
            {
                LogProgress("XML Exception while parsing match response: " + matchListing.region + "-" + matchId + " - " + ex.Message);
            }
            catch (Exception ex)
            {
                LogProgress("Generic Exception while parsing match response: " + matchListing.region + "-" + matchId + " - " + ex.Message);
            }

            fstream.Close();

            if (objResponse == null)
            {
                LogProgress("Failed to load match " + matchListing.region + "-" + matchId + " from cached data. Deleting file.");
                File.Delete(filePath);
            }
            else
            {
                match = (RiotRestAPI.MatchDTO)Convert.ChangeType(objResponse, typeof(RiotRestAPI.MatchDTO));
                LogProgress("Loaded match " + matchListing.region + "-" + matchId + " from cached data.");
            }

            return match;
        }