public IActionResult DeleteGame(int gameId) { Game?game = gamesTable.GetGameById(gameId); if (game is null || game.IsRemoved) { return(RedirectToAction("GameNotFound", "ErrorPage")); } User user = usersTable.GetUserByEmail(User.Identity.Name !) !; ViewBag.User = user; ViewData["layout"] = "~/Views/Shared/_AuthorizedLayout.cshtml"; if (!user.IsAdmin) { return(RedirectToAction("AccessDenied", "ErrorPage")); } usersTable.SetCurrentlyEditedGame(user, game.Id); ViewBag.GameTitle = game.Name; return(View()); }
public IActionResult EditGame(int gameId) { Game?game = gamesTable.GetGameById(gameId); if (game is null || game.IsRemoved) { return(RedirectToAction("GameNotFound", "ErrorPage")); } User user = usersTable.GetUserByEmail(User.Identity.Name !) !; ViewBag.User = user; ViewData["layout"] = "~/Views/Shared/_AuthorizedLayout.cshtml"; if (!user.IsAdmin) { return(RedirectToAction("AccessDenied", "ErrorPage")); } usersTable.SetCurrentlyEditedGame(user, game.Id); viewModel = new GameManagementViewModel { Game = game, Genres = genresTable.GetAllGenres(), Features = featuresTable.GetAllFeatures() }; return(View(viewModel)); }
private bool IsPacketAllowed(IMessageReader message, bool hostOnly) { if (Player == null) { return(false); } Game?game = Player.Game; // GameCode must match code of the current game assigned to the player. if (message.ReadInt32() != game.Code) { return(false); } // Some packets should only be sent by the host of the game. if (hostOnly) { if (game.HostId == Id) { return(true); } _logger.LogWarning("[{0}] Client sent packet only allowed by the host ({1}).", Id, game.HostId); return(false); } return(true); }
public async Task <IActionResult> Index(Game?game = null, CancellationToken cancellationToken = default) { ViewBag.Description = Localization["WEBFRONT_DESCRIPTION_HOME"]; ViewBag.Title = Localization["WEBFRONT_HOME_TITLE"]; ViewBag.Keywords = Localization["WEBFRONT_KEWORDS_HOME"]; var servers = Manager.GetServers().Where(_server => !game.HasValue || _server.GameName == game); var(clientCount, time) = await _serverDataViewer.MaxConcurrentClientsAsync(token : cancellationToken); var(count, recentCount) = await _serverDataViewer.ClientCountsAsync(token : cancellationToken); var model = new IW4MAdminInfo() { TotalAvailableClientSlots = servers.Sum(_server => _server.MaxClients), TotalOccupiedClientSlots = servers.SelectMany(_server => _server.GetClientsAsList()).Count(), TotalClientCount = count, RecentClientCount = recentCount, MaxConcurrentClients = clientCount ?? 0, MaxConcurrentClientsTime = time ?? DateTime.UtcNow, Game = game, ActiveServerGames = Manager.GetServers().Select(_server => _server.GameName).Distinct().ToArray() }; return(View(model)); }
public IActionResult Game(string gameId) { bool hasGameInLib = false; Game?game = gamesTable.GetGameByUrl(gameId); if (game == null || game.IsRemoved) { return(RedirectToAction("GameNotFound", "ErrorPage", new { GameId = gameId })); } if (User.Identity.IsAuthenticated) { User user = usersTable.GetUserByEmail(User.Identity.Name !) !; ViewBag.User = user; ViewData["layout"] = "~/Views/Shared/_AuthorizedLayout.cshtml"; if (user.Library != null && user.Library.UserLibraryGames.Any()) { hasGameInLib = user.Library.UserLibraryGames.FirstOrDefault(ulg => ulg.GameId == game.Id) != null; } } ViewBag.hasGameInLib = hasGameInLib; return(View(game)); }
public async Task DeleteGame_WhenCurrentGameIsNotFound_ShouldReturnNotFoundResult() { // Arrange var gameRepository = A.Fake <IGameRepository>(); Game?game = null; A.CallTo(() => gameRepository.GetGameAsync(A <int> .Ignored)).Returns(game); var sharedRepository = A.Fake <ISharedRepository>(); var mapper = A.Fake <IMapper>(); var linkGenerator = A.Fake <LinkGenerator>(); var gameService = A.Fake <IGameService>(); var testController = new GamesController(gameRepository, sharedRepository, mapper, linkGenerator, gameService); int id = 1; // Act var result = await testController.DeleteGame(id); // Assert A.CallTo(() => gameRepository.GetGameAsync(id)).MustHaveHappenedOnceExactly(); result.Result.ShouldBeOfType <NotFoundObjectResult>(); ((NotFoundObjectResult)result.Result).Value.ShouldBe($"Could not find game with ID of {id}"); }
public override async Task OnConnectedAsync() { if (Context.User?.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated) { Debug.Fail("User was not authenticated when connecting to hub."); return; } string roomId = identity.FindFirst(JwtConfig.RoomIdClaimType) !.Value; bool isAdmin = identity.FindFirst(JwtConfig.RoleClaimType)?.Value == Policies.AdminRole; string?playerName = identity.FindFirst(JwtRegisteredClaimNames.GivenName)?.Value; if (!isAdmin) { Game?game = await _dbContext.GetGameByRoomId(roomId, tracking : false); if (game is null) { throw new HubException($"Game '{roomId}' does not exist."); } if (!game.Players.Any(p => p.Name == playerName)) { throw new HubException($"There's no player with the name '{playerName}' in game '{roomId}'."); } } await Groups.AddToGroupAsync(Context.ConnectionId, roomId); //IList<string> connectionIds = s_connectionIds.GetOrAdd(Context.UserIdentifier!, new List<string>()); //lock (connectionIds) //{ // connectionIds.Add(Context.ConnectionId); //} }
public async Task Delete_WhenIdIsNotNullAndGameIsNotFound_ShouldReturnNotFound() { // Arrange var gamesIndexViewModel = A.Fake <IGamesIndexViewModel>(); var gamesDetailsViewModel = A.Fake <IGamesDetailsViewModel>(); var gameService = A.Fake <IGameService>(); var gameRepository = A.Fake <IGameRepository>(); Game?game = null; A.CallTo(() => gameRepository.GetGameAsync(A <int> .Ignored)).Returns(game); var teamRepository = A.Fake <ITeamRepository>(); var seasonRepository = A.Fake <ISeasonRepository>(); var sharedRepository = A.Fake <ISharedRepository>(); var testController = new GamesController(gamesIndexViewModel, gamesDetailsViewModel, gameService, gameRepository, teamRepository, seasonRepository, sharedRepository); int?id = 1; // Act var result = await testController.Delete(id); // Assert A.CallTo(() => gameRepository.GetGameAsync(id.Value)).MustHaveHappenedOnceExactly(); result.ShouldBeOfType <NotFoundResult>(); }
/// <summary> /// Return the GameType currently set in DisciplineMeta for the selected class name and year or nothing, if no GameType /// is set. /// </summary> /// <param name="className">The class name of the class the GameType is to be returned.</param> /// <param name="year">The year for which the GameType is valid.</param> /// <returns> /// A member of the Enum GameType that represents the GameType set in DisciplineMeta for the corresponding class /// in the given year. /// </returns> /// <remarks></remarks> public static Game?GetGameType(string className, short year) { Game?result = null; using (HonglornDb db = new HonglornDb()) { Discipline[] disciplines = (from c in db.DisciplineCollection where c.ClassName == className && c.Year == year select new[] { c.MaleSprint, c.MaleJump, c.MaleThrow, c.MaleMiddleDistance, c.FemaleSprint, c.FemaleJump, c.FemaleThrow, c.FemaleMiddleDistance }).SingleOrDefault(); if (disciplines.All(d => d is CompetitionDiscipline)) { result = Game.Competition; } else if (disciplines.All(d => d is TraditionalDiscipline)) { result = Game.Traditional; } } return(result); }
public IViewComponentResult Invoke(Game?game) { var servers = Program.Manager.GetServers().Where(_server => !game.HasValue ? true : _server.GameName == game); var serverInfo = servers.Select(s => new ServerInfo() { Name = s.Hostname, ID = s.EndPoint, Port = s.Port, Map = s.CurrentMap.Alias, ClientCount = s.ClientNum, MaxClients = s.MaxClients, GameType = s.Gametype, PlayerHistory = s.ClientHistory.ToArray(), Players = s.GetClientsAsList() .Select(p => new PlayerInfo() { Name = p.Name, ClientId = p.ClientId, Level = p.Level.ToLocalizedLevelName(), LevelInt = (int)p.Level }).ToList(), ChatHistory = s.ChatHistory.ToList(), Online = !s.Throttled, IPAddress = $"{(IPAddress.Parse(s.IP).IsInternal() ? Program.Manager.ExternalIPAddress : s.IP)}:{s.Port}", ConnectProtocolUrl = s.EventParser.URLProtocolFormat.FormatExt(IPAddress.Parse(s.IP).IsInternal() ? Program.Manager.ExternalIPAddress : s.IP, s.Port) }).ToList(); return(View("_List", serverInfo)); }
public async Task EditGet_WhenIdIsNotNullAndGameNotFound_ShouldReturnNotFound() { // Arrange var gamesIndexViewModel = A.Fake <IGamesIndexViewModel>(); var gamesDetailsViewModel = A.Fake <IGamesDetailsViewModel>(); var gameService = A.Fake <IGameService>(); var gameRepository = A.Fake <IGameRepository>(); int? id = 1; Game?game = null; A.CallTo(() => gameRepository.GetGameAsync(id.Value)).Returns(game); var teamRepository = A.Fake <ITeamRepository>(); var seasonRepository = A.Fake <ISeasonRepository>(); var sharedRepository = A.Fake <ISharedRepository>(); var testController = new GamesController(gamesIndexViewModel, gamesDetailsViewModel, gameService, gameRepository, teamRepository, seasonRepository, sharedRepository); // Act var result = await testController.Edit(id); // Assert result.ShouldBeOfType <NotFoundResult>(); }
private static string LoadGame() { Game? game = null; GameState?gameState = null; while (game == null) { Console.Clear(); var saves = GameSaves.GetPlayableSaves(); Console.WriteLine($"Available saves: {string.Join(", ", saves)}"); var filename = InputHandler.GetUserStringInput("Choose the game to load " + $"(D - default name ({GameSaves.DefaultName}), X - exit):", 1, 30, "Enter a valid name!", true); if (filename == null) { return(""); } if (filename.ToLower() == "d") { filename = null; } gameState = GameSaves.LoadSave(filename); game = gameState != null?JsonConvert.DeserializeObject <Game>(gameState.Data) : null; } _saveGame = game; return(gameState !.Opponent == 0 ? PlayGameTwoPlayers() : PlayGameComputer()); }
public async Task <ActionResult <Game> > Get(string id) { UserModel currentUserModel = await userManager.GetUserAsync(HttpContext.User); if (currentUserModel.UserId == null) { return(StatusCode( StatusCodes.Status401Unauthorized, new Response { Status = "Unauthorized", Message = "userId is null" } )); } if (currentUserModel.Sessions.All(s => s.Id != id)) { return(Status403Forbidden()); } Game?game = await gameService.Get(id); if (game == null) { return(NotFound()); } return(game); }
public void SendUpdateStatus(long?idleSince, Game?game) => QueueMessage(new UpdateStatusCommand { IdleSince = idleSince, Game = game != null ? new APIGame { Name = game.Value.Name, Type = game.Value.Type, Url = game.Value.Url } : null });
public void GetAGameWithNonExistingId_() { //Arrange var okResult = _controller.Details(5); Game?expected = null; //Act Assert.Equal(expected, okResult); }
public void OnGet(int?gameId, string?error) { if (gameId != null) { Game = _context.Games.Single(x => x.Id == gameId); } isError = error == "on"; }
public async Task <Dto.Game?> UpdateAsync(int id, Dto.GameInput input) { Game entity = _mapper.Map <Dto.GameInput, Game>(input); Game?result = await _gameRepository.UpdateAsync(id, entity); return(result is null ? null :_mapper.Map <Game, Dto.Game>(result)); }
public async Task <IActionResult> AddGame(int id, [FromBody] PlayerInfo playerInfo) { Game?game = await _gameService.AddNew(id, playerInfo); if (game is null) { return(NotFound()); } return(Ok(game)); }
public async Task DeleteAsync(int id) { Game?game = await _context.Games.FindAsync(id); if (game is not null) { _context.Games.Remove(game); await _context.SaveChangesAsync(); } }
public async Task <IActionResult> AddGame(int id) { Game?game = await _gameService.AddNew(id); if (game is null) { return(NotFound()); } return(Ok(game)); }
public void Run() { if (gameContext is null) { throw new InvalidOperationException(); } game = new Game(gameContext); game.Run(); }
public void SendUpdateStatus(long?idleSince, Game?game, bool?afk, UserStatus status) => QueueMessage(new UpdateStatusCommand { IdleSince = idleSince, Game = game != null ? new APIGame { Name = game.Value.Name, Type = game.Value.Type, Url = game.Value.Url } : null, Afk = afk, Status = status.Value });
public IChallengeFaker CreateChallengeFaker(int?seed, Game?game = null, ChallengeState?state = null) { var faker = new ChallengeFaker(game, state); if (seed.HasValue) { faker.UseSeed(seed.Value); } return(faker); }
public override void AddOrUpdate_Add_Increases_Collection_Count_Before_Save() { Game?game = RandomLocalGame; int cntGame = game.Races.Count; Race race = GenerateRace(game); _context.AddOrUpdate(race); Assert.IsNotNull(game); Assert.AreEqual(cntGame + 1, game.Races.Count); }
private async Task RespondToUser(Game?game) { if (game is null) { await ReplyAsync("Failed to get a replay by that ID"); return; } await ReplyAsync(() => IrcResponse(game), () => DiscordResponse(game)); }
public override void AddOrUpdate_Add_Duplicate_Keeps_Collection_Count_After_Save() { Race race = RandomLocalRace; int cntGame = race.Game.Races.Count; _context.AddOrUpdate(race); SaveChanges(); Game?game = _context.GetGame(race.Game.Abbreviation); Assert.IsNotNull(game); Assert.AreEqual(cntGame, game.Races.Count); }
public ActionParams( ActionRequest request, string playerId, Game?game, Models.SessionModel.Session?session, Board?board ) : base(request, playerId) { Game = game; Board = board; Session = session; }
public override void AddOrUpdate_Add_Increases_Collection_Count_Before_Save() { Game? game = RandomLocalGame; Channel?channel = RandomLocalChannel; int cntGame = game.Trackers.Count; int cntChannel = channel.Trackers.Count; Tracker tracker = new Tracker(channel, game); _context.AddOrUpdate(tracker); Assert.AreEqual(cntGame + 1, game.Trackers.Count); Assert.AreEqual(cntChannel + 1, channel.Trackers.Count); }
public bool Load(string path) { try { var json = File.ReadAllText(path); Data = JsonConvert.DeserializeObject <Game>(json); return(true); } catch (Exception ex) { throw new Exception(ex.Message); } }
public void Timestamp_CreatedAt() { Game?game = GenerateGame(); _context.Add(game); SaveChanges(); game = _context.GetGame(game.Abbreviation); Assert.IsNotNull(game); Assert.IsNotNull(game?.CreatedAt); Assert.AreNotEqual(DateTime.MinValue, game?.CreatedAt); Assert.Greater(DateTime.Now, game?.CreatedAt); }