Exemplo n.º 1
0
		public void TwoNumbersAnswer ()
		{
			GameAnswer answer = new GameAnswer ();
			answer.Correct = "10 | 20";
			answer.CheckExpression = "[0-9]+";
			answer.CheckAttributes = GameAnswerCheckAttributes.Trim | GameAnswerCheckAttributes.MatchAll;

			// Right answers
			Assert.AreEqual (true, answer.CheckAnswer ("10 and 20"));
			Assert.AreEqual (true, answer.CheckAnswer ("10 i 20"));
			Assert.AreEqual (true, answer.CheckAnswer ("10 y 20"));
			Assert.AreEqual (true, answer.CheckAnswer ("10 20"));
			Assert.AreEqual (true, answer.CheckAnswer (" 10 20 "));

			Assert.AreEqual (true, answer.CheckAnswer ("20 and 10"));
			Assert.AreEqual (true, answer.CheckAnswer ("20 i 10"));
			Assert.AreEqual (true, answer.CheckAnswer ("20 y 10"));
			Assert.AreEqual (true, answer.CheckAnswer ("20 10"));
			Assert.AreEqual (true, answer.CheckAnswer (" 20 10 "));

			// Invalid answers
			Assert.AreEqual (false, answer.CheckAnswer (" 10 30 "));
			Assert.AreEqual (false, answer.CheckAnswer ("10"));
			Assert.AreEqual (false, answer.CheckAnswer ("20"));
			Assert.AreEqual (false, answer.CheckAnswer ("10 2"));
		}
Exemplo n.º 2
0
		public void MatchAllCheatMultiOption ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes |= GameAnswerCheckAttributes.MatchAll | GameAnswerCheckAttributes.MultiOption | GameAnswerCheckAttributes.IgnoreSpaces;
			answer.CheckExpression = "[ABCDEFGH]";
			answer.Correct = "A | B | C";
			Assert.AreEqual (false, answer.CheckAnswer ("A B C D"));
		}			
Exemplo n.º 3
0
		public void MatchAllCheatNumbers ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes = GameAnswerCheckAttributes.MatchAll;
			answer.CheckExpression = "[0-9]+";
			answer.Correct = "10 | 20 | 30";
			Assert.AreEqual (false, answer.CheckAnswer ("10 20 30 40 50"));
		}
Exemplo n.º 4
0
		public void DefaultAnswer ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.Correct = "icon";
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));

			answer.Correct = "icona";
			Assert.AreEqual (true, answer.CheckAnswer ("icona"));
		}
Exemplo n.º 5
0
		public void MatchAll ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes = GameAnswerCheckAttributes.MatchAll;
			answer.CheckExpression = "[0-9]+";
			answer.Correct = "10 | 20 | 30";
			Assert.AreEqual (true, answer.CheckAnswer ("10 20 30"));
			Assert.AreEqual (true, answer.CheckAnswer ("30 20 10"));
		}
Exemplo n.º 6
0
		public void DefaultAnswerOptions ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.Correct = "option1 | option2";
			Assert.AreEqual (true, answer.CheckAnswer ("option1"));
			Assert.AreEqual (true, answer.CheckAnswer ("option2"));
			Assert.AreEqual (true, answer.CheckAnswer (" option2 "));

			Assert.AreEqual (false, answer.CheckAnswer ("option3"));
		}
Exemplo n.º 7
0
        public IHttpActionResult PostGameAnswers(IList <GameAnswerDTO> GameAnswersDTOsIn)
        {
            long   firstPlayerId = GameAnswersDTOsIn[0].PlayerId;
            string firstGameCode = GameAnswersDTOsIn[0].GameCode;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                ProbeValidate.ValidateGameCodeVersusPlayerId(firstPlayerId, firstGameCode);
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah

                //Delete the player - if it exists and it does not have any GameAnswers
                if (!ProbeValidate.IsPlayerHaveAnyAnswers(firstPlayerId))
                {
                    Player player = db.Player.Find(firstPlayerId);
                    db.Player.Remove(player);
                    db.SaveChanges(Request != null ? Request.Headers.UserAgent.ToString() : null);
                }

                return(BadRequest(ModelState));
            }

            List <GameAnswerDTO> GameAnswerDTOsOut = new List <GameAnswerDTO>();

            //create GameAnswerDTO's (Id, PlayerId, ChoiceId)
            foreach (GameAnswerDTO GameAnswerDTOIn in GameAnswersDTOsIn)
            {
                //we need to create a GameAnswer (to record in the database)
                GameAnswer GameAnswer = new GameAnswer
                {
                    PlayerId = GameAnswerDTOIn.PlayerId,
                    ChoiceId = GameAnswerDTOIn.ChoiceId
                };

                db.GameAnswer.Add(GameAnswer);
                db.SaveChanges(Request != null ? Request.Headers.UserAgent.ToString() : null);

                GameAnswerDTO GameAnswerDTOOut = new GameAnswerDTO();
                GameAnswerDTOOut.Id       = GameAnswer.Id;
                GameAnswerDTOOut.PlayerId = GameAnswer.PlayerId;
                GameAnswerDTOOut.ChoiceId = GameAnswer.ChoiceId;
                GameAnswerDTOsOut.Add(GameAnswerDTOOut);
            } //foreach (GameAnswerDTO GameAnswerDTOIn in GameAnswersDTOsIn)

            //returning all the GameAnswerDTOs in the list
            return(CreatedAtRoute("DefaultApi", new { id = GameAnswerDTOsOut[0].Id }, GameAnswerDTOsOut));
        } //public IHttpActionResult PostGameAnswers
Exemplo n.º 8
0
		public void CheckCalculationOperator ()
		{
			GameAnswer answer = new GameAnswer ();
			answer.Correct = "+ | -";
			answer.CheckExpression = "[+*-/]";
			answer.CheckAttributes = GameAnswerCheckAttributes.Trim | GameAnswerCheckAttributes.MatchAllInOrder;

			Assert.AreEqual (true, answer.CheckAnswer ("+ i -"));
			Assert.AreEqual (true, answer.CheckAnswer ("+ and -"));
			Assert.AreEqual (true, answer.CheckAnswer ("+ -"));
			Assert.AreEqual (true, answer.CheckAnswer ("+-"));

			Assert.AreEqual (false, answer.CheckAnswer ("- +"));
		}
Exemplo n.º 9
0
		public void CheckPuzzleTimeNowAnswer ()
		{
			GameAnswer answer = new GameAnswer ();
			answer.Correct = "10 PM";
			answer.CheckAttributes = GameAnswerCheckAttributes.Trim | GameAnswerCheckAttributes.IgnoreCase | GameAnswerCheckAttributes.IgnoreSpaces;

			Assert.AreEqual (true, answer.CheckAnswer ("10 PM"));
			Assert.AreEqual (true, answer.CheckAnswer ("10 pm"));
			Assert.AreEqual (true, answer.CheckAnswer ("10pm"));
			Assert.AreEqual (true, answer.CheckAnswer ("10Pm"));
			Assert.AreEqual (true, answer.CheckAnswer (" 10Pm "));

			Assert.AreEqual (false, answer.CheckAnswer ("10 P"));
			Assert.AreEqual (false, answer.CheckAnswer ("10"));
		}
Exemplo n.º 10
0
		public void CheckPuzzlePercentage ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.Correct = "10";
			answer.CheckExpression = "[0-9]+";

			Assert.AreEqual (true, answer.CheckAnswer ("10%"));
			Assert.AreEqual (true, answer.CheckAnswer ("10 %"));
			Assert.AreEqual (true, answer.CheckAnswer ("10"));

			answer.Correct = "9";
			Assert.AreEqual (true, answer.CheckAnswer ("9%"));
			Assert.AreEqual (true, answer.CheckAnswer ("9 %"));
			Assert.AreEqual (true, answer.CheckAnswer ("9"));
		}
Exemplo n.º 11
0
		public void CheckPuzzleBuildTriangle ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.Correct = "A | B | C";
			answer.CheckExpression = "[ABCDF]";
			answer.CheckAttributes = GameAnswerCheckAttributes.Trim | GameAnswerCheckAttributes.IgnoreCase | GameAnswerCheckAttributes.MatchAll;

			Assert.AreEqual (true, answer.CheckAnswer ("A B C"));
			Assert.AreEqual (true, answer.CheckAnswer ("C B A"));
			Assert.AreEqual (true, answer.CheckAnswer ("B C A"));
			Assert.AreEqual (true, answer.CheckAnswer ("A B C"));
			Assert.AreEqual (true, answer.CheckAnswer ("C A B"));
			Assert.AreEqual (true, answer.CheckAnswer ("a b c"));

			Assert.AreEqual (false, answer.CheckAnswer ("B C C"));
			Assert.AreEqual (false, answer.CheckAnswer ("B C"));
			Assert.AreEqual (false, answer.CheckAnswer ("BC"));
		}
Exemplo n.º 12
0
        public async Task Answer(GameAnswer message, GameMessageType messageType = GameMessageType.RegularAnswer)
        {
            PlayerInfo playerInfo = await _players.GetById(message.PlayerId);

            _rabbitMqChannel.BasicPublish(
                _rabbitMqSettings.MessagesExchange,
                new MessagesRoutingKeyBuilder()
                .WithSocialNetwork(playerInfo.ReplyQueueName)
                .WithMessageType(messageType)
                .Build(),
                null,
                new MessageToSocialNetwork
            {
                Text           = message.Text,
                PlayerId       = message.PlayerId,
                Suggestions    = message.Suggestions,
                PlayerSocialId = playerInfo.SocialId
            }.EncodeObject()
                );
        }
Exemplo n.º 13
0
		public void IgnoreSpaces ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes = GameAnswerCheckAttributes.None;
			answer.Correct = "10 pm";
			Assert.AreEqual (true, answer.CheckAnswer ("10 pm"));
			Assert.AreEqual (false, answer.CheckAnswer ("10pm"));

			answer.CheckAttributes = GameAnswerCheckAttributes.IgnoreSpaces;
			Assert.AreEqual (true, answer.CheckAnswer ("10 pm"));
			Assert.AreEqual (true, answer.CheckAnswer ("10pm"));

			answer.CheckAttributes = GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("10 pm"));
			Assert.AreEqual (false, answer.CheckAnswer ("10pm"));

			answer.CheckAttributes = GameAnswerCheckAttributes.IgnoreSpaces | GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("10 pm"));
			Assert.AreEqual (true, answer.CheckAnswer ("10pm"));
		}
Exemplo n.º 14
0
		public void IgnoreCase ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes = GameAnswerCheckAttributes.None;
			answer.Correct = "icon";
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (false, answer.CheckAnswer ("ICON"));

			answer.CheckAttributes = GameAnswerCheckAttributes.IgnoreCase;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (true, answer.CheckAnswer ("ICON"));

			answer.CheckAttributes = GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (false, answer.CheckAnswer ("ICON"));

			answer.CheckAttributes = GameAnswerCheckAttributes.IgnoreCase | GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (true, answer.CheckAnswer ("ICON"));
		}
Exemplo n.º 15
0
		public void Trim ()
		{
			GameAnswer answer = new GameAnswer ();

			answer.CheckAttributes = GameAnswerCheckAttributes.None;
			answer.Correct = "icon";
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (false, answer.CheckAnswer (" icon "));

			answer.CheckAttributes = GameAnswerCheckAttributes.Trim;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (true, answer.CheckAnswer (" icon "));

			answer.CheckAttributes = GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (false, answer.CheckAnswer (" icon "));

			answer.CheckAttributes = GameAnswerCheckAttributes.Trim | GameAnswerCheckAttributes.MatchAll;
			Assert.AreEqual (true, answer.CheckAnswer ("icon"));
			Assert.AreEqual (true, answer.CheckAnswer (" icon "));
		}
Exemplo n.º 16
0
        public IHttpActionResult PostPlayer([ModelBinder(typeof(PlayerModelBinderProvider))] PlayerDTO playerDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            /*
             * Let's make sure the gameplayid and gamecode match up correctly. check for malicious activity
             */
            try
            {
                ProbeValidate.ValidateGameCodeVersusId(playerDTO.GameId, playerDTO.GameCode);
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                return(BadRequest(ModelState));
            }

            int      nbrPlayersAnswersCorrect = 0;
            DateTime dateTimeNow = DateTime.UtcNow;
            Player   player      = new Player();

            //Create a GameAnswers Collection
            ICollection <GameAnswer> gameAnswers = new List <GameAnswer>();

            foreach (GameAnswerDTO gameAnswerDTO in playerDTO.GameAnswers)
            {
                //we need to create a gameAnswer (to record in the database)
                GameAnswer gameAnswer = new GameAnswer
                {
                    PlayerId = playerDTO.Id,
                    ChoiceId = gameAnswerDTO.ChoiceId
                };
                gameAnswers.Add(gameAnswer);
            } //foreach (GameAnswerDTO gameAnswerDTO in playerDTO.GameAnswers)

            Game   g = db.Game.Find(playerDTO.GameId);
            string userNameOfGameAuthor = new ProbeIdentity().GetUserNameFromUserId(g.AspNetUsersId);

            ProbeGame probeGame = new ProbeGame(g);

            /*
             * If we've gotten this far, then the required fields and game code security
             * validations have passed
             */
            try
            {
                //business validations
                if (!probeGame.IsActive())
                {
                    throw new GameNotActiveException();
                }

                player.Id = playerDTO.Id;
                if (!probeGame.IsPlayerSubmitted(player))
                {
                    //In here, we know this is a new player
                    player = new Player
                    {
                        Id        = playerDTO.Id,
                        GameId    = playerDTO.GameId,
                        FirstName = playerDTO.FirstName,
                        LastName  = playerDTO.LastName,
                        NickName  = playerDTO.NickName,
                        EmailAddr = playerDTO.EmailAddr,
                        Sex       = playerDTO.Sex,
                        //Active = true, //Do not specify at this point
                        SubmitDate = dateTimeNow.Date,
                        SubmitTime = DateTime.Parse(dateTimeNow.ToShortTimeString())
                    };

                    //will throw the following exceptions if there is a problem
                    //GameDuplicatePlayerNameException, GameInvalidFirstNameException, GameInvalidNickNameException
                    //ONLY NEED TO VALIDATE IF THE PLAYER HAS NOT SUBMITTED FOR A GAME YET
                    probeGame.ValidateGamePlayer(player);

                    player.Active = true; //Player is always active to begin with
                    db.Person.Add(player);
                }
                else
                {  //we get here only if it's an existing player
                    player = db.Player.Find(playerDTO.Id);

                    if (!probeGame.IsPlayerActive(player))
                    {
                        throw new GamePlayerInActiveException();
                    }
                }//if (!probeGame.IsPlayerSubmitted(player))

                //Making this API backward compatible. Will not attempt to record game answers if its
                //client version v1.0
                if (playerDTO.ClientVersion != ProbeConstants.ClientVersionPostPlayerWithoutAnswers)
                {
                    if (playerDTO.GameAnswers == null)
                    {
                        throw new PlayerDTOMissingAnswersException();
                    }
                    else if (!probeGame.IsValidGameAnswer(gameAnswers))
                    {
                        throw new InvalidGameAnswersException();
                    }

                    //Determine if the GameAnswer submission is not too early. We pass the DTO version because it has the question number
                    //Note: This audit had to come after the player is submitted check and player added to database
                    if (!probeGame.IsPlayerGameAnswerNotTooEarly(dateTimeNow, gameAnswers))
                    {
                        throw new GameAnswersTooEarlyException();
                    }

                    //Determine if the GameAnswer submission is ontime. We pass the DTO version because it has the question number
                    //Note: This audit had to come after the player is submitted check and player added to database
                    if (!probeGame.IsPlayerGameAnswerOnTime(dateTimeNow, gameAnswers))
                    {
                        throw new GameAnswersTooLateException();
                    }

                    //create GameAnswerDTO's (Id, PlayerId, ChoiceId)
                    foreach (GameAnswer gameAnswer in gameAnswers)
                    {
                        //we need to create a gameAnswer (to record in the database)
                        GameAnswer GameAnswerforDB = new GameAnswer
                        {
                            Player   = player, //player could have been created new or an existing
                            ChoiceId = gameAnswer.ChoiceId
                        };

                        db.GameAnswer.Add(GameAnswerforDB);
                    } //foreach (GameAnswerDTO gameAnswerDTOIn in gameAnswersDTOsIn)
                    db.SaveChanges(Request != null ? Request.Headers.UserAgent.ToString() : null); //record all gameanswers to player

                    //We pass in the playerDO.GameAnswers because it holds the QuestionId of each question. Much
                    //more assurance that we are correcting the appropriate questions and answers
                    nbrPlayersAnswersCorrect = probeGame.NbrPlayerAnswersCorrect(playerDTO.GameAnswers);

                    //if the game is LMS - Determine if any of the answers submitted were wrong.
                    //If so then we are going to make the player inactive
                    if (probeGame.GameType == ProbeConstants.LMSGameType)
                    {
                        if (playerDTO.GameAnswers.Count() > nbrPlayersAnswersCorrect)
                        {
                            //We need to make the player inactive.
                            probeGame.SetPlayerStatus(player, false, Player.PlayerGameReasonType.ANSWER_REASON_INCORRECT);
                        }
                    } //if (probeGame.GameType == ProbeConstants.LMSGameType)
                }     //if (!playerDTO.ClientVersion.Contains("v1.0"))

                //notify clients of game author of game change
                NotifyProbe.NotifyGameChanged(userNameOfGameAuthor);

                playerDTO.PlayerGameStatus                     = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.NbrPlayers          = probeGame.NbrPlayers;
                playerDTO.PlayerGameStatus.NbrPlayersRemaining = probeGame.NbrPlayersActive;
                playerDTO.PlayerGameStatus.NbrAnswersCorrect   = nbrPlayersAnswersCorrect;
                playerDTO.PlayerGameStatus.PlayerActive        = probeGame.IsPlayerActive(player);
                playerDTO.PlayerGameStatus.MessageId           = ProbeConstants.MSG_NoError;

                playerDTO.Id = player.Id;                                                   //if a new player created then we have to set the Id to be passed back to the client
                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO)); //EVERYTHING IS GOOD!
            } //try
            catch (GameNotActiveException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_GameNotActive;
                playerDTO.PlayerGameStatus.Message   = "This game is not active at this time.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameDuplicatePlayerNameException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_PlayerDupInGame;
                string playername = new ProbePlayer(player).PlayerGameName;
                playerDTO.PlayerGameStatus.Message = "The player's name (" + playername + ") has already been used in this game.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameInvalidFirstNameException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_PlayerFirstNameInvalid;
                playerDTO.PlayerGameStatus.Message   = "The player's first name is invalid.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameInvalidNickNameException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_PlayerNickNameInvalid;
                playerDTO.PlayerGameStatus.Message   = "The player's nick name is invalid.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (PlayerDTOMissingAnswersException)
            {
                //cleanup first
                if (!probeGame.IsPlayerHaveAnswers(player))
                {
                    ProbeGame.DeletePlayer(db, player);
                    //notify clients of game author of game change
                    NotifyProbe.NotifyGameChanged(userNameOfGameAuthor);
                }

                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_SubmissionMissingAnswers;
                playerDTO.PlayerGameStatus.Message   = "The client player answer submission is missing question-answers.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (InvalidGameAnswersException)
            {
                //cleanup first
                if (!probeGame.IsPlayerHaveAnswers(player))
                {
                    ProbeGame.DeletePlayer(db, player);
                    //notify clients of game author of game change
                    NotifyProbe.NotifyGameChanged(userNameOfGameAuthor);
                }

                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_SubmissionInvalidAnswers;
                playerDTO.PlayerGameStatus.Message   = "The client player answer submission possess the incorrect number of question-answers.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameInvalidPlayerNameException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_PlayerNameInvalid;
                playerDTO.PlayerGameStatus.Message   = "The player's name is invalid.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameInvalidLastNameException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_PlayerLastNameInvalid;
                playerDTO.PlayerGameStatus.Message   = "The player's last name is invalid.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameAnswersTooLateException)
            {
                //Everything is not good. The GameAnswer submission did not come in ontime. So the
                //player will become inactive. However, we will still send player game stats to the client.
                //We need to make the player inactive.
                //Note: we want to keep the player in the datbase (as inactive) also.
                probeGame.SetPlayerStatus(player, false, Player.PlayerGameReasonType.ANSWER_REASON_DEADLINE);

                playerDTO.PlayerGameStatus                     = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.NbrPlayers          = probeGame.NbrPlayers;
                playerDTO.PlayerGameStatus.NbrPlayersRemaining = probeGame.NbrPlayersActive;
                playerDTO.PlayerGameStatus.NbrAnswersCorrect   = nbrPlayersAnswersCorrect;
                playerDTO.PlayerGameStatus.PlayerActive        = probeGame.IsPlayerActive(player);
                playerDTO.PlayerGameStatus.MessageId           = ProbeConstants.MSG_SubmissionNotOntime;
                playerDTO.PlayerGameStatus.Message             = "The player submission was beyond the deadline.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GameAnswersTooEarlyException)
            {
                //Everything is not good. The GameAnswer submission is too early.
                //We will still send player game stats to the client.
                //We will keep the player status active at this point.
                //probeGame.SetPlayerStatus(player, false); DONT NEED THIS FOR NOW

                playerDTO.PlayerGameStatus                     = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.NbrPlayers          = probeGame.NbrPlayers;
                playerDTO.PlayerGameStatus.NbrPlayersRemaining = probeGame.NbrPlayersActive;
                playerDTO.PlayerGameStatus.NbrAnswersCorrect   = nbrPlayersAnswersCorrect;
                playerDTO.PlayerGameStatus.PlayerActive        = probeGame.IsPlayerActive(player);
                playerDTO.PlayerGameStatus.MessageId           = ProbeConstants.MSG_SubmissionTooEarly;
                playerDTO.PlayerGameStatus.Message             = "The player submission was too early.";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (GamePlayerInActiveException)
            {
                playerDTO.PlayerGameStatus           = new PlayerGameStatus();
                playerDTO.PlayerGameStatus.MessageId = ProbeConstants.MSG_GamePlayerInActive;
                string playername = new ProbePlayer(player).PlayerGameName;
                playerDTO.PlayerGameStatus.Message = "The player (" + playername + ") is inactive for the game";

                return(CreatedAtRoute("DefaultApi", new { id = playerDTO.Id }, playerDTO));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah

                //cleanup first - different type of cleanup depends on game type
                if (probeGame.GameType == ProbeConstants.LMSGameType)
                {
                    //if LMS - we only delete the player if there are no answers for that player
                    if (!probeGame.IsPlayerHaveAnswers(player))
                    {
                        ProbeGame.DeletePlayer(db, player);
                        //notify clients of game author of game change
                        NotifyProbe.NotifyGameChanged(userNameOfGameAuthor);
                    }
                }
                else
                {
                    //If Match or Test, then we remove any remants of the player and her answers
                    ProbeGame.DeletePlayer(db, player);
                }
                var errorObject = new
                {
                    errorid      = ex.HResult,
                    errormessage = ex.Message,
                    errorinner   = ex.InnerException,
                    errortrace   = ex.StackTrace
                };
                return(CreatedAtRoute("DefaultApi", new { id = errorObject.errorid }, errorObject));
            }
        }//public IHttpActionResult PostPlayer([...
Exemplo n.º 17
0
        /*
         * Will clone the game and all artifacts associated with that game. gameconfiguration, gamequestion, question/choicequestion,
         * choice and game records. The game to clone is defined by the sourceGameId. Where the game is clone to (what user) is
         * determined by the destAspNetUsersId
         */
        public static Game CloneGame(Controller controller, ProbeDataContext db, long sourceGameId
                                     , string destAspNetUsersId, bool cloneCrossUsers, bool gamePlayInd)
        {
            //clone game - always in suspend mode so its not playable yet and it's editable
            Game   gSource = db.Game.Find(sourceGameId);
            string newName = GetClonedGameName(gSource.Name, destAspNetUsersId);
            string newCode = GetClonedCode(gSource.Code);

            Game gNew = new Game
            {
                AspNetUsersId      = destAspNetUsersId,
                GameTypeId         = gSource.GameTypeId,
                Name               = newName,
                Description        = gSource.Description,
                Code               = newCode,
                TestMode           = gSource.TestMode,
                Published          = (cloneCrossUsers) ? gSource.Published : false,
                SuspendMode        = (cloneCrossUsers) ? gSource.SuspendMode : false,
                ClientReportAccess = gSource.ClientReportAccess,
                StartDate          = gSource.StartDate,
                EndDate            = gSource.EndDate,
                GameUrl            = gSource.GameUrl,
                ACLId              = gSource.ACLId
            };

            db.Game.Add(gNew);

            //clone all gameconfigurations. should only pull the gameconfiguration records that exist. Any configuration that is still
            //using the default ConfigurationG record will not be pulled here. No need to clone this record.
            IList <GameConfigurationDTO> gameConfigurations = db.ConfigurationG
                                                              .Where(c => c.ConfigurationType != ConfigurationG.ProbeConfigurationType.GLOBAL)
                                                              .SelectMany(c => c.GameConfigurations.Where(gc => gc.Game.Id == sourceGameId),
                                                                          (c, gc) =>
                                                                          new GameConfigurationDTO
            {
                ConfigurationGId = gc.ConfigurationGId,
                Value            = gc.Value
            }
                                                                          ).ToList();

            foreach (GameConfigurationDTO gameConfiguration in gameConfigurations)
            {
                GameConfiguration clonedGameConfiguration = new GameConfiguration
                {
                    Game             = gNew,
                    ConfigurationGId = gameConfiguration.ConfigurationGId,
                    Value            = gameConfiguration.Value
                };

                db.GameConfiguration.Add(clonedGameConfiguration);
            }//foreach (GameConfiguration gameConfiguration in gameConfigurations)

            //clone gamequestions and question/choices for each gamequestion
            IList <GameQuestion> gameQuestions = db.GameQuestion.Where(gq => gq.GameId == sourceGameId).ToList();

            Dictionary <long, Dictionary <long, Choice> > questionXreference = new Dictionary <long, Dictionary <long, Choice> >();

            foreach (GameQuestion gameQuestion in gameQuestions)
            {
                //attach questions to game
                long           sourceQuestionId = gameQuestion.QuestionId;
                ChoiceQuestion clonedQuestion   = ProbeQuestion.CloneQuestion(controller, ref db, true, sourceQuestionId);

                GameQuestion clonedGameQuestion = new GameQuestion
                {
                    Game     = gNew,
                    Question = clonedQuestion,
                    OrderNbr = gameQuestion.OrderNbr,
                    Weight   = gameQuestion.Weight
                };

                db.GameQuestion.Add(clonedGameQuestion);

                //We are building a question - choice cross reference table for down the road. old question id -> (old choice id -> new choice)
                ChoiceQuestion            cqOrg            = db.ChoiceQuestion.Find(sourceQuestionId);
                Dictionary <long, Choice> choiceXreference = new Dictionary <long, Choice>();
                //Here we populate the choice X reference table. Associate the old choice with the new choice. Somebody might need this down the road.
                for (int i = 0; i < cqOrg.Choices.Count(); i++)
                {
                    //NEED A DATASTRUCTURE THAT ASSOCIATES ONE CHOICE WITH ANOTHER CHOICE
                    choiceXreference.Add(cqOrg.Choices.ElementAt(i).Id, clonedQuestion.Choices.ElementAt(i));
                }

                //DATASTRUCTURE that does hold old question id -> (old choice id -> new choice). This is to record the choices for the
                //new questions of the game associated with the new gamequestions
                questionXreference.Add(gameQuestion.QuestionId, choiceXreference);
            }//foreach (GameQuestion gameQuestion in gameQuestions)

            //if directed, then the game that is played will be cloned. Players, GameAnswers
            if (gamePlayInd)
            {
                //Get all the players for the game played
                IList <Player> players = db.Player.Where(p => p.GameId == sourceGameId).ToList();
                foreach (Player player in players)
                {
                    Player clonedPlayer = new Player
                    {
                        LastName         = player.LastName,
                        FirstName        = player.FirstName,
                        MiddleName       = player.MiddleName,
                        NickName         = player.NickName,
                        EmailAddr        = player.EmailAddr,
                        MobileNbr        = player.MobileNbr,
                        Sex              = player.Sex,
                        SubmitDate       = player.SubmitDate,
                        SubmitTime       = player.SubmitTime,
                        GameId           = gNew.Id,
                        Active           = player.Active,
                        PlayerGameReason = player.PlayerGameReason
                    };
                    db.Player.Add(clonedPlayer);

                    //Get all the OLD answers for the player in this iteration
                    IList <GameAnswer> gameanswers = db.GameAnswer.Where(ga => ga.PlayerId == player.Id).ToList();
                    foreach (GameAnswer gameAnswer in gameanswers)
                    {
                        GameAnswer clonedGameAnswer = new GameAnswer
                        {
                            Player = clonedPlayer,
                            Choice = questionXreference[gameAnswer.Choice.ChoiceQuestionId][gameAnswer.ChoiceId]
                        };

                        db.GameAnswer.Add(clonedGameAnswer);
                    } //foreach (GameAnswer gameAnswer in gameanswers)
                }     //foreach (Player player in players)
            }         //if (gamePlayInd)

            //THIS WILL RECORD NEW Game, GameConfiguration, GameQuestions, ChoiceQuestion/Question, Choice
            db.SaveChanges(controller.Request != null ? controller.Request.LogonUserIdentity.Name : null); //record all gameanswers for the new player

            return(gNew);
        }//CloneGame