Example #1
0
        public IHttpActionResult PutQuestion(long id, Question question)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != question.Id)
            {
                return(BadRequest());
            }

            db.Entry(question).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QuestionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public IHttpActionResult PutGameConfiguration(long id, GameConfiguration gameConfiguration)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != gameConfiguration.Id)
            {
                return(BadRequest());
            }

            db.Entry(gameConfiguration).State = EntityState.Modified;

            try
            {
                db.SaveChanges(Request != null ? Request.Headers.UserAgent.ToString() : null);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameConfigurationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public JsonResult Create([DataSourceRequest] DataSourceRequest request, QuestionDTO questionDTO)
        {
            try
            {
                ValidateQuestionCreate(questionDTO);
                if (ModelState.IsValid)
                {
                    ChoiceQuestion choiceQuestion = new ChoiceQuestion
                    {
                        Id             = 0,
                        AspNetUsersId  = User.Identity.GetUserId(),
                        OneChoice      = true, //for some reason; disabling the OneChoice prompt in RAZOR turns this to false.. This is a hack
                        UsedInGame     = false,
                        ACLId          = 1,
                        QuestionTypeId = questionDTO.QuestionTypeId,
                        Name           = questionDTO.Name,
                        Text           = questionDTO.Text,
                        Tags           = questionDTO.Tags
                    };

                    db.Question.Add(choiceQuestion);
                    db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                    questionDTO.Id = choiceQuestion.Id; //pass back the new Id to the client
                }

                return(Json(new[] { questionDTO }.ToDataSourceResult(request, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult()));
            }
        }//public JsonResult Create([DataSourceRequest] DataSourceRequest request, QuestionDTO questionDTO)
Example #4
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
Example #5
0
        public JsonResult Create([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO)
        {
            try
            {
                ValidateGameCreate(gameDTO);
                if (ModelState.IsValid)
                {
                    //transform DTO to business object (Game)
                    Game game = new Game
                    {
                        Id            = 0,
                        AspNetUsersId = User.Identity.GetUserId(),
                        GameTypeId    = gameDTO.GameTypeId,
                        Name          = gameDTO.Name,
                        Description   = gameDTO.Description,
                        Code          = gameDTO.Code,

                        //Conversion from local (client-side) to UTC (server-side) is completed in the backend controller
                        StartDate = Probe.Helpers.Mics.ClientTimeZoneHelper.ConvertLocalToUTC(gameDTO.StartDate),
                        EndDate   = Probe.Helpers.Mics.ClientTimeZoneHelper.ConvertLocalToUTC(gameDTO.EndDate),

                        //GameUrl = gameDTO.GameUrl, NOT USED
                        Published   = false,
                        SuspendMode = gameDTO.SuspendMode,
                        //TestMode = gameDTO.TestMode, NOT USED
                        ClientReportAccess = gameDTO.ClientReportAccess,
                        ACLId = 1 //private
                    };

                    db.Game.Add(game);
                    db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);

                    //We will send back the game dates that are coverted to UTC
                    gameDTO.StartDate = ClientTimeZoneHelper.ConvertToLocalTime(game.StartDate, false);
                    gameDTO.EndDate   = ClientTimeZoneHelper.ConvertToLocalTime(game.EndDate, false);

                    gameDTO.IsActive          = ProbeValidate.IsGameActiveOrPlayersExist(game); //updates the IsActive field
                    gameDTO.PlayerCount       = 0;
                    gameDTO.PlayerActiveCount = 0;
                    gameDTO.QuestionCount     = 0;
                    gameDTO.Id = game.Id; //pass back the new Id to the client
                }

                return(Json(new[] { gameDTO }.ToDataSourceResult(request, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult()));
            }
        }//public JsonResult Create([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO)
Example #6
0
        public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, PlayerDTO playerDTO)
        {
            try
            {
                long gameId = playerDTO.GameId;

                //check to ensure the user owns the resources she is trying to access. if not; we get out of here.
                //Somebody is trying to do bad stuff.
                if (!ProbeValidate.IsGameForLoggedInUser((long)playerDTO.GameId))
                {
                    ModelState.AddModelError("", "Player Update could not be accomplished");
                    return(Json(ModelState.ToDataSourceResult()));
                }

                if (ModelState.IsValid)
                {
                    Player player = db.Player.Find(playerDTO.Id);
                    player.Sex = playerDTO.Sex;

                    db.Entry(player).State = EntityState.Modified;
                    db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                }

                //return Json(ModelState.ToDataSourceResult());
                return(Json(new[] { playerDTO }.ToDataSourceResult(dsRequest, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.ToDataSourceResult()));
            }
        }//public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, PlayerDTO playerDTO)
Example #7
0
        public JsonResult Create([DataSourceRequest] DataSourceRequest request, ChoiceDTO choiceDTO)
        {
            try
            {
                //check to ensure the user owns the resources she is trying to access. if not; we get out of here.
                //Somebody is trying to do bad stuff.
                if (!ProbeValidate.IsQuestionForLoggedInUser(choiceDTO.ChoiceQuestionId))
                {
                    ModelState.AddModelError("", "Question Create could not be accomplished");
                    return(Json(ModelState.ToDataSourceResult()));
                }

                if (choiceDTO.Correct)
                {
                    ValidateChoice(choiceDTO.ChoiceQuestionId);                    //only validate if choice selected uses correct
                }
                //Set choice name - same as question name
                choiceDTO.Name = db.ChoiceQuestion.Find(choiceDTO.ChoiceQuestionId).Name;
                if (ModelState.IsValid)
                {
                    Choice choice = new Choice
                    {
                        Id = choiceDTO.Id,
                        ChoiceQuestionId = choiceDTO.ChoiceQuestionId,
                        Name             = choiceDTO.Name,
                        Text             = choiceDTO.Text,
                        Correct          = choiceDTO.Correct,
                        OrderNbr         = choiceDTO.OrderNbr
                    };
                    db.Choice.Add(choice);
                    db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                    choiceDTO.Id = choice.Id;
                }

                NotifyProbe.NotifyChoiceChanged(User.Identity.Name); //let all clients know where was a game change.

                return(Json(new[] { choiceDTO }.ToDataSourceResult(request, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult()));
            }
        }//public JsonResult Create([DataSourceRequest] DataSourceRequest request, ChoiceDTO choiceDTO)
Example #8
0
        }//CloneQuestions

        /*
         * Will delete the question and all artifacts associated with that question. question/choicequestion,
         * choice records.
         */
        public static void DeleteQuestion(Controller controller, ProbeDataContext db, long questionId)
        {
            ChoiceQuestion cq = db.ChoiceQuestion.Find(questionId);

            db.Choice.RemoveRange(cq.Choices);

            db.ChoiceQuestion.Remove(cq);
            db.SaveChanges(controller.Request != null ? controller.Request.LogonUserIdentity.Name : null);
        }//DeleteQuestion
Example #9
0
        public void SetPlayerStatus(Player player, bool activeStatus, Player.PlayerGameReasonType playerGameReason)
        {
            //We need to make the player inactive.
            Player playerUpdate = db.Player.Find(player.Id);

            playerUpdate.Active           = activeStatus;
            playerUpdate.PlayerGameReason = playerGameReason;
            db.Entry(playerUpdate).State  = EntityState.Modified;
            db.SaveChanges();
        }//public void SetPlayerStatus(Player player, bool activeStatus)
        //[ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Description")] QuestionType questionType)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.QuestionType.Add(questionType);
                    db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                    return(RedirectToAction("Index"));
                }

                return(View(questionType));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError(ProbeConstants.MSG_UnsuccessfulOperation.ToString(), ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(View());
            }
        }
        public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, GameQuestionDTO gameQuestionDTO)
        {
            try
            {
                //we are only updating the Game Question order number and weight
                GameQuestion gameQuestion = db.GameQuestion.Find(gameQuestionDTO.Id);
                gameQuestion.OrderNbr = gameQuestionDTO.OrderNbr;
                gameQuestion.Weight   = gameQuestionDTO.Weight;

                db.Entry(gameQuestion).State = EntityState.Modified;
                db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);

                return(Json(new[] { gameQuestionDTO }.ToDataSourceResult(dsRequest, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.ToDataSourceResult()));
            }
        }
Example #12
0
        }//DeleteGame

        //Delete player - if the player Id passed is valid. Will delete game answers if they exist.
        public static void DeletePlayer(ProbeDataContext db, Player player)
        {
            //Only delete if the player Id is valid. Otherwise, we ignore this.
            if (player.Id > 0)
            {
                var gpas = db.GameAnswer.Where(ga => ga.PlayerId == player.Id);
                foreach (GameAnswer ga in gpas)
                {
                    db.GameAnswer.Remove(ga);
                }
                db.Player.Remove(player);

                db.SaveChanges();
            }
        }//public void DeletePlayer()
Example #13
0
        }//GetClonedCodeName

        /*
         * Will delete the game and all artifacts associated with that game. gameconfiguration, gamequestion, question/choicequestion,
         * choice and game records.
         */
        public static void DeleteGame(Controller controller, ProbeDataContext db, long gameId)
        {
            Game g = db.Game.Find(gameId);

            //remove all questions attached to the game/gamequestions
            IList <GameQuestion> gameQuestions = db.GameQuestion.Where(gq => gq.GameId == gameId).ToList();

            foreach (GameQuestion gameQuestion in gameQuestions)
            {
                ProbeQuestion.DeleteQuestion(controller, db, gameQuestion.QuestionId);
            }

            db.Player.RemoveRange(g.Players);             //Remove all players that have submitted games
            db.GameQuestion.RemoveRange(g.GameQuestions); //Remove all gamequestions for game
            db.GameConfiguration.RemoveRange(g.GameConfigurations);
            db.Game.Remove(g);                            //Remove the game itself
            db.SaveChanges(controller.Request != null ? controller.Request.LogonUserIdentity.Name : null);
        }//DeleteGame
Example #14
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
        public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, GameConfigurationDTO gameConfigurationDTO)
        {
            try
            {
                long gameId = (long)gameConfigurationDTO.GameId;

                //check to ensure the user owns the resources she is trying to access. if not; we get out of here.
                //Somebody is trying to do bad stuff.
                if (!ProbeValidate.IsGameForLoggedInUser((long)gameConfigurationDTO.GameId))
                {
                    ModelState.AddModelError("", "Game Configuration Update could not be accomplished");
                    return(Json(ModelState.ToDataSourceResult()));
                }

                if (ModelState.IsValid)
                {
                    switch (gameConfigurationDTO.DataTypeG)
                    {
                    case ConfigurationG.ProbeDataType.TEXT:
                    {
                        if (gameConfigurationDTO.Value.Contains("script"))
                        {
                            ModelState.AddModelError("Value", "Value entered is invalid");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        else if (gameConfigurationDTO.Value.Contains("$("))
                        {
                            ModelState.AddModelError("Value", "Value entered is invalid");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        else if (gameConfigurationDTO.Value.ToLower().Contains("delete"))
                        {
                            ModelState.AddModelError("Value", "Value entered is invalid");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        break;
                    }

                    case ConfigurationG.ProbeDataType.INT:
                    {
                        int valueOutput;
                        if (!Int32.TryParse(gameConfigurationDTO.Value, out valueOutput))
                        {
                            ModelState.AddModelError("Value", "Value entered is not an integer");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        break;
                    }

                    case ConfigurationG.ProbeDataType.FLOAT:
                    {
                        double valueOutput;
                        if (!Double.TryParse(gameConfigurationDTO.Value, out valueOutput))
                        {
                            ModelState.AddModelError("Value", "Value entered is not a real");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        break;
                    }

                    case ConfigurationG.ProbeDataType.BOOLEAN:
                    {
                        if (!(gameConfigurationDTO.Value.IsCaseInsensitiveEqual("false") ||
                              gameConfigurationDTO.Value.IsCaseInsensitiveEqual("true")))
                        {
                            ModelState.AddModelError("Value", "Value entered must be true or false");
                            return(Json(ModelState.ToDataSourceResult()));
                        }
                        else
                        {
                            gameConfigurationDTO.Value = gameConfigurationDTO.Value.ToLower();
                        }
                        break;
                    }
                    }
                    ;


                    //Create a valid GameConfiguration record
                    GameConfiguration gameConfiguration = new GameConfiguration
                    {
                        ConfigurationGId = gameConfigurationDTO.ConfigurationGId,
                        GameId           = (long)gameConfigurationDTO.GameId,
                        Value            = gameConfigurationDTO.Value
                    };

                    /*
                     * First we will check if there is an existing GameConfiguration record. If not, then we will create that record. If
                     * it exists; then we will update that record.
                     */
                    if (db.GameConfiguration
                        .Where(gc => gc.ConfigurationGId == gameConfigurationDTO.ConfigurationGId && gc.GameId == gameConfigurationDTO.GameId).Count() == 0)
                    {
                        //GameConfiguration record doesn't exist; so we are going to create it.
                        db.GameConfiguration.Add(gameConfiguration);
                        db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                        gameConfigurationDTO.Id = gameConfiguration.Id;
                    }
                    else
                    {
                        //to edit an existing record; you need to seed the id with the existing PK
                        gameConfiguration.Id = (int)gameConfigurationDTO.Id;

                        db.Entry(gameConfiguration).State = EntityState.Modified;
                        db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null);
                    }
                }//if (ModelState.IsValid)

                //return Json(ModelState.ToDataSourceResult());
                return(Json(new[] { gameConfigurationDTO }.ToDataSourceResult(dsRequest, ModelState)));
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah
                ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR);
                return(Json(ModelState.ToDataSourceResult()));
            }
        }//public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, GameConfigurationDTO gameConfigurationDTO)
Example #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([...