Ejemplo n.º 1
0
        public async Task EditGameAsync(Guid UserId, GameDto new_game, IEnumerable <PropertyDto> new_genres, List <IFormFile> Medias, List <IFormFile> CoverArt, string rootdir)
        {
            var game = await dbContext.Games
                       .Include(x => x.Medias)
                       .FirstOrDefaultAsync(x => x.Id == new_game.Id);

            game.GameName = new_game.GameName;
            game.Price    = new_game.Price;
            game.Release  = DateTime.Parse(new_game.Release + " 0:00");

            var genres_to_delete = await dbContext.GameProperties.Where(x => x.GameId == new_game.Id && x.Property.type == 0).ToListAsync();

            dbContext.GameProperties.RemoveRange(genres_to_delete);

            foreach (var g in new_genres)
            {
                System.Diagnostics.Debug.WriteLine("A genre:" + g.name);
                dbContext.GameProperties.Add(new GameProperty
                {
                    GameId     = game.Id,
                    PropertyId = g.Id
                }
                                             );
            }

            await SaveMediasAsync(game, Medias, CoverArt, rootdir);

            await dbContext.SaveChangesAsync();
        }
Ejemplo n.º 2
0
        public GameDto CreateNewGame(GameDto gameDto)
        {
            var game = Mapper.Map <Game>(gameDto);

            foreach (var genreInDto in gameDto.Genres)
            {
                var genreResult = _unitOfWork.GenreRepository
                                  .GetByPropertyValue(g => g.Name == genreInDto)
                                  .FirstOrDefault();
                if (genreResult != null)
                {
                    game.Genres.Add(genreResult);
                }
            }
            foreach (var platformTypeInDto in gameDto.PlatformTypes)
            {
                var platformTypeResult = _unitOfWork.PlatformTypeRepository
                                         .GetByPropertyValue(g => g.Type == platformTypeInDto)
                                         .FirstOrDefault();
                if (platformTypeResult != null)
                {
                    game.PlatformTypes.Add(platformTypeResult);
                }
            }

            _unitOfWork.GameRepository.Insert(game);
            _unitOfWork.Commit();
            gameDto = Mapper.Map <GameDto>(gameDto);
            return(gameDto);
        }
Ejemplo n.º 3
0
        public void test1()
        {
            GameDto g1 = new GameDto("012345678", "Player1");
            GameDto g2 = new GameDto("012345678", "Player1");

            Assert.AreEqual <GameDto>(g1, g2);
        }
Ejemplo n.º 4
0
        private PlayerDto RunGame(GameDto game)
        {
            if (game.Players.Count != NUMBER_PLAYERS)
            {
                throw new Exception(ERROR_MESSAGE_NUMBER_PLAYERS_INCORRECT);
            }

            var player1 = game.Players[0];
            var player2 = game.Players[1];

            if (player1.Move.EqualsIgnoreCase(player2.Move))
            {
                return(player1);
            }

            switch (char.ToUpperInvariant(player1.Move))
            {
            case GameConstants.Rock:
                return(player2.Move.EqualsIgnoreCase(GameConstants.Scissor) ? player1 : player2);

            case GameConstants.Paper:
                return(player2.Move.EqualsIgnoreCase(GameConstants.Rock) ? player1 : player2);

            case GameConstants.Scissor:
                return(player2.Move.EqualsIgnoreCase(GameConstants.Paper) ? player1 : player2);

            default:
                throw new Exception(message: ERROR_MESSAGE_STRATEGY_ERROR);
            }
        }
Ejemplo n.º 5
0
        private async Task OnNextStep(
            string roomId,
            int currentRoundNumber,
            string currentHiddenWord,
            GameDto gameDto,
            GameEntity gameEntity)
        {
            if (currentRoundNumber < gameEntity.RoundNumber)
            {
                await SendNotificationAfterEndOfRound(roomId, currentHiddenWord, currentRoundNumber + 1);
            }

            if (gameEntity.GameState == GameState.Finished)
            {
                var pointsWinner = gameEntity.Players.Max(p => p.Score);
                var winner       = gameEntity.Players.First(p => p.Score == pointsWinner);
                userRepository.IncreaseWinsCount(winner);
                foreach (var player in gameEntity.Players)
                {
                    userRepository.UpdateStatistics(player);
                }

                gameEntity.Start();
                gameDto = mapper.Map <GameDto>(gameEntity);
                roomRepository.UpdateGame(int.Parse(roomId), gameDto);
                var victoryNotification = MessageFactory.CreateVictoryNotification(winner.Name);
                await Clients.Group(roomId).SendAsync(RoomHubEvents.GameOver, victoryNotification);
            }
            else
            {
                await Clients.Group(roomId).SendAsync(RoomHubEvents.RoundInfo,
                                                      gameEntity.ExplainingPlayerName, gameEntity.GetSecondsLeft());
            }
        }
Ejemplo n.º 6
0
        public void Given_a_game_When_CreateGame_is_called_Then_creation_is_done_with_success()
        {
            //Arrange
            var gameDto = new GameDto()
            {
                GameInformation = new GameInformationDto()
                {
                    Id         = Guid.NewGuid().ToString(),
                    NomPlayer1 = "Player1",
                    NomPlayer2 = "Player2"
                },
                Grid = new TokenDto[, ] {
                    { TokenDto.X, TokenDto.X, TokenDto.O },
                    { TokenDto._, TokenDto.O, TokenDto._ },
                    { TokenDto.X, TokenDto._, TokenDto._ }
                },
                MoveCounter = 5
            };

            //Act
            var response = _client.Post <GameDto>(UrlGame.CreateGameWithGrid, gameDto);


            // Assert
            Assert.True(response.Success, $"Erreur retournée par l'API : {response.Error}");
            Assert.Equal <GameDto>(gameDto, response.Value);
        }
Ejemplo n.º 7
0
        public async Task PatchGameAsync(string vendorUserName, int id, GameDto game)
        {
            var gameInDB = _context.Games.Include("Vendor").Single(game => game.ID == id);

            if (gameInDB.Vendor.Username != vendorUserName)
            {
                throw new WrongVendorException();
            }
            gameInDB.Name  = game.Name;
            gameInDB.Price = game.Price;
            _context.Entry(gameInDB).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(id))
                {
                    throw new ItemNotFoundException();
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 8
0
 private void GameOver(object sender, GameDto gameDto)
 {
     Context.CurrentGame.Sharks    = new List <SharkDto>();
     Context.CurrentGame.Message   = gameDto.Message;
     Context.CurrentGame.IsStarted = gameDto.IsStarted;
     InvokeAsync(StateHasChanged);
 }
Ejemplo n.º 9
0
 public virtual void Create(GameDto item)
 {
     try
     {
         if (item == null)
         {
             throw new ValidationException("Invalid id", "id");
         }
         if (!this.IsUniqueKey(item.Key))
         {
             throw new ValidationException("Key is not unique", "Key");
         }
         this.unitOfWork.Games.Create(Mapper.Map<Game>(item));
         this.unitOfWork.Save();
     }
     catch (ValidationException exception)
     {
         this.logger.Debug(exception.Message);
         throw;
     }
     catch (Exception exception)
     {
         this.logger.Error(exception.Message);
         this.logger.Trace(exception.StackTrace);
         throw;
     }
 }
Ejemplo n.º 10
0
        public IHttpActionResult CreateGame(GameDto gameDto)
        {
            dynamic Response = new ExpandoObject();

            try
            {
                if (!ModelState.IsValid)
                {
                    Response.Status  = ConstantValues.ResponseStatus.ERROR;
                    Response.Message = ConstantValues.ErrorMessage.BAD_REQUEST;
                    return(Content(HttpStatusCode.BadRequest, Response));
                }

                var game = Mapper.Map <GameDto, Game>(gameDto);
                _context.Games.Add(game);
                _context.SaveChanges();

                gameDto.id      = game.id;
                Response.Status = ConstantValues.ResponseStatus.OK;
                Response.Game   = gameDto;

                return(Created(new Uri(Request.RequestUri + "/" + game.id), Response));
            }
            catch (Exception e)
            {
                Response.Status  = ConstantValues.ResponseStatus.ERROR;
                Response.Message = ConstantValues.ErrorMessage.INTERNAL_SERVER_ERROR;
                return(Content(HttpStatusCode.InternalServerError, Response));
            }
        }
Ejemplo n.º 11
0
        public Result <int> CreateGame(List <ShipDto> ships, string connectionId)
        {
            var enemyShips = new ShipGenerator().GenerateShips();
            var model      = new GameDto
            {
                ConnectionId = connectionId,
                UserArea     = new AreaDto
                {
                    Ships = ships
                },
                ComputerArea = new AreaDto
                {
                    Ships = enemyShips
                }
            };

            try
            {
                var dbModel = _mapper.Map <GameDb>(model);

                _context.Games.Add(dbModel);
                _context.SaveChanges();

                return(Result.Success(dbModel.Id));
            }
            catch (DbUpdateException ex)
            {
                return(Result.Failure <int>(ex.Message));
            }
        }
Ejemplo n.º 12
0
        public void Render(GameDto gameDto)
        {
            System.Console.WriteLine("Grid :");
            System.Console.WriteLine();
            System.Console.WriteLine(String.Format(" {0} {1} {2}\n {3} {4} {5}\n {6} {7} {8}\n\n",
                                                   gameDto.Grid[0],
                                                   gameDto.Grid[1],
                                                   gameDto.Grid[2],
                                                   gameDto.Grid[3],
                                                   gameDto.Grid[4],
                                                   gameDto.Grid[5],
                                                   gameDto.Grid[6],
                                                   gameDto.Grid[7],
                                                   gameDto.Grid[8]));
            System.Console.WriteLine(String.Format("{0}, this your turn", gameDto.CurrentPlayerCode));
            System.Console.Write("Select and press enter :");
            string text = Console.ReadLine();
            int    userSelection;

            if (Int32.TryParse(text, out userSelection))
            {
                uiCommandChannel.SubmitUICommand <PlayCommand>(
                    new PlayCommand(gameDto.CurrentPlayerCode, userSelection % 3, userSelection / 3));
            }
        }
Ejemplo n.º 13
0
 private void GameChanged(object sender, GameDto game)
 {
     Context.CurrentGame.IsStarted = game.IsStarted;
     Context.CurrentGame.Message   = game.Message;
     Context.CurrentGame.IsEasy    = game.IsEasy;
     Context.CurrentGame.Score     = game.Score;
 }
Ejemplo n.º 14
0
        public ActionResult AddGameToBasket(string gameKey)
        {
            GameDto game = _gameService.GetGameByKey(gameKey);

            if (game.Deleted)
            {
                throw new GameDeletedException();
            }

            var basket = Session[Basket] as List <Purchase>;

            if (basket == null)
            {
                basket          = new List <Purchase>();
                Session[Basket] = basket;
            }

            const short gamesQuantity = 1;

            if (basket.Count(p => p.GameId == game.Id) == 0)
            {
                var purchase = new Purchase(game.Id, game.LanguagesNames["ru"], game.Price, gamesQuantity);
                basket.Add(purchase);
            }
            else
            {
                basket.Single(p => p.GameId == game.Id).Quantity += gamesQuantity;
            }

            CreateOrUpdateCurrentOrder(basket);

            return(RedirectToAction("GetCurrentOrderDetails"));
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Details([FromRoute] Guid id)
        {
            GameDto gameDto = await gameService.GetGameByIdAsync(id);

            bool isOwned;
            bool isMyDevelopment;

            try
            {
                var UserId = Guid.Parse(User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value);
                isOwned         = gameService.IsOwnedGame(UserId, id);
                isMyDevelopment = gameDto.UserId == UserId;
            }
            catch (Exception e)
            {
                isOwned         = false;
                isMyDevelopment = false;
            }

            return(Ok(new
            {
                game = gameDto,
                isOwned = isOwned,
                isMyDevelopment = isMyDevelopment
            }));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> GetGame([FromRoute] int gameId)
        {
            Game   game       = repo.GetGame(gameId);
            WAUser gameAuthor = await repo.GetGameAuthor(game);

            var genre   = repo.GetGenreById(game.GenreId);
            var gameDto = new GameDto()
            {
                Descr  = game.Descr,
                Name   = game.Name,
                Id     = game.Id,
                Genre  = genre.Descr,
                Author = new UserDto()
                {
                    Username = gameAuthor.UserName
                }
            };

            if (gameDto != null)
            {
                return(StatusCode(200, responses.GameFoundResponse(gameDto)));
            }
            else
            {
                return(StatusCode(500, ErrorResponse.ServerError));
            }
        }
Ejemplo n.º 17
0
        public ActionResult CreateGame(GameDto gameDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            //var movie = new Movie
            //{
            //    Name = movieDto.Name,
            //    GenreId = movieDto.GenreId,
            //    DateAdded = DateTime.Now,
            //    ReleaseDate = movieDto.ReleaseDate,
            //    NumberInStock = movieDto.NumberInStock

            //};
            var game = new Game();

            game = _mapper.Map(gameDto, game);

            gameDto.Id = game.Id;

            _context.Games.Add(game);
            _context.SaveChanges();

            return(Ok(gameDto));
        }
Ejemplo n.º 18
0
        private void UpdateWindow(GameDto game)
        {
            var bombs = game.Board.Bombs;
            var flags = game.Board.Fields.Where(x => x.State == FieldState.Flag).Count();

            BombsTextBlock.Text  = (bombs - flags).ToString();
            RestartButton.Source = _assets.GameStates[game.GameState];

            if (Game.GameState == GameState.New && game.GameState == GameState.InProgress)
            {
                _timer.Start();
            }

            Game.GameState = game.GameState;

            if (Game.GameState == GameState.Won || Game.GameState == GameState.Lost)
            {
                _timer.Stop();
            }

            if (Game.GameState == GameState.Won)
            {
                MessageBox.Show($"Game won in {Math.Round(game.RoundTime.TotalSeconds, 3)} s.");
            }
        }
Ejemplo n.º 19
0
 public IActionResult UpdateGame([FromRoute] int gameId, [FromBody] GameDto gameDto)
 {
     (IActionResult result, bool isOwner) = EnsureAuthorOwnsGame(gameDto, gameId);
     if (!isOwner)
     {
         return(result);
     }
     try
     {
         if (gameId == 0)
         {
             return(StatusCode(400, ErrorResponse.CustomErrorCode(400, "You're not updating a game.")));
         }
         repo.UpdateGame(gameDto, gameId);
         var updatedGameDto = new GameDto
         {
             Id     = gameId,
             Author = gameDto.Author,
             Descr  = gameDto.Descr,
             Genre  = gameDto.Genre,
             Name   = gameDto.Name
         };
         var successResponse = responses.UpdateResponse(updatedGameDto);
         return(StatusCode(200, successResponse));
     }
     catch (Exception e)
     {
         return(StatusCode(500, ErrorResponse.ServerError));
     }
 }
Ejemplo n.º 20
0
        private GameDto CreateLinksForGame(GameDto game)
        {
            game.Links.Add(new LinkDto(_urlHelper.Link("GetGameForReview",
                                                       new { id = game.Id }),
                                       "self",
                                       "GET"));

            game.Links.Add(
                new LinkDto(_urlHelper.Link("DeleteGame",
                                            new { id = game.Id }),
                            "delete_game",
                            "DELETE"));

            game.Links.Add(
                new LinkDto(_urlHelper.Link("UpdateGame",
                                            new { id = game.Id }),
                            "update_game",
                            "PUT"));

            game.Links.Add(
                new LinkDto(_urlHelper.Link("PartiallyUpdateGame",
                                            new { id = game.Id }),
                            "partially_update_game",
                            "PATCH"));

            return(game);
        }
Ejemplo n.º 21
0
        public GameDto GenerateNewTurn(GameDto Game)
        {
            var tempPlayers = new List <PlayerDto>();

            foreach (var Turn in Game.Turn)
            {
                foreach (var Player in Turn.Players)
                {
                    tempPlayers.Add(Player);
                }
            }

            Game.Turn.Clear();

            for (int i = 0; i < tempPlayers.ToArray().Length; i++)
            {
                if (i % 2 == 0)
                {
                    var List = new List <PlayerDto>();
                    List.Add(tempPlayers[i]);
                    List.Add(tempPlayers[i + 1]);
                    Game.Turn.Add(GameRepository.AddTurn(List));
                }
            }
            return(Game);
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> GetGame([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var game = await _repo.GetByIdAsync <Game>(id);

                if (!game.Success)
                {
                    return(NotFound());
                }

                var gameDto = new GameDto
                {
                    Id   = game.Data.Id,
                    Name = game.Data.Name
                };

                return(Ok(gameDto));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Ejemplo n.º 23
0
        public JsonResult CreateGameWithGrid([FromBody] GameDto vm)
        {
            // Map to the Entity
            var game   = Mapper.Map <Game>(vm);
            var result = _repository.GetGameById(game.GameInfo.Id);

            if (result.Success)
            {
                _logger.LogError($"La partie ne peut pas être créée car son identifiant '{game.GameInfo.Id}' est déjà utilisé");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Une erreur s'est produite lors de la sauvegarde du nouveau jeu"));
            }

            //Create
            var createResult = _repository.AddGame(game)
                               .OnSuccess(() => _repository.SaveAll());

            if (createResult.Failure)
            {
                _logger.LogError($"Échec de la sauvegarde du nouveau jeu : {createResult.Error}");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json($"Échec de la sauvegarde du nouveau jeu : {createResult.Error}"));
            }

            Response.StatusCode = (int)HttpStatusCode.OK;
            return(Json(Mapper.Map <GameDto>(game)));
        }
Ejemplo n.º 24
0
        //pobranie pojedynczej gry
        public async Task <ResultDto <GameDto> > GetGame(int id)
        {
            var result = new ResultDto <GameDto>()
            {
                Error = null
            };

            //probuje uzyskac wskazana gre
            var game = await _repo.GetSingleEntity(x => x.Id == id);

            if (game == null)
            {
                result.Error = "Nie odnaleziono gry";
                return(result);
            }

            //wyciagniecie listy poradnikow do podanej gry w celu ich podliczenia
            var guides = await _guideRepo.GetAllBy(x => x.GameId == id);

            //tworze obiekt z gra i zwracam go
            var gameToSend = new GameDto()
            {
                Id          = game.Id,
                Description = game.Description,
                Name        = game.Name,
                Image       = game.Image,
                Rating      = game.Rating,
                GuidesCount = guides.Count
            };

            result.SuccessResult = gameToSend;

            return(result);
        }
Ejemplo n.º 25
0
        public async Task AddAsync_AddsGame_WhenGameAdded()
        {
            //ARRANGE
            var specificGameName = Guid.NewGuid().ToString();
            var count            = await fixture.Context.Games.CountAsync();

            var imageCount = await fixture.Context.Images.CountAsync();

            var gameDto = new GameDto
            {
                Name     = specificGameName,
                GameLogo = new ImageDto
                {
                    File = new byte[0]
                }
            };

            //ACT
            var result = await service.AddAsync(gameDto);

            //ASSERT
            var game = await fixture.Context.Games.SingleOrDefaultAsync(g => g.Name == specificGameName);

            Assert.Equal(count + 1, await fixture.Context.Games.CountAsync());
            Assert.Equal(imageCount + 1, await fixture.Context.Images.CountAsync());
            Assert.NotNull(game);
            Assert.NotNull(game.GameLogo);
            Assert.Equal(game.Id, result);
        }
Ejemplo n.º 26
0
        public ConfigureGameForm(GameDto game, CarouselClient client)
        {
            InitializeComponent();

            this._CarouselClient = client;
            this._Game           = game;
            this._Game.Load();
            this.ExePathLabel.Text            = this._Game.ExePath;
            _BindingSource                    = new BindingSource();
            _BindingSource.DataSource         = this._Game.LocalFiles;
            this.GameFileDataTable.DataSource = _BindingSource;

            if (this.GameFileDataTable.RowCount >= 1)
            {
                for (int i = GameFileDataTable.ColumnCount - 1; i >= 0; i--)
                {
                    if (i == GameFileDataTable.ColumnCount - 1)
                    {
                        GameFileDataTable.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    }
                    else
                    {
                        GameFileDataTable.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public async Task <int> AddAsync(GameDto game)
        {
            var newGame = new Game
            {
                Name             = game.Name,
                Status           = game.Status,
                HasSite          = game.HasSite,
                GameKey          = game.GameKey,
                LinkEntryTypes   = game.LinkEntryTypes,
                StringEntryTypes = game.StringEntryTypes,
                TagEntryTypes    = game.TagEntryTypes,
                ValueEntryTypes  = game.ValueEntryTypes
            };

            if (game.GameLogo != null && game.GameLogo.File != null)
            {
                newGame.GameLogo = new Image {
                    File = game.GameLogo.File
                }
            }
            ;

            Context.Games.Add(newGame);

            await Context.SaveChangesAsync();

            return(newGame.Id);
        }
Ejemplo n.º 28
0
        public ActionResult UpdateGame(string gameKey)
        {
            GameDto game = _gameService.GetGameByKey(gameKey);

            if (game.Deleted)
            {
                throw new GameDeletedException();
            }

            IEnumerable <PlatformTypeDto> platformTypes = _platformTypeService.GetAllPlatformTypes();
            var platformTypesMultiselect = new MultiSelectList(platformTypes, "Id", "Type");

            IEnumerable <PublisherDto> publishers = _publisherService.GetAllPublishers();
            var publishersMultiselect             = new MultiSelectList(publishers, "Id", "CompanyName");

            IEnumerable <GenreDto> genres = _genreService.GetAllGenres();
            var genresMultiselect         = new MultiSelectList(genres, "Id", "Name");

            var model = game.ToUpdateViewModel();

            model.AllPlatformTypes = platformTypesMultiselect;
            model.AllGenres        = genresMultiselect;
            model.AllPublishers    = publishersMultiselect;

            return(View(model));
        }
        public async Task EditPost_Returns404_WhenCharacterDoesntExist()
        {
            //Arrange
            var model = new CharacterEditViewModel
            {
                Id   = 0,
                Name = "Test"
            };

            var game = new GameDto()
            {
                Name = "test"
            };

            mockGameService.Setup(s => s.GetByIdAsync(It.IsAny <int>())).ReturnsAsync(game);
            mockCharacterService.Setup(s => s.GetByIdAsync(It.IsAny <int>())).ReturnsAsync((CharacterDto)null);

            //Act
            var result = await controller.Edit(model);

            //Assert
            var statusCodeResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal(404, statusCodeResult.StatusCode);
        }
Ejemplo n.º 30
0
        public HttpStatusCodeResult ChangeGameQuantity(ChangeGameQuantityViewModel model)
        {
            var basket = Session[Basket] as List <Purchase>;

            if (basket == null)
            {
                basket = new List <Purchase>();
                GameDto game = _gameService.Get(model.Id);
                basket.Add(new Purchase(game.Id, game.LanguagesNames["ru"], game.Price, model.Quantity));

                Session[Basket] = basket;
            }
            else
            {
                Purchase purchase = basket.Single(p => p.GameId == model.Id);
                if (model.Quantity == 0)
                {
                    basket.Remove(purchase);
                }
                else
                {
                    purchase.Quantity = model.Quantity;
                }
            }

            CreateOrUpdateCurrentOrder(basket);

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
Ejemplo n.º 31
0
        public async Task <IActionResult> NewGame()
        {
            // todo: match making queue/service
            var oppenentId = 2;

            User whiteUser = await _userRepo.GetUser(this.GetCurrentUserId());

            User blackUser = await _userRepo.GetUser(oppenentId);

            Game newGame = new Game(whiteUser, blackUser);

            newGame.StatusCode = GameStatus.Inprogress;
            newGame.Initialize();
            _gameRepo.Add(newGame);
            foreach (Piece piece in newGame.Pieces)
            {
                _gameRepo.Add(piece);
            }
            var result = await _gameRepo.SaveAll();

            GameDto gameDto = _mapper.Map <GameDto>(newGame);

            return(Created("/game/" + gameDto.Id + "/play", gameDto));
            //  return CreatedAtAction("GetGame", gameDto);
            // return CreatedAtRoute( );
            //  Ok(gameDto);
        }
Ejemplo n.º 32
0
 public void Add_Game_With_Existing_Key()
 {
     //Arrange
     var game = new GameDto { Key = "LoL", Name = "New", Description = "Awesome" };
     //Act
     this.gameAppService.Create(game);
 }
Ejemplo n.º 33
0
 public void Add_Game_With_Correct_Argument()
 {
     //Arrenge
     var game = new GameDto
                    {
                        Key = "StarCraft2",
                        Name = "StarCraft2",
                        Description = "Awesome",
                        PlatformTypes = new List<PlatformTypeDto>() { new PlatformTypeDto() { Id = 1 } },
                        Genres = new List<GenreDto> { new GenreDto() { Id = 2 } }
                    };
     //Act
     this.gameAppService.Create(game);
     //Assert
     this.gameRepositoryMock.Verify(x => x.Create(It.IsAny<Game>()), Times.Once);
     this.unitOfWorkMock.Verify(x => x.Save(), Times.Once);
 }
Ejemplo n.º 34
0
 public void Add_Game_With_Wrong_Genre()
 {
     //Arrenge
     var game = new GameDto
                    {
                        Id = 1,
                        Key = "New",
                        Name = "New",
                        Description = "Awesome",
                        Genres = new List<GenreDto> { new GenreDto() { Id = 4 } }
                    };
     //Act
     this.gameAppService.Create(game);
 }
Ejemplo n.º 35
0
 public virtual void Update(GameDto item)
 {
     try
     {
         if (item == null)
         {
             throw new ValidationException("Item can not be null", "Key");
         }
         this.unitOfWork.Games.Update(Mapper.Map<Game>(item));
         this.unitOfWork.Save();
     }
     catch (ValidationException exception)
     {
         this.logger.Debug(exception.Message);
         throw;
     }
     catch (Exception exception)
     {
         this.logger.Error(exception.Message);
         this.logger.Trace(exception.StackTrace);
         throw;
     }
 }
Ejemplo n.º 36
0
 public void Edit_Game_With_Existing_Key()
 {
     //Arrange
     var game = new GameDto { Id = 1, Key = "LoL", Name = "StarCraft", Description = "Awesome" };
     //Act
     this.gameAppService.Update(game);
 }
Ejemplo n.º 37
0
 public void Edit_Game_With_Wrong_PlatforType()
 {
     //Arrenge
     var game = new GameDto
                    {
                        Id = 1,
                        Key = "StarCraft",
                        Name = "StarCraft",
                        Description = "Awesome",
                        PlatformTypes = new List<PlatformTypeDto>() { new PlatformTypeDto() {Id = 6, Type = "Wrong"}}
                    };
     //Act
     this.gameAppService.Update(game);
 }
Ejemplo n.º 38
0
 public void Add_Game_With_Wrong_PlatformType()
 {
     //Arrenge
     var game = new GameDto
                    {
                        Key = "New",
                        Name = "New",
                        Description = "Awesome",
                        PlatformTypes = new List<PlatformTypeDto>() { new PlatformTypeDto() { Id = 4 } }
                    };
     //Act
     this.gameAppService.Create(game);
 }
Ejemplo n.º 39
0
 public void Edit_Game_With_Wrong_Genre()
 {
     //Arrenge
     var game = new GameDto
                    {
                        Id = 1,
                        Key = "StarCraft",
                        Name = "StarCraft",
                        Description = "Awesome",
                        Genres = new List<GenreDto> { new GenreDto() {Id = -1, Name = "Wrong"} }
                    };
     //Act
     this.gameAppService.Update(game);
 }