public ActionResult CreateGame(CreateGame createGame)
        {
            var cmd    = new CreateGameCommand(repo);
            var result = cmd.Execute(createGame);

            return(Json(result));
        }
Example #2
0
        public async Task Handle_GivenValidRequest_ShouldCreateValidEntity()
        {
            // Arrange
            var cloudinaryHelperMock = new Mock <ICloudinaryHelper>();
            var cloudinaryMock       = new Mock <Cloudinary>();
            var imagePlaceholderUrl  = "https://steamcdn-a.akamaihd.net/steam/apps/440/header.jpg";

            cloudinaryHelperMock
            .Setup(x => x.UploadImage(It.IsAny <IFormFile>(), It.IsAny <string>(), It.IsAny <Transformation>()))
            .ReturnsAsync(imagePlaceholderUrl);

            var sut = new CreateGameCommandHandler(this.deletableEntityRepository, cloudinaryHelperMock.Object, this.mediatorMock.Object);

            var command = new CreateGameCommand()
            {
                Name        = "Team Fortress 2",
                Description = @"One of the most popular online action games of all time, Team Fortress 2 delivers constant free updates—new game modes, maps, equipment and, most importantly, hats. Nine distinct classes provide a broad range of tactical abilities and personalities, and lend themselves to a variety of player skills. New to TF ? Don’t sweat it! No matter what your style and experience, we’ve got a character for you.Detailed training and offline practice modes will help you hone your skills before jumping into one of TF2’s many game modes, including Capture the Flag, Control Point, Payload, Arena, King of the Hill and more. Make a character your own! There are hundreds of weapons, hats and more to collect, craft, buy and trade.Tweak your favorite class to suit your gameplay style and personal taste.You don’t need to pay to win—virtually all of the items in the Mann Co.Store can also be found in-game.",
                GameImage   = new FormFile(It.IsAny <Stream>(), It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>(), It.IsAny <string>())
            };

            // Act
            await sut.Handle(command, CancellationToken.None);

            var game = this.dbContext.Games.SingleOrDefault(g => g.Name == command.Name);

            // Assert
            this.mediatorMock.Verify(x => x.Publish(It.IsAny <GameCreatedNotification>(), It.IsAny <CancellationToken>()));
            game.ShouldNotBeNull();
            game.Name.ShouldBe(command.Name);
            game.GameImageUrl.ShouldBe(imagePlaceholderUrl);
            game.Description.ShouldBe(command.Description);
        }
Example #3
0
        public async void ShouldCreateGame()
        {
            //arrange
            BoardContext context = new ContextBuilder().BuildClean();

            string expectedName      = "Sabotaz";
            int    expectedAge       = 5;
            int    expectedMaxAmount = 6;
            int    expectedMinAmount = 1;


            //act
            var command = new CreateGameCommand();

            command.Name = expectedName;
            command.MinimalPlayersAmount = expectedMinAmount;
            command.MinimalPlayersAge    = expectedAge;
            command.MaximalPlayersAmount = expectedMaxAmount;

            var handler = new CreateGameCommand.Handler(context);
            var result  = await handler.Handle(command, default);

            //assert
            var createdGame = context.Games
                              .Where(x => x.Id == result)
                              .FirstOrDefault();

            Assert.Equal(expectedAge, createdGame.MinimalPlayersAge);
            Assert.Equal(expectedMaxAmount, createdGame.MaximalPlayersAmount);
            Assert.Equal(expectedMinAmount, createdGame.MinimalPlayersAmount);
            Assert.Equal(expectedName, createdGame.Name);
        }
Example #4
0
        public void Execute_CreatesGameWithPlayers()
        {
            var command = new CreateGameCommand(repository);
            var result  = command.Execute(new CreateGame(new[] { "Player 1", "Player 2" }));
            var game    = repository.Items[0];

            Assert.AreEqual(result.Id, game.Id);
        }
Example #5
0
        public async Task <ActionResult <GameDetailDto> > Create([FromBody] CreateGameCommand command)
        {
            var id = await Mediator.Send(command);

            return(Ok(await Mediator.Send(new GetGameDetailQuery {
                Id = id
            })));
        }
Example #6
0
        public async Task Handle_GivenNullRequest_ShouldThrowArgumentNullException()
        {
            // Arrange
            var sut = new CreateGameCommandHandler(It.IsAny <IDeletableEntityRepository <Game> >(), It.IsAny <ICloudinaryHelper>(), this.mediatorMock.Object);
            CreateGameCommand command = null;

            // Act & Assert
            await Should.ThrowAsync <ArgumentNullException>(sut.Handle(command, It.IsAny <CancellationToken>()));
        }
Example #7
0
        public void Handle(CreateGameCommand command)
        {
            var gameId = GameId.NewGameId(command.GameId);

            eventStore.Add(gameId, Domain.Game.addQuestion(SingleAnswerQuestion.create("What is my favorite color?", new[] { "Red", "Green", "Blue" })));
            eventStore.Add(gameId, Domain.Game.addQuestion(SingleAnswerQuestion.create("Which is my favorite animal?", new[] { "Dog", "Cat", "Alligator", "Snail" })));
            eventStore.Add(gameId, Domain.Game.addQuestion(SingleAnswerQuestion.create("Do I believe the cake is a lie?", new[] { "Yes", "No" })));
            eventStore.Add(gameId, Domain.Game.addQuestion(MultipleAnswerQuestion.create("What are my favorite colors?", new[] { "Red", "Green", "Blue", "Yellow" })));
        }
Example #8
0
        public async Task ExecuteAsync(GameCreatedCommand command)
        {
            _logger.LogInformation(
                $"{nameof(GameCreatedCommand)} has been triggered with parameter {command.ToJsonString()}");

            CreateGameCommand createGameCommand = _mapper.Map <CreateGameCommand>(command);

            await _mediator.Send(createGameCommand);
        }
Example #9
0
 private void cheAllCommand()
 {
     CreateGameCommand.RaiseCanExecuteChanged();
     LoadPlayersFromDocumentCommand.RaiseCanExecuteChanged();
     DeletePlayerCommnd.RaiseCanExecuteChanged();
     CleanGameSettingCommand.RaiseCanExecuteChanged();
     SaveGameSettingCommand.RaiseCanExecuteChanged();
     OutPutPlayersCommand.RaiseCanExecuteChanged();
 }
        public void DuplicateNamedGameIsCatchAndNotAllowed(string tName)
        {
            var vDocumentStore = GetEmbeddedDatabase;

            var vModel = new CreateGameModel {Name = tName};

            var vCommand = new CreateGameCommand(vDocumentStore, vModel);
            vCommand.Execute();
            Assert.AreEqual(eGameCreationStatus.DuplicateName, vCommand.Execute());
        }
Example #11
0
        public async Task <IActionResult> Create(CreateGameCommand command)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View());
            }

            await this.Mediator.Send(command);

            return(this.RedirectToAction(nameof(Index)));
        }
Example #12
0
        public ActionResult StartGame(string difficulty_name)
        {
            var create_game_command = new CreateGameCommand();

            create_game_command.player_id       = _player_identifier.get_player_identifier();
            create_game_command.game_difficulty = new GameDifficultyFactory().find_game_difficulty_by(difficulty_name);

            _bus.send(create_game_command);

            return(RedirectToAction("Index", "Game"));
        }
        public void ShouldValidateWhenCommandIsValid()
        {
            var command = new CreateGameCommand()
            {
                Name      = "FIFA 19",
                CompanyId = Guid.NewGuid(),
                UserId    = Guid.NewGuid()
            };

            Assert.True(command.Valid());
        }
Example #14
0
        public async Task <IActionResult> Create()
        {
            var command = new CreateGameCommand(UserId);

            await _commandProcessor.SendAsync(command);

            return(CreatedAtAction(
                       "GetGame",
                       new { command.Id },
                       new { command.Id, command.CreatedOn }));
        }
Example #15
0
        public async Task Handle_GivenInvalidRequest_ShouldThrowEntityAlreadyExistsException()
        {
            // Arrange
            var sut = new CreateGameCommandHandler(this.deletableEntityRepository, It.IsAny <ICloudinaryHelper>(), this.mediatorMock.Object);
            CreateGameCommand command = new CreateGameCommand {
                Name = "SampleGame1"
            };

            // Act & Assert
            await Should.ThrowAsync <EntityAlreadyExistsException>(sut.Handle(command, It.IsAny <CancellationToken>()));
        }
Example #16
0
        public async Task <ActionResult> Create([FromForm] CreateGameCommand createGameCommand)
        {
            if (ModelState.IsValid)
            {
                await Mediator.Send(createGameCommand);

                TempData["message"] =
                    $"Game \"{createGameCommand.Name}\" has been saved.";

                return(RedirectToAction(nameof(Index)));
            }

            return(View(createGameCommand));
        }
Example #17
0
        public void ShouldRegisterGameWhenCommandIsValid()
        {
            var command = new CreateGameCommand()
            {
                UserId    = Guid.NewGuid(),
                CompanyId = Guid.NewGuid(),
                Name      = "FIFA 19"
            };

            var result = _handler.Handle(command);

            Assert.NotEqual(null, result);
            Assert.True(_handler.Valid);
        }
        public async Task ShouldCreateGame()
        {
            var cmd = new CreateGameCommand("Ratchet & Clank: Rift Apart", 2015, "PC");

            await SendAsync(cmd);

            var entity = await FindAsync <IGameRepository, Game>(cmd.Id);

            entity.Should().NotBeNull();
            entity.Id.Should().Be(cmd.Id);
            entity.Name.Should().Be("Ratchet & Clank: Rift Apart");
            entity.LaunchYear.Should().Be(2015);
            entity.Platform.Should().Be("PC");
        }
        public void CreatesGameInRaven(string tName)
        {
            var vDocumentStore = GetEmbeddedDatabase;

            var vModel = new CreateGameModel {Name = tName};

            var vCommand = new CreateGameCommand(vDocumentStore, vModel);
            vCommand.Execute();

            using(var vSession = vDocumentStore.OpenSession())
            {
                Assert.IsNotNull(vSession.Load<Game>("Games/" + tName));

            }
        }
Example #20
0
        public async Task <ActionResult <GameTokenDto> > CreateGame([FromBody] CreateGameCommand command)
        {
            Game game = new Game(
                command.Name,
                command.Password,
                command.MaxPlayers.Value,
                command.AdminName,
                command.AdminBuyIn.Value,
                command.SmallBlind.Value,
                command.BigBlind.Value);

            _gameRepository.AddGame(game);

            await _lobbyHub.Clients.All.SendAsync("gamecreated", _mapper.Map <GameListItemDto>(game));

            return(Ok(GenerateToken(game.Id, game.Players.First().Id)));
        }
Example #21
0
        public void IsValid_WhenOpponentIdIsEmpty_ShouldBeFalse()
        {
            // arrange
            string opponentId            = string.Empty;
            bool   isOpponentCrossPlayer = false;
            var    command = new CreateGameCommand()
            {
                OpponentId            = opponentId,
                IsOpponentCrossPlayer = isOpponentCrossPlayer
            };
            var validator = new CreateGameCommandValidator();

            // act
            FluentValidation.Results.ValidationResult result = validator.Validate(command);

            // assert
            result.IsValid.ShouldBe(false);
        }
Example #22
0
        public void IsValid_WhenOpponentIdIsNotEmptyOrNullAndIsShorterThan450_ShouldBeTrue()
        {
            // arrange
            string opponentId            = "opponentId";
            bool   isOpponentCrossPlayer = false;
            var    command = new CreateGameCommand()
            {
                OpponentId            = opponentId,
                IsOpponentCrossPlayer = isOpponentCrossPlayer
            };
            var validator = new CreateGameCommandValidator();

            // act
            FluentValidation.Results.ValidationResult result = validator.Validate(command);

            // assert
            result.IsValid.ShouldBe(true);
        }
Example #23
0
        public void IsValid_WhenOpponentIdIsLongerThan450_ShouldBeFalse()
        {
            // arrange
            string opponentId            = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis laoreet odio. Ut consequat lacinia ex, ut suscipit ligula ultrices sed. Duis quis libero eu ipsum convallis tempus. Sed malesuada augue pulvinar aliquam facilisis. Nulla fermentum enim quis convallis iaculis. Aliquam eu varius magna. Sed quis metus placerat, eleifend orci sed, tempus ligula. Duis ut egestas ante. Proin a purus ac erat gravida aliquam quis vitae justo. Mauris id.";
            bool   isOpponentCrossPlayer = false;
            var    command = new CreateGameCommand()
            {
                OpponentId            = opponentId,
                IsOpponentCrossPlayer = isOpponentCrossPlayer
            };
            var validator = new CreateGameCommandValidator();

            // act
            FluentValidation.Results.ValidationResult result = validator.Validate(command);

            // assert
            result.IsValid.ShouldBe(false);
        }
Example #24
0
        public async Task ShouldCreateANewGame()
        {
            GenerateMock();

            _gameRepositoryMock.Setup(x => x.Add(It.IsAny <Game>()));

            _gameRepositoryMock.Setup(x => x.UnitOfWork.SaveAsync(It.IsAny <CancellationToken>()));

            var handler = GetHandler();

            var command = new CreateGameCommand("name", 2010, "platform");

            await handler.Handle(command, default);

            _gameRepositoryMock.Verify(x => x.Add(It.Is <Game>(f => f.Platform == "platform" && f.Name == "name" && f.LaunchYear == 2010)));

            _gameRepositoryMock.Verify(x => x.UnitOfWork.SaveAsync(It.IsAny <CancellationToken>()));
        }
Example #25
0
        private static IEnumerable <ICommand> GenerateSampleDataCommands(int numberOfGames)
        {
            var results       = new List <ICommand>();
            var samplePlayers = GenerateSamplePlayers().ToList();

            results.AddRange(samplePlayers);

            for (int g = 0; g < numberOfGames; g++)
            {
                var newGame = new CreateGameCommand();
                newGame.GameId   = Guid.NewGuid();
                newGame.GameDate = GetUniqueDate(results);
                results.Add(newGame);

                var numPlayers = _rnd.Next(5, 10);
                var players    = new List <AddPlayerToGameCommand>();

                for (int p = 0; p < numPlayers; p++)
                {
                    var newPlayer = new AddPlayerToGameCommand();
                    newPlayer.PlayerId = GetRandomPlayer(samplePlayers, players);
                    newPlayer.GameId   = newGame.GameId;

                    players.Add(newPlayer);
                }

                results.AddRange(players);

                for (int p = 1; p < numPlayers; p++)
                {
                    var knockoutCommand = new KnockoutPlayerCommand();
                    knockoutCommand.GameId   = newGame.GameId;
                    knockoutCommand.PlayerId = players[p].PlayerId;

                    results.Add(knockoutCommand);
                }
            }

            return(results);
        }
Example #26
0
        public async Task Handle_WhenOpponentIsNotCrossPlayer_ShouldCreateGameWithCrossPlayerAsCurrentUser()
        {
            // arrange
            string opponentId            = "opponentId";
            bool   isOpponentCrossPlayer = false;
            var    command = new CreateGameCommand
            {
                OpponentId            = opponentId,
                IsOpponentCrossPlayer = isOpponentCrossPlayer
            };
            var handler = new CreateGameCommandHandler(Context, CurrentUserService, DateTime);

            // act
            int result = await handler.Handle(command, CancellationToken.None);

            Game entity = Context.Games.Find(result);

            // assert
            entity.ShouldNotBeNull();
            entity.StartDate.ShouldBe(DateTime.Now);
            entity.CrossPlayerId.ShouldBe(CurrentUserService.UserId);
            entity.NoughtPlayerId.ShouldBe(opponentId);
        }
        public void ShouldLogFailedCommand()
        {
            var testCommand = new CreateGameCommand();

            testCommand.GameDate  = DateTime.Now.AddDays(-2);
            testCommand.CommandId = Guid.NewGuid();
            testCommand.GameId    = Guid.NewGuid();
            testCommand.IPAddress = "12.34.56.78";
            testCommand.Timestamp = DateTime.Now;

            var mockCommandRepository = new Mock <ICommandRepository>();
            var mockEventRepository   = new Mock <IEventRepository>();
            var mockQueryService      = new Mock <IQueryService>();

            mockQueryService.Setup(q => q.Execute(It.IsAny <GetGameCountByDateQuery>())).Returns(0);

            var sut = new CommandHandlerFactory(
                mockEventRepository.Object,
                mockQueryService.Object,
                mockCommandRepository.Object);

            var ex = new ArgumentException("foo");

            mockEventRepository.Setup(x => x.PublishEvents(It.IsAny <IAggregateRoot>(), testCommand)).Throws(ex);

            try
            {
                sut.ExecuteCommand(testCommand);
            }
            catch
            {
                // eat all exceptions
            }

            mockCommandRepository.Verify(x => x.LogCommand(testCommand));
            mockCommandRepository.Verify(x => x.LogFailedCommand(testCommand, ex));
        }
        public void ShouldLogCommand()
        {
            var testCommand = new CreateGameCommand();

            testCommand.GameDate  = DateTime.Now.AddDays(-2);
            testCommand.CommandId = Guid.NewGuid();
            testCommand.GameId    = Guid.NewGuid();
            testCommand.IPAddress = "12.34.56.78";
            testCommand.Timestamp = DateTime.Now;

            var mockCommandRepository = new Mock <ICommandRepository>();
            var mockQueryService      = new Mock <IQueryService>();

            mockQueryService.Setup(q => q.Execute(It.IsAny <GetGameCountByDateQuery>())).Returns(0);

            var sut = new CommandHandlerFactory(
                new Mock <IEventRepository>().Object,
                mockQueryService.Object,
                mockCommandRepository.Object);

            sut.ExecuteCommand(testCommand);

            mockCommandRepository.Verify(x => x.LogCommand(testCommand));
        }
Example #29
0
 public async Task Post([FromBody] CreateGameCommand command)
 {
     await CommandPublisher.ExecuteAsync(command);
 }
Example #30
0
        public async Task <ICommandResult> Post([FromBody] CreateGameCommand command)
        {
            var result = _handler.Handle(command);

            return(await Response(result));
        }
 public Domain.GameOptions map_from(CreateGameCommand command)
 {
     return new GameOptions(command.game_difficulty, command.player_id);
 }
Example #32
0
 private static bool DoesDateMatch(CreateGameCommand x, DateTime result)
 {
     return(x.GameDate.Year == result.Year && x.GameDate.Month == result.Month && x.GameDate.Day == result.Day);
 }
 public Domain.GameOptions map_from(CreateGameCommand command)
 {
     return new GameOptions(command.game_difficulty, command.player_id);
 }