PageRenderTime 4ms CodeModel.GetById 7ms app.highlight 80ms RepoModel.GetById 1ms app.codeStats 1ms

/src/Diversity.Data/DataAccess/SqlServer/SqlGameRepository.cs

https://bitbucket.org/symmetrateam/echallengeapi
C# | 1647 lines | 1341 code | 284 blank | 22 comment | 297 complexity | 99c3a5ea0647f9e640d042ab1c266323 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1using System;
   2using System.Collections.Generic;
   3using System.Data;
   4using System.Data.Entity;
   5using System.Data.Linq;
   6using System.Diagnostics;
   7using System.IO;
   8using System.Linq;
   9using System.Runtime.Serialization;
  10using System.Text;
  11using System.Web.Configuration;
  12using System.Xml;
  13using System.Xml.Linq;
  14using Diversity.Common;
  15using Diversity.DataModel.SqlRepository;
  16using Diversity.Common.Enumerations;
  17using Diversity.Data.Utility;
  18using Diversity.Domain.Model;
  19using log4net;
  20using Card = Diversity.Domain.Model.Card;
  21using Client = Diversity.Domain.Model.Client;
  22using Game = Diversity.Domain.Model.Game;
  23using FlashAsset = Diversity.Domain.Model.FlashAsset;
  24
  25namespace Diversity.Data.DataAccess.SqlServer
  26{
  27    public partial class SqlGameRepository : SqlRepository, IGameRepository
  28    {
  29        private static readonly ILog _log = LogManager.GetLogger((System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
  30
  31        public Game GetGame(int gameId, int languageId, Guid userId)
  32        {
  33            var game = GetGameById(languageId, gameId, userId);
  34            return game;
  35        }
  36
  37        public bool CanNewGameBePlayedByUser(int gameId, int languageId, Guid userId)
  38        {
  39            var dbGame = (from g in DataContext.Games
  40                          where g.GameID == gameId
  41                          select g).FirstOrDefault();
  42
  43            if(dbGame == null)
  44            {
  45                return false;
  46            }
  47
  48            if(dbGame.NumberOfTimesGameCanBePlayed == 0 || 
  49                (dbGame.GameID_Template.HasValue && GetGameIdForInProgressGame(gameId,userId).HasValue))
  50            {
  51                return true;
  52            }
  53
  54            var gameCount = (from g in DataContext.Games
  55                             where g.GameID_Template == gameId
  56                                   && g.UserID_CreatedBy == userId && !g.IsADeletedRow && !g.IsAnAuditRow
  57                             select g).Count();
  58
  59            return !(gameCount > dbGame.NumberOfTimesGameCanBePlayed);
  60        }
  61
  62        public IQueryable<FlashAsset> GetFlashAssets(int languageId)
  63        {
  64            var assets = from f in DataContext.FlashAssets
  65                   join l in DataContext.FlashAsset_Languages on f.FlashAssetID equals l.FlashAssetID
  66                   where l.LanguageID == languageId
  67                   select new 
  68                              {
  69                                  Name = f.Key,
  70                                  l.Value,
  71                                  Lcid = l.Language.LCID
  72                              };
  73
  74            var results = (from a in assets
  75                           select new FlashAsset()
  76                                      {
  77                                          Name = a.Name,
  78                                          Value = a.Value,
  79                                          Lcid = a.Lcid
  80                                      });
  81
  82            return results;
  83        }
  84
  85        public int? GetGameIdForInProgressGame(int gameTemplateId, Guid userId)
  86        {
  87            var gamePlayer = DataContext.GamePlayers
  88                .FirstOrDefault
  89                (
  90                    p =>
  91                    p.UserID == userId && !p.IsAvatar && p.Game.GameID_Template == gameTemplateId &&
  92                    p.Game.GameCompletionDate == null
  93                );
  94                       
  95            if(gamePlayer == null)
  96            {
  97                return null;
  98            }
  99
 100            return gamePlayer.GameID;
 101        }
 102
 103        DataModel.SqlRepository.Game DuplicateGameFromTemplate(Game templateGame, Guid userId, int languageId, bool lockDownTemplate)
 104        {
 105            var currentDateTime = DateTime.Now;
 106            var duplicateGame = new DataModel.SqlRepository.Game();
 107
 108            duplicateGame.UserID_CreatedBy = userId;
 109            duplicateGame.UserID_LastModifiedBy = userId;
 110            duplicateGame.CreatedOnDateTime = currentDateTime;
 111            duplicateGame.LastModifiedOnDateTime = currentDateTime;
 112            duplicateGame.GameID_Template = templateGame.Id;
 113            duplicateGame.IsOnlineGame = templateGame.GameSettings.IsOnline;
 114            duplicateGame.GameNowLockedDown = lockDownTemplate;
 115            duplicateGame.GameConfigCanBeModifiedAcrossInstances =
 116                templateGame.GameSettings.GameConfigCanBeModifiedAcrossInstances;
 117            duplicateGame.IsTimedGame = templateGame.GameSettings.IsTimed;
 118            duplicateGame.UseCardTime = templateGame.GameSettings.UseCardTime;
 119            duplicateGame.UseActualAvatarNames = templateGame.AvatarSettings.UseActualName;
 120            duplicateGame.UseHistoricAvatarAnswers = templateGame.AvatarSettings.UseHistoricAnswers;
 121            duplicateGame.UseActualAvatarAnsweringTimes = templateGame.AvatarSettings.UseActualAnsweringTimes;
 122            duplicateGame.AllUsersMustFinishThisGameByThisDate =
 123                templateGame.GameSettings.AllUsersMustFinishThisGameBy;
 124            duplicateGame.PlayerTurn_RandomNoRepeatingUntilAllHavePlayed =
 125                templateGame.PlayerTurnSettings.RandomNoRepeatingUntilAllHavePlayed;
 126            duplicateGame.PlayerTurn_ByPlayerSequenceNoElseRandom =
 127                templateGame.PlayerTurnSettings.BySequenceNoElseRandom;
 128            duplicateGame.DefaultGameTimeInSeconds = templateGame.GameSettings.DefaultGameTimeInSeconds;
 129            duplicateGame.GameThemeData = templateGame.GameSettings.GameThemeData;
 130            duplicateGame.CanSkipTutorial = templateGame.GameSettings.CanSkipTutorial;
 131            duplicateGame.GameTemplateNameForDashboard = templateGame.GameSettings.GameTemplateNameForDashboard;
 132            duplicateGame.ExternalID = templateGame.CourseCode;
 133
 134            //set values here to create a new instance game
 135            duplicateGame.HasBeenDownloaded = true;
 136            duplicateGame.NumberOfTimesRun = 1;
 137            duplicateGame.GameStartDate = DateTime.Now;
 138            duplicateGame.IsAGameTemplate = false;
 139            duplicateGame.GameCompletionDate = null;
 140
 141            duplicateGame.ProductID = templateGame.ProductId;
 142
 143            //add the real game player to the game
 144            var gamePlayer = new GamePlayer();
 145            gamePlayer.CreatedOnDateTime = currentDateTime;
 146            gamePlayer.IsAvatar = false;
 147            gamePlayer.LastModifiedOnDateTime = currentDateTime;
 148            gamePlayer.UserID = userId;
 149            gamePlayer.UserID_CreatedBy = userId;
 150            gamePlayer.UserID_LastModifiedBy = userId;
 151
 152            duplicateGame.GamePlayers.Add(gamePlayer);
 153
 154            foreach (var cardGroup in templateGame.CardGroups)
 155            {
 156                var duplicateCardGroupSequence = new GameCardGroupSequence();
 157                duplicateCardGroupSequence.CardGroupSequenceNo = cardGroup.CardGroupSequenceNo;
 158                duplicateCardGroupSequence.GameID = duplicateGame.GameID;
 159                duplicateCardGroupSequence.IsAMandatoryCardGroup = cardGroup.IsMandatoryGroup;
 160                duplicateCardGroupSequence.CreatedOnDateTime = currentDateTime;
 161                duplicateCardGroupSequence.LastModifiedOnDateTime = currentDateTime;
 162                duplicateCardGroupSequence.UserID_CreatedBy = userId;
 163                duplicateCardGroupSequence.UserID_LastModifiedBy = userId;
 164
 165                foreach (Card card in cardGroup.Cards)
 166                {
 167                    var duplicateGameCardSequence = new GameCardSequence();
 168                    duplicateGameCardSequence.CardID = card.Id;
 169                    duplicateGameCardSequence.CardSequenceNo = card.CardSequenceNo;
 170                    duplicateGameCardSequence.CardViewedInGame = false;
 171                    duplicateGameCardSequence.CardViewedInGameOn = null;
 172                    duplicateGameCardSequence.GameCardGroupSequenceID =
 173                        duplicateCardGroupSequence.GameCardGroupSequenceID;
 174                    duplicateGameCardSequence.IsAMandatoryCard = card.IsAMandatoryCard;
 175                    duplicateGameCardSequence.UseLongVersion = card.UseLongVersion;
 176
 177                    duplicateGameCardSequence.CreatedOnDateTime = currentDateTime;
 178                    duplicateGameCardSequence.LastModifiedOnDateTime = currentDateTime;
 179                    duplicateGameCardSequence.UserID_CreatedBy = userId;
 180                    duplicateGameCardSequence.UserID_LastModifiedBy = userId;
 181
 182                    duplicateCardGroupSequence.GameCardSequences.Add(duplicateGameCardSequence);
 183                }
 184
 185                duplicateGame.GameCardGroupSequences.Add(duplicateCardGroupSequence);
 186            }
 187
 188            return duplicateGame;
 189        }
 190
 191        List<DataModel.SqlRepository.Game> GetSimulatedPlayerGames(Game templateGame, int languageId, bool lockDownTemplate)
 192        {
 193            var player1 =
 194                DataContext.Users.FirstOrDefault(u => u.LoweredUserName == ConfigurationHelper.SystemPlayer1.ToLower());
 195
 196            var player1Game = DuplicateGameFromTemplate(templateGame, player1.UserId, languageId, lockDownTemplate);            
 197
 198            var player2 =
 199                DataContext.Users.FirstOrDefault(u => u.LoweredUserName == ConfigurationHelper.SystemPlayer2.ToLower());
 200
 201            var player2Game = DuplicateGameFromTemplate(templateGame, player2.UserId, languageId, lockDownTemplate);
 202
 203            var player3 =
 204                DataContext.Users.FirstOrDefault(u => u.LoweredUserName == ConfigurationHelper.SystemPlayer3.ToLower());
 205
 206            var player3Game = DuplicateGameFromTemplate(templateGame, player3.UserId, languageId, lockDownTemplate);
 207
 208            var results = new List<DataModel.SqlRepository.Game>();
 209            results.Add(player1Game);
 210            results.Add(player2Game);
 211            results.Add(player3Game);
 212            return results;
 213        }
 214
 215        List<Result> GetSimulatedAnswersForGame(DataModel.SqlRepository.Game game, Guid lastModifiedByUserId)
 216        {
 217            var results = new List<Result>();
 218
 219            var avatar = game.GamePlayers.FirstOrDefault();
 220
 221            foreach(var cardSequence in game.GameCardGroupSequences.SelectMany(c=>c.GameCardSequences))
 222            {
 223                var card = DataContext.Cards.FirstOrDefault(c=>c.CardID == cardSequence.CardID);
 224
 225                if(card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleChoiceQuestionCard)) ||
 226                    card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleChoiceImageQuestionCard)) ||
 227                    card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleChoiceAuditStatementCard)) ||
 228                    card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleChoiceAuditStatementImageCard))
 229                    )
 230                {
 231                    var random = new Random();
 232
 233                    var answerNo = random.Next(1, card.QuestionCard.QuestionCard_GeneralAnswers.Count);
 234                    var answers = card.QuestionCard.QuestionCard_GeneralAnswers.ToList();
 235
 236                    var timeToAnswer = card.CardMaxTimeToAnswerInSeconds > 0
 237                                           ? random.Next(1, card.CardMaxTimeToAnswerInSeconds)
 238                                           : 0;                                       
 239
 240                    var playerResult = new MultipleChoicePlayerResult()
 241                                           {
 242                                               AnswerId = answers[answerNo].QuestionCard_GeneralAnswerID,
 243                                               PlayerId = avatar.UserID,
 244                                               TimeTakenToAnswerInSeconds = timeToAnswer
 245                                           };
 246
 247                    var xml = SerializeObject(playerResult);
 248
 249                    if(string.IsNullOrEmpty(xml))
 250                    {
 251                        continue;
 252                    }
 253
 254                    var resultXml = XElement.Parse(xml);
 255
 256
 257                    var currentDateTime = DateTime.Now;
 258                    var result = new Result()
 259                    {
 260                        CardID = card.CardID,
 261                        CreatedOnDateTime = currentDateTime,
 262                        GameID = game.GameID,
 263                        Internal_CardTypeID = card.Internal_CardTypeID,
 264                        LastModifiedOnDateTime = currentDateTime,
 265                        ResultType = resultXml.Name.LocalName,
 266                        ResultXmlElement = resultXml,
 267                        UserID_CreatedBy = lastModifiedByUserId,
 268                        UserID_LastModifiedBy = lastModifiedByUserId
 269                    };
 270                    
 271                    results.Add(result);
 272                }
 273                else if (card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MatchingListQuestionCard)))
 274                {
 275                    var random = new Random();
 276                    
 277                    var answers = card.QuestionCard.QuestionCard_GeneralAnswers.ToList();
 278
 279                    var timeToAnswer = card.CardMaxTimeToAnswerInSeconds > 0
 280                                          ? random.Next(1, card.CardMaxTimeToAnswerInSeconds)
 281                                          : 0;
 282
 283                    var playerResult = new MatchingListPlayerResult()
 284                    {
 285                        PlayerId = avatar.UserID,
 286                        TimeTakenToAnswerInSeconds = timeToAnswer,
 287                        Results = new MatchingListPlayerResultAnswer[answers.Count]
 288                    };
 289
 290                    int rhAnswerNo;
 291                    int lhAnswerNo;
 292
 293                    for (int i = 0; i < playerResult.Results.Count; i++)
 294                    {
 295                        rhAnswerNo = random.Next(0, answers.Count);
 296                        lhAnswerNo = random.Next(0, answers.Count);
 297
 298                        playerResult.Results[i] = new MatchingListPlayerResultAnswer()
 299                                                  {
 300                                                      AnswerSequenceNo = 0,
 301                                                      RHAnswerId = answers[rhAnswerNo].QuestionCard_GeneralAnswerID,
 302                                                      LHAnswerId = answers[lhAnswerNo].QuestionCard_GeneralAnswerID
 303                                                  };
 304                    }
 305
 306                    var xml = SerializeObject(playerResult);
 307
 308                    if (string.IsNullOrEmpty(xml))
 309                    {
 310                        continue;
 311                    }
 312
 313                    var resultXml = XElement.Parse(xml);
 314
 315                    var currentDateTime = DateTime.Now;
 316                    var result = new Result()
 317                    {
 318                        CardID = card.CardID,
 319                        CreatedOnDateTime = currentDateTime,
 320                        GameID = game.GameID,
 321                        Internal_CardTypeID = card.Internal_CardTypeID,
 322                        LastModifiedOnDateTime = currentDateTime,
 323                        ResultType = resultXml.Name.LocalName,
 324                        ResultXmlElement = resultXml,
 325                        UserID_CreatedBy = lastModifiedByUserId,
 326                        UserID_LastModifiedBy = lastModifiedByUserId
 327                    };
 328
 329                    results.Add(result);
 330
 331                }
 332                else if (card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleCheckBoxQuestionCard)) ||
 333                    card.Internal_CardType.Internal_CardTypeShortCode.Equals(Enum.GetName(typeof(CardType), CardType.MultipleCheckBoxImageQuestionCard)))
 334                {
 335                    var random = new Random();
 336
 337                    var answers = card.QuestionCard.QuestionCard_GeneralAnswers.Where(c => c.IsCorrectAnswer).ToList();
 338
 339                    var timeToAnswer = card.CardMaxTimeToAnswerInSeconds > 0
 340                                           ? random.Next(1, card.CardMaxTimeToAnswerInSeconds)
 341                                           : 0;
 342
 343                    var playerResult = new MultipleCheckBoxPlayerResult()
 344                    {
 345                        PlayerId = avatar.UserID,
 346                        TimeTakenToAnswerInSeconds = timeToAnswer,
 347                        Results = new MultipleCheckBoxPlayerResultAnswer[answers.Count]
 348                    };
 349
 350                    for (int i = 0; i < playerResult.Results.Count; i++)
 351                    {
 352                        var answerNo = random.Next(0, answers.Count);
 353
 354                        playerResult.Results[i] = new MultipleCheckBoxPlayerResultAnswer()
 355                        {
 356                            AnswerId = answers[answerNo].QuestionCard_GeneralAnswerID
 357                        };
 358                    }
 359
 360                    var xml = SerializeObject(playerResult);
 361
 362                    if (string.IsNullOrEmpty(xml))
 363                    {
 364                        continue;
 365                    }
 366
 367                    var resultXml = XElement.Parse(xml);
 368
 369
 370                    var currentDateTime = DateTime.Now;
 371                    var result = new Result()
 372                    {
 373                        CardID = card.CardID,
 374                        CreatedOnDateTime = currentDateTime,
 375                        GameID = game.GameID,
 376                        Internal_CardTypeID = card.Internal_CardTypeID,
 377                        LastModifiedOnDateTime = currentDateTime,
 378                        ResultType = resultXml.Name.LocalName,
 379                        ResultXmlElement = resultXml,
 380                        UserID_CreatedBy = lastModifiedByUserId,
 381                        UserID_LastModifiedBy = lastModifiedByUserId
 382                    };
 383
 384                    results.Add(result);
 385                }
 386            }
 387            return results;
 388        }
 389
 390        static string SerializeObject<T>(T source)
 391        {
 392            using (var stream = new MemoryStream())
 393            {
 394                var serializer = new DataContractSerializer(typeof(T));
 395                serializer.WriteObject(stream, source);
 396                return System.Text.Encoding.UTF8.GetString(stream.ToArray());
 397            }
 398        }
 399
 400
 401        public Game CreateGameFromTemplateGame(Game templateGame, Guid userId, int languageId, bool lockDownTemplate)
 402        {
 403            //select random players for avatars
 404            var avatars = GetRandomAvatarsForOnlineGame(templateGame.Id, userId);
 405
 406            //first check if there are any avatars available
 407            //if no avatars available for template game then the system
 408            //avatars need to be used to simulate playing the game               
 409            var createdGameId = -1;
 410            var currentDateTime = DateTime.Now;
 411            using (var dataContext = new EChallengeDataContext())
 412            {
 413                var duplicateGame = DuplicateGameFromTemplate(templateGame, userId, languageId, lockDownTemplate);
 414
 415                var gameInvite =
 416                    dataContext.GameInvites.FirstOrDefault(c => c.UserID == userId && c.GameID == templateGame.Id);
 417
 418                if (gameInvite != null)
 419                {
 420                    duplicateGame.ThemeClientUserGroupExternalID = gameInvite.ThemeClientUserGroupExternalID;
 421                }
 422
 423                dataContext.Games.Add(duplicateGame);               
 424            
 425                if (avatars.Count <= 0)
 426                {
 427                    var games = GetSimulatedPlayerGames(templateGame, languageId, lockDownTemplate);
 428                    
 429
 430                    foreach (var game in games)
 431                    {
 432                        var currentPlayer = game.GamePlayers.FirstOrDefault();
 433                        var player = new GamePlayer()
 434                                             {
 435                                                 UserID = currentPlayer.UserID,
 436                                                 IsAvatar = true
 437                                             };
 438                        avatars.Add(player);               
 439
 440                        foreach (var result in GetSimulatedAnswersForGame(game,userId))
 441                        {
 442                            result.GamePlayer = player;
 443                            game.Results.Add(result);
 444                        }
 445
 446                        game.GameCompletionDate = DateTime.Now;
 447                        dataContext.Games.Add(game);                                                            
 448                    }                                       
 449                }
 450
 451                var gamePlayer = duplicateGame.GamePlayers.FirstOrDefault();
 452
 453                //now fill populate other information for avatars;
 454                foreach (var avatar in avatars)
 455                {
 456                    avatar.IsAvatar = true;
 457                    avatar.GameID = duplicateGame.GameID;
 458                    avatar.CreatedOnDateTime = currentDateTime;
 459                    avatar.UserID_CreatedBy = userId;
 460                    avatar.LastModifiedOnDateTime = currentDateTime;
 461                    avatar.UserID_LastModifiedBy = userId;
 462                }
 463
 464                //generate random player sequences for avatar and player
 465                avatars.Add(gamePlayer);
 466
 467                var shuffleAvatars = avatars.OrderBy(a => Guid.NewGuid()).ToList();
 468                for (var i = 0; i < shuffleAvatars.Count(); i++)
 469                {
 470                    var player = shuffleAvatars[i];
 471                    player.PlayerTurnSequenceNo = i + 1;
 472                }
 473
 474                if (shuffleAvatars.Count > 0)
 475                {
 476                    foreach (var shuffleAvatar in shuffleAvatars.Where(a => a.IsAvatar))
 477                    {
 478                        duplicateGame.GamePlayers.Add(shuffleAvatar);
 479                    }
 480
 481                    var player = shuffleAvatars.FirstOrDefault(a => a.UserID == gamePlayer.UserID);
 482                    gamePlayer.PlayerTurnSequenceNo = player.PlayerTurnSequenceNo;
 483
 484                    var list = duplicateGame.GamePlayers.ToList();
 485                }
 486
 487                using (var transaction = dataContext.Database.BeginTransaction())
 488                {
 489                    //as a new game is now based of the template game we need to lock down the template
 490                    var currentTemplateGame = dataContext.Games.FirstOrDefault(g => g.GameID == templateGame.Id);
 491                    currentTemplateGame.GameNowLockedDown = lockDownTemplate;
 492
 493                    try
 494                    {
 495                        dataContext.SaveChanges();
 496                        transaction.Commit();
 497                        createdGameId = duplicateGame.GameID;
 498                    }
 499                    catch (Exception)
 500                    {
 501                        transaction.Rollback();
 502                        throw;
 503                    }                    
 504                }
 505            }
 506
 507            var createdGame = GetGame(createdGameId, languageId, userId);
 508            createdGame.IsResumed = false;
 509            return createdGame;
 510        }
 511
 512        public bool SaveResult(Guid userId, int cardSequenceId, string resultType, XElement resultXml)
 513        {
 514            var saved = false;
 515
 516            using (var dataContext = new EChallengeDataContext())
 517            {
 518                var cardSequence =
 519                    dataContext.GameCardSequences.FirstOrDefault(s => s.GameCardSequenceID == cardSequenceId);
 520
 521                if (cardSequence == null)
 522                {
 523                    return false;
 524                }
 525
 526                var cardId = cardSequence.CardID;
 527                var gameId = cardSequence.GameCardGroupSequence.GameID;
 528
 529                if (dataContext.Results.Any(r => r.GameID == gameId && r.CardID == cardId))
 530                {
 531                    var existingResult = dataContext.Results.FirstOrDefault(r => r.GameID == gameId && r.CardID == cardId);
 532
 533                    if(existingResult != null)
 534                    {
 535                        var cardType = GetCardTypeFromCardSequenceId(cardSequenceId);
 536
 537                        if (cardType != CardType.MultipleChoicePriorityFeedbackCard &&
 538                            cardType != CardType.TextAreaPriorityFeedbackCard &&
 539                            cardType != CardType.MultipleCheckBoxPriorityFeedbackCard)
 540                        {
 541                            dataContext.Results.Remove(existingResult);   
 542                        }
 543                        else
 544                        {
 545                            var feedbackResult = Deserialize<VotingCardFeedbackResult>(existingResult.ResultXmlElement);
 546
 547                            if (feedbackResult != null)
 548                            {
 549                                var currentFeedbackResult = Deserialize<VotingCardFeedbackResult>(resultXml);
 550
 551                                if (currentFeedbackResult != null && 
 552                                    feedbackResult.AnswerId == currentFeedbackResult.AnswerId)
 553                                {
 554                                    dataContext.Results.Remove(existingResult);  
 555                                }
 556                            }
 557                        }                        
 558                    }                   
 559                }
 560
 561                bool isUpdateOnly = false;
 562
 563                var currentDateTime = DateTime.Now;
 564
 565                cardSequence.LastModifiedOnDateTime = currentDateTime;
 566                cardSequence.UserID_LastModifiedBy = userId;
 567                cardSequence.CardViewedInGame = true;
 568                cardSequence.CardViewedInGameOn = currentDateTime;
 569
 570                Result result = null;
 571                if (string.Compare(resultType, typeof(PlayerResult).Name, true) == 0)
 572                {
 573                    isUpdateOnly = true;
 574                }
 575                else
 576                {
 577                    var card = dataContext.Cards.FirstOrDefault(c => c.CardID == cardId);
 578
 579                    if (card == null)
 580                    {
 581                        return false;
 582                    }
 583
 584                    var gamePlayer =
 585                        dataContext.GamePlayers.FirstOrDefault(g => g.GameID == gameId && g.UserID == userId);
 586
 587                    if(gamePlayer == null)
 588                    {
 589                        throw new Exception(@"The result could no be saved as the Game Player could not be found for this game.");
 590                    }
 591
 592                    result = new Result()
 593                                     {
 594                                         CardID = cardId,
 595                                         CreatedOnDateTime = currentDateTime,
 596                                         GameID = gameId,
 597                                         Internal_CardTypeID = card.Internal_CardTypeID,
 598                                         LastModifiedOnDateTime = currentDateTime,
 599                                         ResultType = resultType,
 600                                         ResultXmlElement = resultXml,
 601                                         UserID_CreatedBy = userId,
 602                                         UserID_LastModifiedBy = userId,
 603                                         GamePlayerID = gamePlayer.GamePlayerID
 604                                     };
 605
 606                    dataContext.Results.Add(result);                    
 607                }
 608
 609                dataContext.SaveChanges();
 610
 611                if(isUpdateOnly)
 612                {
 613                    saved = true;
 614                }
 615                else
 616                {
 617                    saved = result.ResultID > 0;
 618                }
 619
 620            }
 621            return saved;
 622        }
 623
 624        public bool SkipCard(Guid userId, int cardSequenceId)
 625        {
 626            var saved = false;
 627
 628            using (var dataContext = new EChallengeDataContext())
 629            {
 630                var cardSequence =
 631                    dataContext.GameCardSequences.FirstOrDefault(s => s.GameCardSequenceID == cardSequenceId);
 632
 633                if (cardSequence == null)
 634                {
 635                    return false;
 636                }
 637
 638                var currentDateTime = DateTime.Now;
 639
 640                cardSequence.LastModifiedOnDateTime = currentDateTime;
 641                cardSequence.UserID_LastModifiedBy = userId;
 642                cardSequence.CardViewedInGame = true;
 643                cardSequence.CardViewedInGameOn = currentDateTime;
 644
 645                dataContext.SaveChanges();
 646                saved = true;
 647            }
 648            return saved;
 649
 650        }
 651
 652        public bool SetGameAsCompleted(Guid userId, int gameId)
 653        {
 654            var saved = false;
 655
 656            using (var dataContext = new EChallengeDataContext())
 657            {
 658                var game =
 659                    dataContext.Games.FirstOrDefault(s => s.GameID == gameId && s.UserID_CreatedBy == userId);
 660
 661                if (game == null)
 662                {
 663                    return false;
 664                }
 665
 666                var currentDateTime = DateTime.Now;
 667
 668                game.LastModifiedOnDateTime = currentDateTime;
 669                game.UserID_LastModifiedBy = userId;
 670                game.GameCompletionDate = DateTime.Now;
 671
 672                var gameCompletedShortCode = Enum.GetName(typeof (CardType), CardType.GameCompletedCard);
 673
 674                var gameCompletedCard = dataContext.GameCardSequences.FirstOrDefault(
 675                    c =>
 676                    c.Card.Internal_CardType.Internal_CardTypeShortCode ==
 677                    gameCompletedShortCode && c.GameCardGroupSequence.GameID == gameId);
 678
 679                if (gameCompletedCard != null)
 680                {
 681                    gameCompletedCard.LastModifiedOnDateTime = currentDateTime;
 682                    gameCompletedCard.UserID_LastModifiedBy = userId;
 683                    gameCompletedCard.CardViewedInGame = true;
 684                    gameCompletedCard.CardViewedInGameOn = game.GameCompletionDate;
 685                }
 686
 687                dataContext.SaveChanges();
 688                saved = true;
 689            }
 690            return saved;
 691        }
 692
 693        public bool HasUnansweredQuestions(int gameId)
 694        {
 695            var excludedCardTypes = new List<string>();
 696            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.AwardCard));
 697            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.CertificateCard));
 698            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.CompanyPolicyCard));
 699            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.GameIntroCard));
 700            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.GameCompletedCard));
 701            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.LeadingQuestionCard));
 702            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.LcdCategoryCard));
 703            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.IntroSurveyCard));
 704            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.RoundResultCard));
 705            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.ScoreboardCard));
 706            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.TransitionUpCard));
 707            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.TransitionDownCard));
 708            excludedCardTypes.Add(Enum.GetName(typeof(CardType), CardType.ThemeIntroCard));
 709
 710            var cardsequences = DataContext.GameCardGroupSequences
 711                .Where(g => g.GameID == gameId)
 712                .SelectMany(g => g.GameCardSequences);
 713
 714            _log.Debug(@"Start Has Unanswered Questions");
 715
 716            var gameCompletedShortCode = Enum.GetName(typeof (CardType), CardType.GameCompletedCard);
 717            var noOfCardsRequiredToBeViewed = cardsequences.Where(
 718                c =>
 719                c.IsAMandatoryCard && c.Card.Internal_CardType.Internal_CardTypeShortCode != gameCompletedShortCode).Distinct().Count();
 720
 721            _log.DebugFormat(@"Cards Required to be Viewed = {0}", noOfCardsRequiredToBeViewed);
 722
 723            var noOfCardsViewInGame = cardsequences.Where(
 724                c => c.IsAMandatoryCard && c.CardViewedInGame && c.Card.Internal_CardType.Internal_CardTypeShortCode != gameCompletedShortCode).Distinct().Count();
 725
 726            _log.DebugFormat(@"Cards Viewed = {0}", noOfCardsViewInGame);
 727
 728            if(noOfCardsRequiredToBeViewed != noOfCardsViewInGame)
 729            {
 730                return true;
 731            }
 732
 733            var noOfCardsRequiredToBeAnswered = cardsequences.Where(
 734                c =>
 735                //validate mandatory cards
 736                c.IsAMandatoryCard &&
 737                !excludedCardTypes.Contains(c.Card.Internal_CardType.Internal_CardTypeShortCode))
 738                .Distinct().Count();
 739
 740            _log.DebugFormat(@"Cards Required to be Answered = {0}", noOfCardsRequiredToBeAnswered);
 741
 742            var results = DataContext.Results.Where(r=>r.GameID == gameId).Select(r=>r.CardID);
 743
 744            var cardSequencesToAnswer =(DataContext.GameCardGroupSequences
 745                .Where(g => g.GameID == gameId)                
 746                .SelectMany(g => g.GameCardSequences))
 747                .Where(c=>c.IsAMandatoryCard && !excludedCardTypes.Contains(c.Card.Internal_CardType.Internal_CardTypeShortCode));
 748
 749
 750            var noOfCardsAnswered = (from c in cardSequencesToAnswer
 751                           where results.Contains(c.CardID)
 752                           select c).Count();
 753
 754            _log.DebugFormat(@"Cards Answered = {0}", noOfCardsAnswered);
 755
 756            //var noOfCardsAnswered = (from grp in DataContext.GameCardGroupSequences
 757            //                         from cs in grp.GameCardSequences
 758            //                         where grp.GameID == gameId && cs.IsAMandatoryCard && !excludedCardTypes.Contains(cs.Card.Internal_CardType.Internal_CardTypeShortCode)
 759            //                         && results.Contains(cs.CardID)
 760            //                         select cs).Count();
 761
 762
 763                                        
 764            
 765            if(noOfCardsAnswered == noOfCardsRequiredToBeAnswered)
 766            {
 767                return false;
 768            }
 769
 770            return true;
 771        }
 772
 773        public bool IncrementGameRunCount(int gameId, Guid userId)
 774        {
 775            var saved = false;
 776
 777            using (var dataContext = new EChallengeDataContext())
 778            {
 779                var game =
 780                    dataContext.Games.FirstOrDefault(s => s.GameID == gameId && s.UserID_CreatedBy == userId);
 781
 782                if (game == null)
 783                {
 784                    return false;
 785                }
 786
 787                var currentDateTime = DateTime.Now;
 788
 789                game.LastModifiedOnDateTime = currentDateTime;
 790                game.UserID_LastModifiedBy = userId;
 791                var numberOfTimesRun = game.NumberOfTimesRun;
 792                numberOfTimesRun++;
 793                game.NumberOfTimesRun = numberOfTimesRun;
 794
 795                dataContext.SaveChanges();
 796                saved = true;
 797            }
 798            return saved;
 799        }
 800
 801        public CardType GetCardTypeFromCardSequenceId(int cardSequenceId)
 802        {
 803            var cardSequence = DataContext.GameCardSequences.FirstOrDefault(s => s.GameCardSequenceID == cardSequenceId);
 804
 805            if(cardSequence == null)
 806            {
 807                return CardType.Unknown;                
 808            }            
 809            return GetCardType(cardSequence.CardID);
 810        }        
 811
 812        public CardType GetCardType(int cardId)
 813        {
 814            var card = DataContext.Cards.FirstOrDefault(c => c.CardID == cardId);
 815
 816            if (card == null)
 817            {
 818                return CardType.Unknown;
 819            }
 820
 821            var result = CardType.Unknown;
 822
 823            if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.ArrangeSequenceQuestionCard))
 824            {
 825                result = CardType.ArrangeSequenceQuestionCard;
 826            }
 827            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.FillInTheBlankQuestionCard))
 828            {
 829                result = CardType.FillInTheBlankQuestionCard;
 830            }
 831            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MatchingListQuestionCard))
 832            {
 833                result = CardType.MatchingListQuestionCard;
 834            }
 835            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.NumericQuestionCard))
 836            {
 837                result = CardType.NumericQuestionCard;
 838            }
 839            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.PotLuckQuestionCard))
 840            {
 841                result = CardType.PotLuckQuestionCard;
 842            }
 843            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoiceQuestionCard))
 844            {
 845                result = CardType.MultipleChoiceQuestionCard;
 846            }
 847            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoiceImageQuestionCard))
 848            {
 849                result = CardType.MultipleChoiceImageQuestionCard;
 850            }
 851            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleCheckBoxQuestionCard))
 852            {
 853                result = CardType.MultipleCheckBoxQuestionCard;
 854            }
 855            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.LcdCategoryCard))
 856            {
 857                result = CardType.LcdCategoryCard;
 858            }
 859            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoiceAuditStatementCard))
 860            {
 861                result = CardType.MultipleChoiceAuditStatementCard;
 862            }
 863            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoiceAuditStatementImageCard))
 864            {
 865                result = CardType.MultipleChoiceAuditStatementImageCard;
 866            }
 867            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.CompanyPolicyCard))
 868            {
 869                result = CardType.CompanyPolicyCard;
 870            }
 871            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.LeadingQuestionCard))
 872            {
 873                result = CardType.LeadingQuestionCard;
 874            }
 875            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TransitionUpCard))
 876            {
 877                result = CardType.TransitionUpCard;
 878            }
 879            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TransitionDownCard))
 880            {
 881                result = CardType.TransitionDownCard;
 882            }
 883            else if(card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.GameCompletedCard))
 884            {
 885                result = CardType.GameCompletedCard;                
 886            }
 887            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoiceSurveyCard))
 888            {
 889                result = CardType.MultipleChoiceSurveyCard;
 890            }
 891            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleCheckBoxSurveyCard))
 892            {
 893                result = CardType.MultipleCheckBoxSurveyCard;
 894            }
 895            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleCheckBoxPriorityFeedbackCard))
 896            {
 897                result = CardType.MultipleCheckBoxPriorityFeedbackCard;
 898            }
 899            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoicePriorityFeedbackCard))
 900            {
 901                result = CardType.MultipleChoicePriorityFeedbackCard;
 902            }
 903            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TextAreaPriorityFeedbackCard))
 904            {
 905                result = CardType.TextAreaPriorityFeedbackCard;
 906            }
 907            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.PriorityIssueVotingCard))
 908            {
 909                result = CardType.PriorityIssueVotingCard;
 910            }
 911            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TextAreaSurveyCard))
 912            {
 913                result = CardType.TextAreaSurveyCard;
 914            }
 915            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TextBoxSurveyCard))
 916            {
 917                result = CardType.TextBoxSurveyCard;
 918            }
 919            else if(card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TextAreaPersonalActionPlanCard))
 920            {
 921                result = CardType.TextAreaPersonalActionPlanCard;
 922            }
 923            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.TextBoxPersonalActionPlanCard))
 924            {
 925                result = CardType.TextBoxPersonalActionPlanCard;
 926            }
 927            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleChoicePersonalActionPlanCard))
 928            {
 929                result = CardType.MultipleChoicePersonalActionPlanCard;
 930            }
 931            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MultipleCheckboxPersonalActionPlanCard))
 932            {
 933                result = CardType.MultipleCheckboxPersonalActionPlanCard;
 934            }
 935            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.ScoreboardCard))
 936            {
 937                result = CardType.ScoreboardCard;
 938            }
 939            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.RoundResultCard))
 940            {
 941                result = CardType.RoundResultCard;
 942            }
 943            else if(card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.IntroSurveyCard))
 944            {
 945                result = CardType.IntroSurveyCard;                
 946            }
 947            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.GameIntroCard))
 948            {
 949                result = CardType.GameIntroCard;
 950            }
 951            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.ThemeIntroCard))
 952            {
 953                result = CardType.ThemeIntroCard;
 954            }
 955            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.MatchingListQuestionCard))
 956            {
 957                result = CardType.MatchingListQuestionCard;
 958            }
 959            else if (card.Internal_CardType.Internal_CardTypeShortCode == Enum.GetName(typeof(CardType), CardType.BranchingCard))
 960            {
 961                result = CardType.BranchingCard;
 962            }
 963
 964            return result;
 965        }
 966
 967        public Dashboard GetDashboard(Guid userId, int languageId)
 968        {
 969            return
 970                new Dashboard()
 971                {
 972                    Games = GetGamesForDashboard(userId, languageId).ToList(),
 973                    Player = GetPlayer(userId)
 974                };
 975        }
 976
 977
 978        IEnumerable<GameTemplateInstance> GetGamesForDashboard(Guid userId, int languageId)
 979        {
 980            var dbGames = from g in DataContext.Games
 981                   join i in DataContext.GameInvites on g.GameID equals i.GameID
 982                   where g.IsAGameTemplate && i.UserID == userId
 983                   select new 
 984                              {
 985                                  Id = g.GameID,
 986                                  game = g,
 987                                  NumberOfTimesGameCanBePlayed = g.NumberOfTimesGameCanBePlayed.HasValue ? g.NumberOfTimesGameCanBePlayed.Value : 1
 988                              };
 989
 990
 991            var games = new List<GameTemplateInstance>();
 992
 993            foreach (var dbGame in dbGames)
 994            {
 995                var game = new GameTemplateInstance()
 996                               {
 997                                   Id = dbGame.Id,
 998                                   GameSettings = GetGameSettings(dbGame.game),
 999                                   Games = GetGameInstancesForTemplate(dbGame.Id, userId),
1000                                   NumberOfTimesGameCanBePlayed = dbGame.NumberOfTimesGameCanBePlayed
1001                               };
1002
1003                games.Add(game);
1004            }
1005
1006            return games;
1007        }
1008
1009        List<GameInstance> GetGameInstancesForTemplate(int gameTemplateId, Guid userId)
1010        {
1011            var results = (from g in DataContext.Games
1012                    join p in DataContext.GamePlayers on g.GameID equals p.GameID
1013                    where g.GameID_Template == gameTemplateId && !g.IsAGameTemplate
1014                        && p.UserID == userId && g.UserID_CreatedBy == userId 
1015                        // Use UserID_CreatedBy above as a user will only be able to create his own game instances.
1016                        // This also prevents bringing up games in other peoples dashboard as the UserID may be used 
1017                        // as a simulated player in another game and so checking the player UserID only is not sufficient
1018                    select new 
1019                               {
1020                                   Id = g.GameID,
1021                                   game = g,
1022                                   ProductId = g.ProductID,
1023                               }).Distinct().ToList();
1024
1025            var gameInstances = new List<GameInstance>();
1026
1027            foreach (var result in results)
1028            {
1029                var gameInstance = new GameInstance()
1030                                       {
1031                                           Id = result.Id,
1032                                           GameSettings = GetGameSettings(result.game),
1033                                           ProductId = result.ProductId,
1034                                           PercentCompleted = GetPercentCompleted(result.Id)
1035                                       };
1036
1037                SetGameHeaderCardTotals(gameInstance);
1038
1039                gameInstances.Add(gameInstance);
1040            }
1041
1042            return gameInstances;
1043        }
1044
1045        public IQueryable<Game> GetGames(int languageId)
1046        {
1047            var games = from g in DataContext.Games
1048                          select g;
1049
1050            var results = (from g in games
1051                           select new Game()
1052                                      {
1053                                          Id = g.GameID,
1054                                          ProductId = g.ProductID,
1055                                          GameSettings = GetGameSettings(g),
1056                                          AvatarSettings = GetAvatarSettings(g),
1057                                          PlayerTurnSettings = GetPlayerTurnSettings(g),
1058                                          Players = new List<Player>(GetGamePlayers(g.GameID)),
1059                                          CardGroups = GetCardGroups(g.GameID, languageId).ToList(),
1060                                          PercentCompleted = g.IsAGameTemplate ? 0 : GetPercentCompleted(g.GameID),
1061                                          IsResumed = true
1062                                          //All set to true here. When new games are created from templates, 
1063                                          //after receving the game from db this value is set to false to indicate a new game
1064                                      });
1065
1066            foreach (var result in results)
1067            {
1068                SetGameHeaderCardTotals(result);
1069

Large files files are truncated, but you can click here to view the full file