public JsonResult Delete([DataSourceRequest] DataSourceRequest request, PlayerDTO playerDTO) { try { if (!ProbeValidate.IsGameForLoggedInUser(playerDTO.GameId)) { ModelState.AddModelError("", "Player Delete could not be accomplished"); return(Json(ModelState.ToDataSourceResult())); } if (playerDTO != null && ModelState.IsValid) { //will delete the game play submissions of the player and then the player. Player player = db.Player.Find(playerDTO.Id); ProbeGame.DeletePlayer(db, player); } return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.ToDataSourceResult())); } }//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, QuestionDTO questionDTO)
public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO) { 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.IsGameForLoggedInUser((long)gameDTO.Id)) { ModelState.AddModelError("", "Game Delete could not be accomplished"); return(Json(ModelState.ToDataSourceResult())); } ValidateGameDelete(gameDTO.Id); if (gameDTO != null && ModelState.IsValid) { db.Configuration.LazyLoadingEnabled = true; ProbeGame.DeleteGame(this, db, gameDTO.Id); } return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.ToDataSourceResult())); } }//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO)
public List <PlayerLMSSummaryReturn> GetPlayerLMSSummaryData(long gameid, string code, int playerstatusfilter) { /* * the gameid and code passed must correlate or they may be something malicious going on. so we stop * the response ASAP and throw an exception AND WE DO NOT CATCH IT, which should be picked up by Elmah. Exception handling here * have to be improved big-time */ ProbeValidate.ValidateGameCodeVersusId(gameid, code); try { //update player statuses for a game. ProbeGame.UpdateAllGamePlayerStatuses(); DateTime dateTimeNowUTC = DateTime.UtcNow; var db = new ProbeDataContext(); Game game = db.Game.Find(gameid); ProbeGame probeGame = new ProbeGame(game); //Get information about question that most recently passed the deadline and the next question after that long questionIdForMostRecentQuestion = probeGame.GetMostRecentQuestionPassedDeadline(dateTimeNowUTC); int mostRecentQuestionNbrPassed = ProbeConstants.ValueIntNone; DateTime mostRecentQuestionDeadlinePassed = DateTime.MinValue; if (questionIdForMostRecentQuestion != ProbeConstants.NoPrimaryKeyId) { mostRecentQuestionNbrPassed = probeGame.GetProbeGameQuestionDeadline(questionIdForMostRecentQuestion).QuestionNumber; mostRecentQuestionDeadlinePassed = probeGame.GetProbeGameQuestionDeadline(questionIdForMostRecentQuestion).QuestionDeadlineDT; } //NOTE: playerstatusfilter = 0 is ALL players; = 1 ACTIVE players; = 2 INACTIVE players var result = db.Database.SqlQuery <PlayerLMSSummaryData> ("exec GetPlayerLMSSummary " + gameid + ',' + playerstatusfilter).ToList(); List <PlayerLMSSummaryReturn> reportData = new List <PlayerLMSSummaryReturn>(); foreach (PlayerLMSSummaryData row in result) { PlayerLMSSummaryReturn plsr = new PlayerLMSSummaryReturn { PlayerName = row.PlayerName, PlayerId = row.PlayerId, PlayerStatus = row.PlayerStatus, PlayerGameReason = row.PlayerGameReason, QuestionNbrLastSubmitted = row.QuestionNbrLastSubmitted - 1, //convert to base 0 element MostRecentQuestionNbrDeadlinePassed = mostRecentQuestionNbrPassed, MostRecentQuestionDeadlinePassed = mostRecentQuestionDeadlinePassed }; reportData.Add(plsr); } return(reportData); } catch (Exception ex) { throw ex; } }//public PlayerLMSSummaryReturn GetPlayerLMSSummaryData(long gameid, string code)
public List <PlayerLMSDetailReturn> GetPlayerLMSSummaryData(long gameid, string code, long playerid) { /* * the gameid and code passed must correlate or they may be something malicious going on. so we stop * the response ASAP and throw an exception AND WE DO NOT CATCH IT, which should be picked up by Elmah. Exception handling here * have to be improved big-time */ ProbeValidate.ValidateGameCodeVersusId(gameid, code); try { //update player statuses for a game. ProbeGame.UpdateAllGamePlayerStatuses(); //NOTE: playerstatusfilter = 0 is ALL players; = 1 ACTIVE players; = 2 INACTIVE players var result = db.Database.SqlQuery <PlayerLMSDetailData> ("exec GetPlayerLMSDetail " + gameid + ',' + playerid).ToList(); bool firstNullSelection = true; List <PlayerLMSDetailReturn> reportData = new List <PlayerLMSDetailReturn>(); foreach (PlayerLMSDetailData row in result) { //Will serialize all selections that ARE NOT null OR (the first selection that is NULL and the PlayerGameReason is DEADLINE). That would be the question //that the player just missed the deadline on if (row.SelectedChoices != null || !row.PlayerStatus && row.SelectedChoices == null && row.PlayerGameReason == Player.PlayerGameReasonType.ANSWER_REASON_DEADLINE && firstNullSelection) { PlayerLMSDetailReturn pldr = new PlayerLMSDetailReturn { PlayerName = row.PlayerName, PlayerId = row.PlayerId, PlayerStatus = row.PlayerStatus, PlayerGameReason = row.PlayerGameReason, QuestionId = row.QuestionId, Question = row.Question, OrderNbr = row.OrderNbr, SelectedChoices = row.SelectedChoices, CorrectChoices = row.CorrectChoices }; reportData.Add(pldr); if (row.SelectedChoices == null) { firstNullSelection = false; } }//if (row.SelectedChoices != null) } return(reportData); } catch (Exception ex) { throw ex; } }//public PlayerLMSSummaryReturn GetPlayerLMSSummaryData(long gameid, string code)
}//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO) public JsonResult Clone(long id) { try { //Note: set to NOT clone the game play records (player, gameanswer). //This will clone the game, gameconfiguration, gamequestion/question/choicequestion/choice. //Will also set the cloned game as NOT published and NOT suspended bool gamePlayInd = false; bool cloneCrossUsers = false; Game clonedGame = ProbeGame.CloneGame(this, db, id, User.Identity.GetUserId(), cloneCrossUsers, gamePlayInd); NotifyProbe.NotifyGameChanged(User.Identity.Name); //let all clients know where was a game change. //The message return via an AJAX call ResultMessage resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_GameCloneSuccessful, MessageType = Helpers.Mics.MessageType.Informational, Message = @"The game <span style=""font-style:italic;font-weight:bold"">" + db.Game.Find(id).Name + @"</span> has been cloned successfully to game <span style=""font-style:italic;font-weight:bold"">" + clonedGame.Name + @"</span>" }; return(Json(resultMessage, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah //The message return via an AJAX call ResultMessage resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_UnsuccessfulOperation, MessageType = Helpers.Mics.MessageType.Error, Message = "The was an error when attempting to clone the game '" + db.Game.Find(id).Name + "'. " + ex.Message }; return(Json(resultMessage, JsonRequestBehavior.AllowGet)); } } //public JsonResult Clone(long id)
} //public JsonResult Clone(long id) public JsonResult CloneToUser(long id, string userid) { try { //Note: set to clone the game play records (player and gameanwer). This //will clone the entire game (all props), gameconfiguration, gamequestion/question/choicequestion/choice; player,gameanswer //It will be a ready for play in the destination user account Game clonedGame = ProbeGame.CloneGameFromAnotherUser(this, db, id, userid); NotifyProbe.NotifyGameChanged(User.Identity.Name); //let all clients know where was a game change. //The message return via an AJAX call ResultMessage resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_GameCloneSuccessful, MessageType = Helpers.Mics.MessageType.Informational, Message = @"The game <span style=""font-style:italic;font-weight:bold"">" + db.Game.Find(id).Name + @"</span> has been cloned successfully to game <span style=""font-style:italic;font-weight:bold"">" + clonedGame.Name + @"</span>" + @" in the user account <span style=""font-style:italic;font-weight:bold"">" + new ProbeIdentity().GetUserNameFromUserId(userid) + @"</span>" }; return(Json(resultMessage, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah //The message return via an AJAX call ResultMessage resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_UnsuccessfulOperation, MessageType = Helpers.Mics.MessageType.Error, Message = "The was an error when attempting to clone the game '" + db.Game.Find(id).Name + "'. " + ex.Message }; return(Json(resultMessage, JsonRequestBehavior.AllowGet)); } } //public JsonResult CloneToUser(long id)
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([...
}//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO) //MNS - Not being used at the moment 8/28/15 public JsonResult DeleteStandAlone(long id) { ResultMessage resultMessage; string gameName = db.Game.Find(id).Name; 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.IsGameForLoggedInUser(id)) { //The message return via an AJAX call resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_UnsuccessfulOperation, MessageType = Helpers.Mics.MessageType.Informational, Message = @"Game Delete could not be accomplished." }; return(Json(resultMessage, JsonRequestBehavior.AllowGet)); }// if (!ProbeValidate.IsGameForLoggedInUser(id)) ValidateGameDelete(id); db.Configuration.LazyLoadingEnabled = true; ProbeGame.DeleteGame(this, db, id); //The message return via an AJAX call resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_GameDeleteSuccessful, MessageType = Helpers.Mics.MessageType.Informational, Message = @"The game <span style=""font-style:italic;font-weight:bold"">" + gameName + @"</span> has been deleted successfully." }; } catch (GameIsActiveException) { //The message that the calling RAZOR can use resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_GameHasPlayers, MessageType = Helpers.Mics.MessageType.Error, Message = @"The game <span style=""font-style:italic;font-weight:bold"">" + gameName + @"</span> cannot be deleted because it is currently active or has players that have submitted." }; } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah //The message return via an AJAX call resultMessage = new ResultMessage { MessageId = ProbeConstants.MSG_UnsuccessfulOperation, MessageType = Helpers.Mics.MessageType.Error, Message = "The was an error when attempting to delete the game '" + gameName + "'. " + ex.Message }; } return(Json(resultMessage, JsonRequestBehavior.AllowGet)); }//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO gameDTO)
public JsonResult GetGameSchedules([DataSourceRequest] DataSourceRequest request, long gameid) { try { Game game = db.Game.Find(gameid); ProbeGame probeGame = new ProbeGame(game); int nbrQuestions = game.GameQuestions.Count(); int nbrPlayers = game.Players.Count(); IList <GameQuestionScheduleDTO> gameQuestionScheduleDTOs = new List <GameQuestionScheduleDTO>(); DateTime gameLocalStartDate = ClientTimeZoneHelper.ConvertToLocalTime(game.StartDate, false); DateTime gameLocalEndDate = ClientTimeZoneHelper.ConvertToLocalTime(game.EndDate, false); //override set to true, because this date will be serialized/stringified on the server side DateTime gameLocalEndDateforServer = ClientTimeZoneHelper.ConvertToLocalTime(game.EndDate, true); string specificStartScheduleDesc = string.Empty; switch ((ProbeGameType)game.GameTypeId) { case ProbeGameType.Match: case ProbeGameType.Test: if (game.Published && !game.SuspendMode) { specificStartScheduleDesc = "At this time game is active. Players can use their game code to play game and submit their answers up to the game end date (" + gameLocalEndDateforServer.ToString() + "). Game configuration cannot be changed, questions cannot be added or removed, and players cannot be edited or removed." + " There are " + nbrQuestions + " question(s) to be answered for this game." + " There are " + nbrPlayers + " players(s) that have or are playing this game."; } else if (nbrQuestions == 0) { specificStartScheduleDesc = "At this time, game is inactive. The game organizer must add questions to this game from the Question Library (Questions button), set any specifc game configurations (Config button)," + " publish (Publish button), and then distribute the game code to all the players"; } else { specificStartScheduleDesc = "At this time, game is inactive. Players cannot find game with a game code nor can they submit their answers." + " There are " + nbrQuestions + " question(s) to be answered for this game." + " There are " + nbrPlayers + " players(s) that have or are playing this game."; } break; case ProbeGameType.LMS: if (game.Published && !game.SuspendMode) { specificStartScheduleDesc = "At this time, game is active. At this time, players can use their game code to play game or submit an answer to the next LMS question up to the game end date (" + gameLocalEndDateforServer.ToString() + "). Game configuration cannot be changed, questions cannot be added or removed, and players cannot be edited or removed." + " There are " + nbrQuestions + "question(s) to be answered for this game." + " There are " + nbrQuestions + "players(s) that have or are playing this game."; } else if (nbrQuestions == 0) { specificStartScheduleDesc = "At this time, game is inactive. The game organizer must add questions to this game from the Question Library (Questions button), set any specifc game configurations (Config button)," + " publish (Publish button), and then distribute the game code to all the players"; } else { specificStartScheduleDesc = "Game is inactive. Players cannot find game with the game code nor can they submit an answer to the next LMS question." + " There are " + nbrQuestions + "question(s) to be answered for this game." + " There are " + nbrQuestions + "players(s) that have or are playing this game."; } break; } GameQuestionScheduleDTO gameQuestionScheduleStartDTO = new GameQuestionScheduleDTO { Id = 0, ScheduleName = "Game Start", ScheduleDesc = "Game Start. The game status is " + ((game.Published) ? "published" : "not published") + ((game.SuspendMode) ? "(suspended)" : "") + ". " + specificStartScheduleDesc, StartDate = gameLocalStartDate, InterimDate = gameLocalStartDate, EndDate = gameLocalStartDate }; gameQuestionScheduleDTOs.Add(gameQuestionScheduleStartDTO); //For the LMS games, there are individual question schedules if (game.GameTypeId == (long)ProbeGameType.LMS) { IList <ProbeGameQuestionDeadline> probeGameQuestionDeadlines = probeGame.ProbeGameQuestionDeadlines; foreach (ProbeGameQuestionDeadline pgqd in probeGameQuestionDeadlines) { ChoiceQuestion choiceQuestion = db.ChoiceQuestion.Find(pgqd.QuestionId); GameQuestionScheduleDTO gameQuestionScheduleDTO = new GameQuestionScheduleDTO { Id = 0, ScheduleName = "Question #" + pgqd.QuestionNumber, ScheduleDesc = "Question " + choiceQuestion.Name + ". Text: " + choiceQuestion.Text, //". The start date defines when question will be available to a player to answer." + //" The end date defines when question must be answered by a player." + //" The warning date defines when a warning message is displayed to a player that a question deadline is approaching.", GameId = gameid, QuestionId = pgqd.QuestionId, //StartDate = pgqd.QuestionStartDT, //InterimDate = pgqd.QuestionWarningDT, //EndDate = pgqd.QuestionDeadlineDT, //TimeSpanString = ConvertTimeSpanToString(pgqd.QuestionDeadlineDT.Subtract(pgqd.QuestionStartDT)) /* WHEN WE PASS A LIST TO KENDO GRID - IT TAKES CARE OF CONVERTING UTC DATE TO LOCAL */ StartDate = ClientTimeZoneHelper.ConvertToLocalTime(pgqd.QuestionStartDT, false), InterimDate = ClientTimeZoneHelper.ConvertToLocalTime(pgqd.QuestionWarningDT, false), EndDate = ClientTimeZoneHelper.ConvertToLocalTime(pgqd.QuestionDeadlineDT, false), TimeSpanString = ConvertTimeSpanToString( ClientTimeZoneHelper.ConvertToLocalTime(pgqd.QuestionDeadlineDT, false).Subtract(ClientTimeZoneHelper.ConvertToLocalTime(pgqd.QuestionStartDT, false))) }; gameQuestionScheduleDTOs.Add(gameQuestionScheduleDTO); } //foreach (ProbeGameQuestionDeadline pgqd in probeGameQuestionDeadlines) } //if (game.GameTypeId == (long)ProbeGameType.LMS) GameQuestionScheduleDTO gameQuestionScheduleEndDTO = new GameQuestionScheduleDTO { Id = 0, ScheduleName = "Game End", ScheduleDesc = "Game End. The game will become inactive", StartDate = gameLocalEndDate, InterimDate = gameLocalEndDate, EndDate = gameLocalEndDate }; gameQuestionScheduleDTOs.Add(gameQuestionScheduleEndDTO); return(this.Json(gameQuestionScheduleDTOs.ToDataSourceResult(request), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.ToDataSourceResult())); } }//public JsonResult GetGameSchedule([DataSourceRequest]DataSourceRequest request, long gameid)
public GameLMSSummaryReturn GetGameLMSSummaryData(long gameid, string code) { /* * the gameid and code passed must correlate or they may be something malicious going on. so we stop * the response ASAP and throw an exception AND WE DO NOT CATCH IT, which should be picked up by Elmah. Exception handling here * have to be improved big-time */ ProbeValidate.ValidateGameCodeVersusId(gameid, code); try { DateTime dateTimeNowUTC = DateTime.UtcNow; var db = new ProbeDataContext(); Game game = db.Game.Find(gameid); ProbeGame probeGame = new ProbeGame(game); //update player statuses for a game. ProbeGame.UpdateAllGamePlayerStatuses(game, dateTimeNowUTC); //Get information about question that most recently passed the deadline and the next question after that long questionIdForMostRecentQuestion = probeGame.GetMostRecentQuestionPassedDeadline(dateTimeNowUTC); if (questionIdForMostRecentQuestion != ProbeConstants.NoPrimaryKeyId) { int mostRecentQuestionNbrPassed = probeGame.GetProbeGameQuestionDeadline(questionIdForMostRecentQuestion).QuestionNumber; DateTime mostRecentQuestionDeadlinePassed = probeGame.GetProbeGameQuestionDeadline(questionIdForMostRecentQuestion).QuestionDeadlineDT; string mostRecentQuestionNameDeadlinePassed = db.Question.Find(questionIdForMostRecentQuestion).Name; int nextQuestionNbr = (mostRecentQuestionNbrPassed + 1 <= probeGame.ProbeGameQuestionDeadlines.Count) ? mostRecentQuestionNbrPassed + 1 : mostRecentQuestionNbrPassed; ProbeGameQuestionDeadline nextpgqd = probeGame.ProbeGameQuestionDeadlines.Where(pgqd => pgqd.QuestionNumber == nextQuestionNbr).FirstOrDefault(); DateTime nextQuestionDeadline = nextpgqd.QuestionDeadlineDT; string nextQuestionName = db.Question.Find(nextpgqd.QuestionId).Name; int gameNbrQuestions = probeGame.Game.GameQuestions.Count(); mostRecentQuestionNbrPassed--; //calibrate to element 0 base. it was at element 1 base nextQuestionNbr--; //calibrate to element 0 base. it was at element 1 base //Will return -1 if there are no questions submitted yet int maxQuestionNbrSubmitted = probeGame.GetMaxQuestionNbrSubmitted(); GameStatusType gameStatusType = GameStatusType.UNKNOWN; if (ProbeValidate.IsGameStartPassed(game) && (mostRecentQuestionNbrPassed < probeGame.ProbeGameQuestionDeadlines.Count - 1)) { gameStatusType = GameStatusType.ACTIVE; } else { gameStatusType = GameStatusType.COMPLETED; } GameLMSSummaryReturn gsdr = new GameLMSSummaryReturn { GameStatus = gameStatusType, GameNbrQuestions = gameNbrQuestions, NbrPlayers = probeGame.NbrPlayers, NbrPlayersActive = probeGame.NbrPlayersActive, NbrPlayersInactive = probeGame.NbrPlayers - probeGame.NbrPlayersActive, MostRecentQuestionNbrDeadlinePassed = mostRecentQuestionNbrPassed, MostRecentQuestionNameDeadlinePassed = mostRecentQuestionNameDeadlinePassed, MostRecentQuestionDeadlinePassed = mostRecentQuestionDeadlinePassed, NextQuestionNbr = nextQuestionNbr, NextQuestionName = nextQuestionName, NextQuestionDeadline = nextQuestionDeadline, MaxQuestionNbrSubmitted = maxQuestionNbrSubmitted }; return(gsdr); } else { //IF WE ARE HERE THAT MEANS THAT THE FIRST QUESTION DEADLINE OF THE GAME HAS NOT PASSED. //We send back a reduced set of information when the game is not active and it hasn't even started int gameNbrQuestions = probeGame.Game.GameQuestions.Count(); GameStatusType gameStatusType = GameStatusType.UNKNOWN; int mostRecentQuestionNbrPassed = ProbeConstants.ValueIntNone; string mostRecentQuestionNameDeadlinePassed = ProbeConstants.ValueStringNone; DateTime mostRecentQuestionDeadlinePassed = DateTime.MinValue; int nextQuestionNbr = ProbeConstants.ValueIntNone; string nextQuestionName = ProbeConstants.ValueStringNone; DateTime nextQuestionDeadline = DateTime.MinValue; if (ProbeValidate.IsGameStartPassed(game)) { //no most recent question deadline passed. However there is a next question deadline (first question //of the game gameStatusType = GameStatusType.STARTEDNOQUESTIONPASSED; nextQuestionNbr = 0; nextQuestionDeadline = probeGame.ProbeGameQuestionDeadlines[0].QuestionDeadlineDT; nextQuestionName = db.Question.Find(probeGame.ProbeGameQuestionDeadlines[0].QuestionId).Name; } else { gameStatusType = GameStatusType.NOTSTARTED; } int maxQuestionNbrSubmitted = probeGame.GetMaxQuestionNbrSubmitted(); GameLMSSummaryReturn gsdr = new GameLMSSummaryReturn { //We will provide information about any players that have submitted already even if the first question's deadline hasn't been reached. GameStatus = gameStatusType, GameNbrQuestions = gameNbrQuestions, NbrPlayers = probeGame.NbrPlayers, NbrPlayersActive = probeGame.NbrPlayersActive, NbrPlayersInactive = probeGame.NbrPlayers - probeGame.NbrPlayersActive, MostRecentQuestionNbrDeadlinePassed = mostRecentQuestionNbrPassed, MostRecentQuestionNameDeadlinePassed = mostRecentQuestionNameDeadlinePassed, MostRecentQuestionDeadlinePassed = mostRecentQuestionDeadlinePassed, NextQuestionNbr = nextQuestionNbr, NextQuestionName = nextQuestionName, NextQuestionDeadline = nextQuestionDeadline, MaxQuestionNbrSubmitted = maxQuestionNbrSubmitted }; return(gsdr); } } catch (Exception ex) { throw ex; } }//public GameLMSSummaryReturn