Пример #1
0
        protected void SetupScope()
        {
            var builder = new ContainerBuilder();

            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperConfig());
            }));

            builder.Register(ctx => ctx.Resolve <MapperConfiguration>().CreateMapper()).As <IMapper>().InstancePerLifetimeScope();

            var serviceCollection = new ServiceCollection()
                                    .AddEntityFrameworkInMemoryDatabase();

            var dbOptionsBuilder = new DbContextOptionsBuilder <ImperaContext>();

            builder.Register(_ => dbOptionsBuilder.Options).As <DbContextOptions <ImperaContext> >();

            this.RegisterDependencies(builder);

            builder.Populate(serviceCollection);

            this.Container = builder.Build();

            dbOptionsBuilder.UseInMemoryDatabase("impera_test").UseInternalServiceProvider(new AutofacServiceProvider(this.Container));

            this.Scope      = Container.BeginLifetimeScope("AutofacWebRequest");
            this.Context    = this.Scope.Resolve <ImperaContext>();
            this.UnitOfWork = new UnitOfWork(this.Context);
        }
Пример #2
0
        public static IUnitOfWork GetInMemoryUnitOfWork()
        {
            var options = new DbContextOptionsBuilder <ImperaContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var context = new ImperaContext(options);

            return(new UnitOfWork(context));
        }
        public override async Task Seed(ImperaContext context)
        {
            await base.Seed(context);

            if (context.MapTemplates.FirstOrDefault(x => x.Name == "TestMap") == null)
            {
                context.MapTemplates.Add(new Domain.Map.MapTemplateDescriptor
                {
                    Name = "TestMap",
                    LastModifiedAt = DateTime.UtcNow,
                    CreatedAt = DateTime.UtcNow
                });
            }

            // Add dummy news entry
            var newsEntry = NewsEntry.Create();
            newsEntry.CreatedBy = context.Users.FirstOrDefault(x => x.UserName == "System");
            newsEntry.CreatedAt = DateTime.UtcNow;
            newsEntry.AddContent("en", "DB initialized", "DB has been updated");
            context.NewsEntries.Add(newsEntry);
            context.SaveChanges();
        }
        public override async Task Seed(ImperaContext context)
        {
            await base.Seed(context);

            if (context.MapTemplates.FirstOrDefault(x => x.Name == "TestMap") == null)
            {
                context.MapTemplates.Add(new Domain.Map.MapTemplateDescriptor
                {
                    Name           = "TestMap",
                    LastModifiedAt = DateTime.UtcNow,
                    CreatedAt      = DateTime.UtcNow
                });
            }

            // Add dummy news entry
            var newsEntry = NewsEntry.Create();

            newsEntry.CreatedBy = context.Users.FirstOrDefault(x => x.UserName == "System");
            newsEntry.CreatedAt = DateTime.UtcNow;
            newsEntry.AddContent("en", "DB initialized", "DB has been updated");
            context.NewsEntries.Add(newsEntry);
            context.SaveChanges();
        }
Пример #5
0
        protected void SetupScope()
        {
            var builder = new ContainerBuilder();

            var serviceCollection = new ServiceCollection()
                                    .AddEntityFrameworkInMemoryDatabase();

            var dbOptionsBuilder = new DbContextOptionsBuilder <ImperaContext>();

            builder.Register(_ => dbOptionsBuilder.Options).As <DbContextOptions <ImperaContext> >();

            this.RegisterDependencies(builder);

            builder.Populate(serviceCollection);

            this.Container = builder.Build();

            dbOptionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(new AutofacServiceProvider(this.Container));

            this.Scope      = Container.BeginLifetimeScope("AutofacWebRequest");
            this.Context    = this.Scope.Resolve <ImperaContext>();
            this.UnitOfWork = new UnitOfWork(this.Context);
        }
Пример #6
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, 
            ImperaContext dbContext,
            DbSeed dbSeed)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            // Enable Cors
            app.UseCors(b => b.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().DisallowCredentials().Build());

            // Auth
            app.UseIdentity();
            //app.UseFacebookAuthentication(new FacebookOptions
            //{
            //   ClientId = Configuration["Authentication:Facebook:ClientId"],
            //    AppId = Configuration["Authentication:Facebook:AppId"],
            //    AppSecret = Configuration["Authentication:Facebook:AppSecret"]
            //});
            app.UseOAuthValidation(options => {
                options.Events = new AspNet.Security.OAuth.Validation.OAuthValidationEvents
                {
                    // Note: for SignalR connections, the default Authorization header does not work,
                    // because the WebSockets JS API doesn't allow setting custom parameters.
                    // To work around this limitation, the access token is retrieved from the query string.
                    OnRetrieveToken = context => {
                        context.Token = context.Request.Query["bearer_token"];

                        return Task.FromResult(0);
                    }
                };
            });
            app.UseOpenIddict();

            app.UseMvc();

            app.UseWebSockets();
            app.UseSignalR();

            app.UseSwagger();
            app.UseSwaggerUi();

            // Initialize database
            if (env.IsDevelopment())
            {
                // Always recreate in development
                //dbContext.Database.EnsureDeleted();
                dbContext.Database.EnsureCreated();
            }
            else
            {
                dbContext.Database.Migrate();
            }

            dbSeed.Seed(dbContext).Wait();

            AutoMapperConfig.Configure();

            // Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues = new[] { JobQueues.Critical, JobQueues.Normal },
            });
            app.UseHangfireDashboard();

            Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });

            // Configure Impera background jobs
            JobConfig.Configure();
        }
Пример #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ILoggerFactory loggerFactory,
            ImperaContext dbContext,
            DbSeed dbSeed)
        {
            if (env.IsDevelopment())
            {
                app.UsePathBase("/api");
            }

            NLog.LogManager.Configuration.Variables["configDir"] = Configuration["LogDir"];

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

            // Enable Cors
            app.UseCors(b => b
                        .WithOrigins("http://localhost:8080", "https://dev.imperaonline.de", "https://imperaonline.de", "https://www.imperaonline.de")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithExposedHeaders("X-MiniProfiler-Ids")
                        .AllowCredentials());

            // Auth
            app.UseAuthentication();

            // TODO: Fix, how does this work?
            //app.UseOpenIddict();

            // Enable serving client and static assets
            app.UseResponseCompression();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    // Do not cache main entry point.
                    if (!ctx.File.Name.Contains("index.html"))
                    {
                        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=6000000");
                    }
                }
            });

            app.UseMiniProfiler();

            // Configure swagger generation & UI
            app.UseOpenApi();
            app.UseSwaggerUi3();

            app.UseMvc(routes =>
            {
                // Route for sub areas, i.e. Admin
                routes.MapRoute("areaRoute", "{area:exists}/{controller=News}/{action=Index}");

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

            app.UseWebSockets();
            app.UseSignalR(routes =>
            {
                routes.MapHub <Hubs.MessagingHub>("/signalr/chat");
                routes.MapHub <Hubs.GameHub>("/signalr/game");
            });

            // Initialize database
            Log.Info("Initializing database...").Write();
            if (env.IsDevelopment())
            {
                if (Startup.RunningUnderTest)
                {
                    dbContext.Database.EnsureDeleted();
                }
                else
                {
                    dbContext.Database.Migrate();
                }
            }
            else
            {
                Log.Info("Starting migration...").Write();
                dbContext.Database.Migrate();
                Log.Info("...done.").Write();
            }
            Log.Info("...done.").Write();

            Log.Info("Seeding database...").Write();
            dbSeed.Seed(dbContext).Wait();
            Log.Info("...done.").Write();

            // Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues                  = new[] { JobQueues.Critical, JobQueues.Normal },
                WorkerCount             = 2,
                SchedulePollingInterval = TimeSpan.FromSeconds(30),
                ServerCheckInterval     = TimeSpan.FromSeconds(60),
                HeartbeatInterval       = TimeSpan.FromSeconds(60)
            });
            app.UseHangfireDashboard("/Admin/Hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });

            Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.All
            });

            // Configure Impera background jobs
            JobConfig.Configure();
        }
Пример #8
0
 public GameRepository(ImperaContext context)
     : base(context)
 {
 }
Пример #9
0
        protected void SetupScope()
        {
            var builder = new ContainerBuilder();

            var serviceCollection = new ServiceCollection()
                 .AddEntityFrameworkInMemoryDatabase();

            var dbOptionsBuilder = new DbContextOptionsBuilder<ImperaContext>();

            builder.Register(_ => dbOptionsBuilder.Options).As<DbContextOptions<ImperaContext>>();

            this.RegisterDependencies(builder);

            builder.Populate(serviceCollection);

            this.Container = builder.Build();

            dbOptionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(new AutofacServiceProvider(this.Container));

            this.Scope = Container.BeginLifetimeScope("AutofacWebRequest");
            this.Context = this.Scope.Resolve<ImperaContext>();
            this.UnitOfWork = new UnitOfWork(this.Context);
        }
Пример #10
0
        public virtual async Task Seed(ImperaContext context)
        {
            // Enable if seed should be debugged locally
            // if (System.Diagnostics.Debugger.IsAttached == false)
            //     System.Diagnostics.Debugger.Launch();

            // Insert roles            
            if (await this.roleManager.FindByNameAsync("admin") == null)
            {
                await this.roleManager.CreateAsync(new IdentityRole("admin"));
            }

            if (await this.roleManager.FindByNameAsync("system") == null)
            {
                await this.roleManager.CreateAsync(new IdentityRole("system"));
            }

            // Insert technical user
            User systemUser = await this.userManager.FindByNameAsync("System");
            if (systemUser == null)
            {
                systemUser = new User
                {                    
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    GameSlots = int.MaxValue
                };
                var result = await this.userManager.CreateAsync(systemUser, Guid.NewGuid().ToString());
                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }

            await userManager.AddToRolesAsync(systemUser, new[] { "admin", "system" });

            // Insert bot user
            User botUser = await this.userManager.FindByNameAsync("Bot");
            if (botUser == null)
            {
                botUser = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    GameSlots = int.MaxValue
                };
                await this.userManager.CreateAsync(botUser, Guid.NewGuid().ToString());
            }

            await this.userManager.AddToRoleAsync(botUser, "system");

#if DEBUG
            // Insert test user
            User testUser = context.Users.FirstOrDefault(x => x.UserName == "digitald");
            if (testUser == null)
            {
                testUser = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true
                };
                await this.userManager.CreateAsync(testUser, "impera1234");
            }

            await this.userManager.AddToRoleAsync(testUser, "admin");

            User testUser2 = context.Users.FirstOrDefault(x => x.UserName == "ddtest");
            if (testUser2 == null)
            {
                testUser2 = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true
                };
                await this.userManager.CreateAsync(testUser2, "impera1234");
            }

            // News
            var newsEntry = Domain.News.NewsEntry.Create();
            newsEntry.CreatedBy = newsEntry.CreatedBy = testUser;
            newsEntry.LastModifiedAt =newsEntry.CreatedAt = newsEntry.CreatedAt = DateTime.UtcNow;
            newsEntry.AddContent("en", "Title", "This is a news entry.");            
            context.NewsEntries.Add(newsEntry);
#endif

            context.SaveChanges();

            this.InitChannels(context, systemUser);

            this.InitLadder(context, systemUser);

            // Default set of maps
            var mapType = typeof(Maps);
            foreach (var mapMethod in mapType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
            {
                var mapName = mapMethod.Name;
                var mapTemplateDescriptor = new MapTemplateDescriptor
                {
                    Name = mapName
                };

                mapTemplateDescriptor.LastModifiedAt = mapTemplateDescriptor.CreatedAt = DateTime.UtcNow;

                if (context.MapTemplates.FirstOrDefault(mt => mt.Name == mapTemplateDescriptor.Name) == null)
                {
                    context.MapTemplates.Add(mapTemplateDescriptor);
                }
            }

            context.SaveChanges();
        }
Пример #11
0
        private void InitLadder(ImperaContext context, User systemUser)
        {
            if (context.Ladders.FirstOrDefault(l => l.Name == "Default") == null)
            {
                var ladder = new Ladder("Default", 2, 2);

                ladder.MapTemplates.Add("WorldDeluxe");

                ladder.Options.MapDistribution = MapDistribution.Default;
                ladder.Options.VisibilityModifier.Add(VisibilityModifierType.None);
                ladder.Options.VictoryConditions.Add(VictoryConditionType.Survival);

                ladder.Options.AttacksPerTurn = 3;
                ladder.Options.InitialCountryUnits = 3;
                ladder.Options.MapDistribution = MapDistribution.Default;
                ladder.Options.MaximumNumberOfCards = 5;
                ladder.Options.MaximumTimeoutsPerPlayer = 1;
                ladder.Options.MinUnitsPerCountry = 1;
                ladder.Options.MovesPerTurn = 3;
                ladder.Options.NewUnitsPerTurn = 3;
                ladder.Options.TimeoutInSeconds = (int)TimeSpan.FromDays(1).TotalSeconds;

                ladder.ToggleActive(true);

                context.Ladders.Add(ladder);

                context.SaveChanges();
            }
        }
Пример #12
0
        private void InitChannels(ImperaContext context, User systemUser)
        {
            // Insert default chat channels
            if (context.Channels.FirstOrDefault(c => c.Name == "General") == null)
            {
                context.Channels.Add(new Channel
                {
                    Name = "General",
                    Type = ChannelType.General,
                    CreatedBy = systemUser
                });

                context.Channels.Add(new Channel
                {
                    Name = "Admin",
                    Type = ChannelType.Admin,
                    CreatedBy = systemUser
                });
            }

            context.SaveChanges();
        }
Пример #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,
            ILoggerFactory loggerFactory,
            ImperaContext dbContext,
            DbSeed dbSeed)
        {
            loggerFactory.AddNLog();
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.AddNLogWeb();
            NLog.LogManager.Configuration.Variables["configDir"] = Configuration["LogDir"];

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

            // Enable Cors
            app.UseCors(b => b
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithExposedHeaders("X-MiniProfiler-Ids")
                        .DisallowCredentials()
                        .Build());

            // Auth
            app.UseIdentity();

            /*app.UseFacebookAuthentication(new FacebookOptions
             * {
             *  AppId = Configuration["Authentication:Facebook:AppId"],
             *  AppSecret = Configuration["Authentication:Facebook:AppSecret"]
             * });
             *
             * app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
             * {
             *  ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
             *  ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
             * });*/

            app.UseOAuthValidation(options =>
            {
                options.Events = new AspNet.Security.OAuth.Validation.OAuthValidationEvents
                {
                    // Note: for SignalR connections, the default Authorization header does not work,
                    // because the WebSockets JS API doesn't allow setting custom parameters.
                    // To work around this limitation, the access token is retrieved from the query string.
                    OnRetrieveToken = context =>
                    {
                        context.Token = context.Request.Query["bearer_token"];

                        if (string.IsNullOrEmpty(context.Token))
                        {
                            context.Token = context.Request.Cookies["bearer_token"];
                        }

                        return(Task.FromResult(0));
                    }
                };
            });
            app.UseOpenIddict();

            // Enable serving client and static assets
            app.UseResponseCompression();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    // Do not cache main entry point.
                    if (!ctx.File.Name.Contains("index.html"))
                    {
                        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=6000000");
                    }
                }
            });

            app.UseMiniProfiler(new StackExchange.Profiling.MiniProfilerOptions
            {
                RouteBasePath = "~/admin/profiler",

                SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(),

                // Control storage
                Storage = new MemoryCacheStorage(TimeSpan.FromMinutes(60))
            });

            app.UseMvc(routes =>
            {
                // Route for sub areas, i.e. Admin
                routes.MapRoute("areaRoute", "{area:exists}/{controller=News}/{action=Index}");

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

            app.UseWebSockets();
            app.UseSignalR();

            app.UseSwagger();
            app.UseSwaggerUi();

            // Initialize database
            Log.Info("Initializing database...").Write();
            if (env.IsDevelopment())
            {
                if (Startup.RunningUnderTest)
                {
                    dbContext.Database.EnsureDeleted();
                }

                dbContext.Database.Migrate();
            }
            else
            {
                Log.Info("Starting migration...").Write();
                dbContext.Database.Migrate();
                Log.Info("...done.").Write();
            }
            Log.Info("...done.").Write();

            Log.Info("Seeding database...").Write();
            dbSeed.Seed(dbContext).Wait();
            Log.Info("...done.").Write();

            AutoMapperConfig.Configure();

            // Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues                  = new[] { JobQueues.Critical, JobQueues.Normal },
                WorkerCount             = 2,
                SchedulePollingInterval = TimeSpan.FromSeconds(30),
                ServerCheckInterval     = TimeSpan.FromSeconds(60),
                HeartbeatInterval       = TimeSpan.FromSeconds(60)
            });
            app.UseHangfireDashboard("/Admin/Hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });

            Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.All
            });

            // Configure Impera background jobs
            JobConfig.Configure();
        }