コード例 #1
0
        public void ConfigureDevelopment(IApplicationBuilder app, IWebHostEnvironment env,
                                         LeaderboardContext context, TelemetryConfiguration configuration)
        {
            // configuration.DisableTelemetry = true;

            DbInitializer.Initialize(context).Wait();
            app.UseDeveloperExceptionPage();

            app.UseOpenApi(config =>
            {
                config.DocumentName = "v1";
                config.Path         = "/openapi/v1.json";
            });
            app.UseSwaggerUi3(config =>
            {
                config.SwaggerRoutes.Add(new SwaggerUi3Route("v1.0", "/openapi/v1.json"));

                config.Path         = "/openapi";
                config.DocumentPath = "/openapi/v1.json";
            });

            app.UseHealthChecks("/health");
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
コード例 #2
0
 public LeaderboardController(LeaderboardContext context, IFeatureManager featureManager,
                              ILoggerFactory loggerFactory = null)
 {
     this.context        = context;
     this.featureManager = featureManager;
     this.logger         = loggerFactory?.CreateLogger <LeaderboardController>();
 }
コード例 #3
0
        public PersonControllerV1(LeaderboardContext context)
        {
            this.context = context;
            this.context.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;

            personDAL = new PersonDAL(context);
        }
コード例 #4
0
        public async Task <BoardEntryDto> Post(BoardEntryDto boardEntryDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    ReasonPhrase = "Invalid data",
                    StatusCode   = HttpStatusCode.BadRequest
                });
            }

            using (var dbContext = new LeaderboardContext())
            {
                var boardEntry = new BoardEntry
                {
                    Id        = Guid.NewGuid(),
                    Failed    = boardEntryDto.Failed,
                    Passed    = boardEntryDto.Passed,
                    Skipped   = boardEntryDto.Skipped,
                    Username  = boardEntryDto.Username,
                    Submitted = DateTime.UtcNow
                };

                // remove existing entry before adding new one
                // should probably have a password or something
                dbContext.Leaderboard.RemoveRange(dbContext.Leaderboard.Where(l => l.Username == boardEntryDto.Username));

                // add new entry
                var result = dbContext.Leaderboard.Add(boardEntry);
                await dbContext.SaveChangesAsync();

                if (dbContext.TopTenEntries.Any(be => be.Id == result.Id))
                {
                    var clients = GlobalHost.ConnectionManager.GetHubContext <LeaderboardHub>().Clients;
                    clients.All.leaderboardUpdate(await dbContext.TopTenEntries.Select(entry => new BoardEntryDto
                    {
                        Id        = entry.Id,
                        Failed    = entry.Failed,
                        Passed    = entry.Passed,
                        Skipped   = entry.Skipped,
                        Username  = entry.Username,
                        Submitted = entry.Submitted
                    }).ToListAsync());
                }

                return(new BoardEntryDto
                {
                    Failed = result.Failed,
                    Id = result.Id,
                    Passed = result.Passed,
                    Skipped = result.Skipped,
                    Username = result.Username,
                    Submitted = result.Submitted
                });
            }
        }
コード例 #5
0
 public async Task <List <BoardEntryDto> > GetBoard()
 {
     using (var dbContext = new LeaderboardContext())
     {
         return(await dbContext.TopTenEntries.Select(entry => new BoardEntryDto
         {
             Id = entry.Id,
             Failed = entry.Failed,
             Passed = entry.Passed,
             Skipped = entry.Skipped,
             Username = entry.Username,
             Submitted = entry.Submitted
         }).ToListAsync());
     }
 }
コード例 #6
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, LeaderboardContext context)
        {
            LoggerFactory.Create(builder => builder.AddConsole());
            LoggerFactory.Create(builder => builder.AddDebug());
            if (env.EnvironmentName == Microsoft.Extensions.Hosting.Environments.Development)
            {
                DbInitializer.Initialize(context).Wait();
                app.UseDeveloperExceptionPage();
            }

            app.UseOpenApi();
            app.UseSwaggerUi3();
            app.UseMvc();
        }
コード例 #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,
                              ILoggerFactory loggerFactory, LeaderboardContext context)
        {
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
            loggerFactory.AddAzureWebAppDiagnostics(
                new AzureAppServicesDiagnosticsSettings
            {
                OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
            }
                );
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                DbInitializer.Initialize(context).Wait();
                app.UseDeveloperExceptionPage();
            }

            app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
            {
                settings.SwaggerRoute       = "/swagger/v1/swagger.json";
                settings.ShowRequestHeaders = true;
                settings.DocExpansion       = "list";
                settings.UseJsonEditor      = true;
                settings.PostProcess        = document =>
                {
                    document.BasePath = "/";
                };
                settings.GeneratorSettings.Title       = "Leaderboard API";
                settings.GeneratorSettings.Description = "Leaderboard 2019 Web API";
                settings.GeneratorSettings.Version     = "1.0";
                settings.GeneratorSettings.OperationProcessors.Add(
                    new ApiVersionProcessor()
                {
                    IncludedVersions = { "1.0" }
                }
                    );
            });

            app.UseMvcWithDefaultRoute();

            app.UsePrometheusServer();
        }
コード例 #8
0
        public async Task Delete()
        {
            using (var dbContext = new LeaderboardContext())
            {
                dbContext.Leaderboard.RemoveRange(dbContext.Leaderboard);
                await dbContext.SaveChangesAsync();

                var clients = GlobalHost.ConnectionManager.GetHubContext <LeaderboardHub>().Clients;
                clients.All.leaderboardUpdate(await dbContext.TopTenEntries.Select(entry => new BoardEntryDto
                {
                    Id        = entry.Id,
                    Failed    = entry.Failed,
                    Passed    = entry.Passed,
                    Skipped   = entry.Skipped,
                    Username  = entry.Username,
                    Submitted = entry.Submitted
                }).ToListAsync());
            }
        }
コード例 #9
0
        public void ConfigureDevelopment(IApplicationBuilder app, IWebHostEnvironment env,
                                         LeaderboardContext context, TelemetryConfiguration configuration)
        {
            // configuration.DisableTelemetry = true;

            DbInitializer.Initialize(context).Wait();
            app.UseDeveloperExceptionPage();

            app.UseOpenApi(config =>
            {
                config.DocumentName = "v1";
                config.Path         = "/openapi/v1.json";
            });
            app.UseSwaggerUi3(config =>
            {
                config.SwaggerRoutes.Add(new SwaggerUi3Route("v1.0", "/openapi/v1.json"));

                config.Path         = "/openapi";
                config.DocumentPath = "/openapi/v1.json";
            });

            //app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseAzureAppConfiguration();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/ping", new HealthCheckOptions()
                {
                    Predicate = _ => false
                });

                HealthCheckOptions options = new HealthCheckOptions();
                options.ResultStatusCodes[HealthStatus.Degraded] = 418; // I'm a tea pot (or other HttpStatusCode enum)
                options.AllowCachingResponses = true;
                options.Predicate             = _ => true;
                options.ResponseWriter        = UIResponseWriter.WriteHealthCheckUIResponse;
                endpoints.MapHealthChecks("/health", options);

                endpoints.MapHealthChecksUI();
                endpoints.MapControllers();
            });
        }
コード例 #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, LeaderboardContext context)
        {
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
            loggerFactory.AddAzureWebAppDiagnostics(
                new AzureAppServicesDiagnosticsSettings
            {
                OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
            }
                );
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                DbInitializer.Initialize(context).Wait();
                app.UseDeveloperExceptionPage();
            }

            app.UseOpenApi();
            app.UseSwaggerUi3();

            app.UseMvcWithDefaultRoute();
        }
コード例 #11
0
        public async Task <IEnumerable <BoardEntryDto> > Get(int page = 1, int pageSize = 100)
        {
            if (page < 1 || pageSize > 1000 || pageSize < 1)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    ReasonPhrase = "Invalid pagination",
                    StatusCode   = HttpStatusCode.BadRequest
                });
            }

            using (var dbContext = new LeaderboardContext())
            {
                return(await dbContext.TopTenEntries.Select(entry => new BoardEntryDto
                {
                    Id = entry.Id,
                    Failed = entry.Failed,
                    Passed = entry.Passed,
                    Skipped = entry.Skipped,
                    Username = entry.Username,
                    Submitted = entry.Submitted
                }).ToListAsync());
            }
        }
コード例 #12
0
        public ActionResult Post([FromBody] Record record, [FromServices] LeaderboardContext db)
        {
            if (record.Nickname == null || record.Nickname == "")
            {
                return(BadRequest("Invalid nickname"));
            }
            if (record.Guid == null)
            {
                return(BadRequest("Invalid GUID"));
            }
            var found = db.Records.SingleOrDefault(r => r.Guid == record.Guid);

            if (found != default)
            {
                found.Nickname  = record.Nickname;
                found.HighScore = record.HighScore;
            }
            else
            {
                db.Records.Add(record);
            }
            db.SaveChanges();
            return(Ok());
        }
コード例 #13
0
 public LeaderboardController(LeaderboardContext context)
 {
     _context = context;
 }
コード例 #14
0
ファイル: Startup.cs プロジェクト: robrich/dockerworkshop2017
        // 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, LeaderboardContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("CorsPolicy");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger(); // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Leaderboard API V1");
            });
            app.UseMvcWithDefaultRoute();

            if (env.IsDevelopment())
            {
                DbInitializer.Initialize(context).Wait();
            }
        }
コード例 #15
0
 public IEnumerable <Record> Get([FromServices] LeaderboardContext db)
 {
     return(db.Records.OrderByDescending(r => r.HighScore));
 }
コード例 #16
0
 public ScoreDAL(LeaderboardContext context)
 {
     _context   = context;
     _personDAL = new PersonDAL(context);
 }
コード例 #17
0
 public ScoresController(LeaderboardContext context)
 {
     this.context = context;
 }
コード例 #18
0
 public LeaderboardRepository(LeaderboardContext context)
 {
     _context = context;
 }
コード例 #19
0
 public PlayerProvider(LeaderboardContext leaderboardContext)
 {
     this.leaderboardContext = leaderboardContext;
 }
コード例 #20
0
 public PersonDAL(LeaderboardContext context)
 {
     _context = context;
 }
コード例 #21
0
 public LeaderboardRepository(LeaderboardContext leaderboardContext)
 {
     _leaderboardContext = leaderboardContext;
 }
コード例 #22
0
 /// <summary>
 /// Initialises a new instance of the <see cref="LeaderboardService"/> class.
 /// </summary>
 /// <param name="context">The LeaderboardContext object</param>
 public LeaderboardService(LeaderboardContext context, ILogger <LeaderboardService> logger)
 {
     this.context = context;
     this.logger  = logger;
 }