public static void insertBlockIntoDb(Guid teamId, GameViewModel game, BlockViewModel block, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                GameMemberBlock blocks = new GameMemberBlock();
                blocks.DateTimeBlocked = block.CurrentDateTimeBlock;
                blocks.GameBlockId = block.BlockId;
                blocks.JamNumber = block.JamNumber;
                blocks.JamId = block.JamId;
                blocks.PeriodNumber = block.Period;
                blocks.PeriodTimeRemainingMilliseconds = block.PeriodTimeRemaining;
                blocks.Game = g;

                blocks.MemberWhoBlocked = g.GameTeams.Where(x => x.TeamId == teamId).First().GameMembers.Where(x => x.GameMemberId == block.PlayerWhoBlocked.SkaterId).FirstOrDefault();
                if (blocks.MemberWhoBlocked != null)
                {
                    db.GameMemberBlock.Add(blocks);
                    db.SaveChanges();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        private static Tournament DisplayTournament(GameTournament tourny)
        {
            try
            {
                var memId = RDN.Library.Classes.Account.User.GetMemberId();
                Tournament to = new Tournament();
                to.TournamentClass = (TournamentClassEnum)tourny.TournamentClass;
                to.TournamentType = (TournamentTypeEnum)tourny.TournamentTypeEnum;
                to.EndDate = tourny.EndDate;
                if (tourny.SelectedShop != null)
                    to.SelectedShop = tourny.SelectedShop.MerchantId.ToString();
                to.EndDateDisplay = tourny.EndDate.ToShortDateString();
                to.StartDateDisplay = tourny.StartDate.ToShortDateString();
                to.StartDate = tourny.StartDate;
                to.Id = tourny.TournamentId;
                to.IsPublished = tourny.IsPublished;
                to.AreBracketsPublished = tourny.AreBracketsPublished;
                to.PrivateKey = tourny.PrivateTournamentId;
                to.Name = tourny.TournamentName;
                to.PassCodeForGames = tourny.TournamentPasscode;
                to.EmbedVideoString = tourny.EmbedVideoString;
                to.TournamentWebsite = tourny.TournamentWebsite;

                if (tourny.OwnerOfTournament != null)
                {
                    MemberDisplayBasic m = new MemberDisplayBasic();
                    m.DerbyName = tourny.OwnerOfTournament.DerbyName;
                    m.MemberId = tourny.OwnerOfTournament.MemberId;
                    m.UserId = tourny.OwnerOfTournament.AspNetUserId;
                    to.Owners.Add(m);
                }

                for (int i = 0; i < tourny.OwnersOfTournament.Count; i++)
                {
                    try
                    {
                        if (to.Owners.Where(x => x.MemberId == tourny.OwnersOfTournament[i].Owner.MemberId).FirstOrDefault() == null)
                        {
                            MemberDisplayBasic m = new MemberDisplayBasic();
                            m.DerbyName = tourny.OwnersOfTournament[i].Owner.DerbyName;
                            m.MemberId = tourny.OwnersOfTournament[i].Owner.MemberId;
                            m.UserId = tourny.OwnersOfTournament[i].Owner.AspNetUserId;
                            to.Owners.Add(m);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }


                if (tourny.Logo != null)
                    to.Photos.Add(new PhotoItem(tourny.Logo.ImageUrl, tourny.Logo.ImageUrlThumb, true, tourny.TournamentName));
                #region contact
                if (tourny.ContactCard != null)
                {
                    var add = tourny.ContactCard.Addresses.FirstOrDefault();
                    if (add != null)
                    {
                        to.Address = add.Address1;
                        to.Address2 = add.Address2;
                        to.City = add.CityRaw;
                        if (add.Country != null)
                        {
                            to.Country = add.Country.Code;
                            to.CountryId = add.Country.CountryId;
                        }
                        to.State = add.StateRaw;
                        to.ZipCode = add.Zip;
                    }
                }

                #endregion
                #region paywall
                if (tourny.Paywall != null)
                {
                    to.Paywall.DailyPrice = tourny.Paywall.DailyPrice;
                    to.Paywall.DescriptionOfPaywall = tourny.Paywall.DescriptionOfPaywall;
                    to.Paywall.EndDate = tourny.Paywall.EndDate;
                    if (tourny.Paywall.EndDate.HasValue)
                        to.Paywall.EndDateDisplay = tourny.Paywall.EndDate.Value.ToShortDateString();
                    to.Paywall.IsEnabled = tourny.Paywall.IsEnabled;
                    to.Paywall.IsRemoved = tourny.Paywall.IsRemoved;
                    to.Paywall.PaywallId = tourny.Paywall.PaywallId;
                    to.Paywall.StartDate = tourny.Paywall.StartDate;
                    if (tourny.Paywall.StartDate.HasValue)
                        to.Paywall.StartDateDisplay = tourny.Paywall.StartDate.Value.ToShortDateString();
                    to.Paywall.TimespanPrice = tourny.Paywall.TimespanPrice;
                    to.PaywallId = tourny.Paywall.PaywallId;
                    to.Paywall.AcceptPaypal = tourny.Paywall.Merchant.AcceptPaymentsViaPaypal;
                    to.Paywall.AcceptStripe = tourny.Paywall.Merchant.AcceptPaymentsViaStripe;
                    if (memId != new Guid())
                    {
                        var isPaid = tourny.Paywall.PaywallInvoices.Where(x => x.MemberPaidId == memId).OrderByDescending(x => x.Created).FirstOrDefault();
                        if (isPaid != null)
                        {
                            if (isPaid.ValidUntil > DateTime.UtcNow && (isPaid.Invoice.InvoiceStatus == (byte)InvoiceStatus.Payment_Successful || isPaid.Invoice.InvoiceStatus == (byte)InvoiceStatus.Pending_Payment_From_Paypal))
                            {
                                to.Paywall.IsPaid = true;
                            }
                        }
                        else
                            to.Paywall.IsPaid = false;
                    }
                    to.Paywall.MerchantId = tourny.Paywall.Merchant.MerchantId;
                }

                #endregion
                #region Games
                List<Game> games = new List<Game>();
                foreach (var game in tourny.Games)
                {
                    try
                    {
                        Game g = new Game();
                        g.GameId = game.GameId;
                        g.GameName = game.GameName;
                        g.GameDate = game.GameDate;
                        var teams = game.GameTeams.OrderByDescending(x => x.Created).Take(2);
                        var team1 = teams.OrderByDescending(x => x.TeamName).FirstOrDefault();
                        var team2 = teams.OrderBy(x => x.TeamName).FirstOrDefault();
                        g.Team1Name = team1.TeamName;
                        g.Team1LinkId = team1.TeamIdLink;
                        g.Team1Id = team1.TeamId;
                        g.Team2Name = team2.TeamName;
                        g.Team2LinkId = team2.TeamIdLink;
                        g.Team2Id = team2.TeamId;
                        g.Team1ScoreTotal = team1.GameScores.Select(x => x.Point).Sum();
                        g.Team2ScoreTotal = team2.GameScores.Select(x => x.Point).Sum();

                        foreach (var b in team1.GameMembers)
                        {
                            TeamMembersViewModel a = new TeamMembersViewModel();
                            a.SkaterId = b.GameMemberId;
                            a.SkaterLinkId = b.MemberLinkId;
                            a.SkaterName = b.MemberName;
                            a.SkaterNumber = b.MemberNumber;
                            if (to.AllSkaters.Where(x => x.SkaterLinkId == a.SkaterLinkId).FirstOrDefault() == null)
                                to.AllSkaters.Add(a);
                        }
                        foreach (var b in team2.GameMembers)
                        {
                            TeamMembersViewModel a = new TeamMembersViewModel();
                            a.SkaterId = b.GameMemberId;
                            a.SkaterLinkId = b.MemberLinkId;
                            a.SkaterName = b.MemberName;
                            a.SkaterNumber = b.MemberNumber;
                            if (to.AllSkaters.Where(x => x.SkaterLinkId == a.SkaterLinkId).FirstOrDefault() == null)
                                to.AllSkaters.Add(a);

                        }

                        foreach (var assist in game.GameMemberAssists)
                        {
                            AssistViewModel a = new AssistViewModel();
                            a.AssistId = assist.GameAssistId;
                            a.PlayerWhoAssisted = new TeamMembersViewModel();
                            a.PlayerWhoAssisted.SkaterId = assist.MemberWhoAssisted.GameMemberId;
                            a.PlayerWhoAssisted.SkaterName = assist.MemberWhoAssisted.MemberName;
                            a.PlayerWhoAssisted.SkaterLinkId = assist.MemberWhoAssisted.MemberLinkId;
                            to.AssistLeaders.Add(a);
                        }
                        foreach (var pen in game.GameMemberPenalties)
                        {
                            PenaltyViewModel a = new PenaltyViewModel();
                            a.PenaltyId = pen.GamePenaltyId;
                            a.PenaltyAgainstMember = new TeamMembersViewModel();
                            a.PenaltyAgainstMember.SkaterId = pen.MemberWhoPenaltied.GameMemberId;
                            a.PenaltyAgainstMember.SkaterName = pen.MemberWhoPenaltied.MemberName;
                            a.PenaltyAgainstMember.SkaterLinkId = pen.MemberWhoPenaltied.MemberLinkId;
                            a.PenaltyType = (PenaltiesEnum)Enum.Parse(typeof(PenaltiesEnum), pen.PenaltyType.ToString());
                            to.PenaltyLeaders.Add(a);
                        }
                        foreach (var blocks in game.GameMemberBlocks)
                        {
                            BlockViewModel a = new BlockViewModel();
                            a.BlockId = blocks.GameBlockId;
                            a.PlayerWhoBlocked = new TeamMembersViewModel();
                            a.PlayerWhoBlocked.SkaterId = blocks.MemberWhoBlocked.GameMemberId;
                            a.PlayerWhoBlocked.SkaterName = blocks.MemberWhoBlocked.MemberName;
                            a.PlayerWhoBlocked.SkaterLinkId = blocks.MemberWhoBlocked.MemberLinkId;
                            to.BlockLeaders.Add(a);
                        }
                        games.Add(g);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                to.Games = games;

                #endregion

                var ts = tourny.Teams.Where(x => x.IsRemoved == false);
                foreach (var team in ts)
                {
                    try
                    {
                        TeamViewModel t = new TeamViewModel();
                        t.PoolNumber = team.PoolNumber;
                        t.LeagueName = team.LeageName;
                        //t.TeamLinkId = team.TeamIdLink;
                        t.TeamName = team.TeamName;
                        t.TeamId = team.TeamId;
                        t.SeedRating = team.SeedRating;
                        to.TeamsForTournament.Add(t);
                        TournamentApi.TournamentTeam tt = new TournamentApi.TournamentTeam(team.TeamId, team.SeedRating, team.PoolNumber);
                        to.TeamsForTournamentApi.Add(tt);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                #region seededbracketsForPerformance
                try
                {
                    to.TouramentTypeForSeedingEnum = (TournamentTypeEnum)tourny.TournamentTypeEnumForSeedingRound;
                    if (to.TouramentTypeForSeedingEnum != TournamentTypeEnum.None)
                    {

                        TournamentApi.IPairingsGenerator pg = null;

                        switch (to.TouramentTypeForSeedingEnum)
                        {
                            case TournamentTypeEnum.Boil_Off:
                                pg = new BoilOffPairingsGenerator();
                                break;
                            case TournamentTypeEnum.Round_Robin:
                                pg = new RoundRobinPairingsGenerator();
                                break;
                            case TournamentTypeEnum.Double_Elimination:
                                pg = new EliminationTournament(2);
                                break;
                            case TournamentTypeEnum.Single_Elimination:
                                pg = new EliminationTournament(1);
                                break;
                            case TournamentTypeEnum.Round_Robin_Pool_Play:
                                pg = new RoundRobinPairingsGenerator(true);
                                break;
                        }
                        if (pg is TournamentApi.ITournamentVisualizer)
                        {
                            to.VisualizedBracketsSeeded = (TournamentApi.ITournamentVisualizer)pg;
                        }

                        foreach (var round in tourny.SeedingRounds)
                        {
                            try
                            {
                                TournamentRoundsClass r = new TournamentRoundsClass();
                                List<TournamentApi.TournamentPairing> ppList = new List<TournamentApi.TournamentPairing>();
                                r.RoundNumber = round.RoundNumber;
                                foreach (var pair in round.Pairings)
                                {
                                    List<TournamentApi.TournamentTeamScore> ttList = new List<TournamentApi.TournamentTeamScore>();
                                    TournamentPairingClass p = new TournamentPairingClass();
                                    p.Id = pair.PairingId;
                                    p.GroupId = pair.GroupId;
                                    p.TimeToStart = pair.StartTime.GetValueOrDefault();
                                    if (pair.StartTime.HasValue)
                                        p.TimeToStartDisplay = p.TimeToStart.ToString("HH:mm");
                                    p.TrackId = pair.TrackNumber;
                                    foreach (var team in pair.Teams)
                                    {
                                        TeamViewModel t = new TeamViewModel();
                                        t.TeamId = team.Team.TeamId;
                                        t.TeamName = team.Team.TeamName;
                                        t.TeamLinkId = team.TeamIdInGame;
                                        if (t.TeamLinkId != new Guid() && p.GameId == new Guid())
                                        {
                                            var g = to.Games.Where(x => x.Team1Id == t.TeamLinkId || x.Team2Id == t.TeamLinkId).FirstOrDefault();
                                            if (g != null)
                                                p.GameId = g.GameId;
                                        }
                                        t.Score = team.Score;
                                        p.Teams.Add(t);

                                        TournamentApi.TournamentTeamScore tt = new TournamentApi.TournamentTeamScore(new TournamentApi.TournamentTeam(t.TeamId, team.Team.SeedRating), new TournamentApi.HighestPointsScore(team.Score));
                                        ttList.Add(tt);

                                    }
                                    TournamentApi.TournamentPairing pp = new TournamentApi.TournamentPairing(ttList);
                                    pp.GroupId = p.GroupId;
                                    ppList.Add(pp);
                                    r.Pairings.Add(p);
                                }

                                TournamentApi.TournamentRound rr = new TournamentApi.TournamentRound(ppList);
                                to.TournamentRoundsApiForSeeding.Add(rr);
                                to.TournamentRoundsForSeedingGameplay.Add(r);
                            }
                            catch (Exception exception)
                            {
                                ErrorDatabaseManager.AddException(exception, exception.GetType());
                            }
                        }

                        if (pg != null)
                        {
                            pg.LoadState(to.TeamsForTournamentApi, to.TournamentRoundsApiForSeeding);
                            try
                            {
                                var nextRound = pg.CreateNextRound(null);

                                to.HasSeedingFinishForTournament = (nextRound == null) && (tourny.SeedingRounds.Count() > 1);

                                if (to.TournamentRoundsApiForSeeding.Any())
                                {
                                    var rankings = pg.GenerateRankings();

                                    to.RankingsForSeededRounds = new List<TournamentApi.TournamentRanking>(from rk in rankings
                                                                                                           select new TournamentApi.TournamentRanking
                                                                                                           {
                                                                                                               TeamName = to.TeamsForTournament.Where(tm => tm.TeamId == rk.team.TeamId).Single().TeamName,
                                                                                                               rank = rk.rank,
                                                                                                               Loses = rk.Loses,
                                                                                                               PointSpread = rk.PointSpread,
                                                                                                               scoreDescription = rk.scoreDescription,
                                                                                                               team = rk.team,
                                                                                                               TotalPoints = rk.TotalPoints,
                                                                                                               Wins = rk.Wins
                                                                                                           });
                                }

                            }
                            catch (Exception exception)
                            {
                                ErrorDatabaseManager.AddException(exception, exception.GetType());
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType());
                }

                #endregion


                #region brackets
                try
                {
                    to.TournamentType = (TournamentTypeEnum)tourny.TournamentTypeEnum;
                    if (to.TournamentType != TournamentTypeEnum.None)
                    {
                        if (to.TouramentTypeForSeedingEnum != TournamentTypeEnum.None && to.HasSeedingFinishForTournament)
                        {
                            foreach (var ranking in to.RankingsForSeededRounds)
                            {
                                var team = to.TeamsForTournamentApi.Where(x => x.TeamId == ranking.team.TeamId).FirstOrDefault();
                                team.Rating = (int)ranking.rank;
                            }
                        }


                        TournamentApi.IPairingsGenerator pg = null;

                        switch (to.TournamentType)
                        {
                            case TournamentTypeEnum.Boil_Off:
                                pg = new BoilOffPairingsGenerator();
                                break;
                            case TournamentTypeEnum.Round_Robin:
                                pg = new RoundRobinPairingsGenerator();
                                break;
                            case TournamentTypeEnum.Round_Robin_Pool_Play:
                                pg = new RoundRobinPairingsGenerator(true);
                                break;
                            case TournamentTypeEnum.Double_Elimination:
                                pg = new EliminationTournament(2);
                                break;
                            case TournamentTypeEnum.Single_Elimination:
                                pg = new EliminationTournament(1);
                                break;
                        }
                        try
                        {
                            if (pg is TournamentApi.ITournamentVisualizer)
                            {
                                to.VisualizedBrackets = (TournamentApi.ITournamentVisualizer)pg;
                            }
                        }
                        catch //(TournamentApi.InvalidTournamentStateException ex)
                        {
                            //Debug.WriteLine(ex);
                        }

                        foreach (var round in tourny.Rounds)
                        {
                            try
                            {
                                TournamentRoundsClass r = new TournamentRoundsClass();
                                List<TournamentApi.TournamentPairing> ppList = new List<TournamentApi.TournamentPairing>();
                                r.RoundNumber = round.RoundNumber;
                                foreach (var pair in round.Pairings)
                                {
                                    List<TournamentApi.TournamentTeamScore> ttList = new List<TournamentApi.TournamentTeamScore>();
                                    TournamentPairingClass p = new TournamentPairingClass();
                                    p.Id = pair.PairingId;
                                    p.GroupId = pair.GroupId;
                                    p.TimeToStart = pair.StartTime.GetValueOrDefault();
                                    if (pair.StartTime.HasValue)
                                        p.TimeToStartDisplay = p.TimeToStart.ToString("HH:mm");
                                    p.TrackId = pair.TrackNumber;
                                    foreach (var team in pair.Teams)
                                    {
                                        TeamViewModel t = new TeamViewModel();
                                        t.TeamId = team.Team.TeamId;
                                        t.TeamName = team.Team.TeamName;
                                        t.TeamLinkId = team.TeamIdInGame;
                                        if (t.TeamLinkId != new Guid() && p.GameId == new Guid())
                                        {
                                            var g = to.Games.Where(x => x.Team1Id == t.TeamLinkId || x.Team2Id == t.TeamLinkId).FirstOrDefault();
                                            if (g != null)
                                                p.GameId = g.GameId;
                                        }
                                        t.Score = team.Score;
                                        p.Teams.Add(t);

                                        TournamentApi.TournamentTeamScore tt = new TournamentApi.TournamentTeamScore(new TournamentApi.TournamentTeam(t.TeamId, team.Team.SeedRating), new TournamentApi.HighestPointsScore(team.Score));
                                        ttList.Add(tt);

                                    }
                                    TournamentApi.TournamentPairing pp = new TournamentApi.TournamentPairing(ttList);
                                    pp.GroupId = p.GroupId;
                                    ppList.Add(pp);
                                    r.Pairings.Add(p);
                                }

                                TournamentApi.TournamentRound rr = new TournamentApi.TournamentRound(ppList);
                                to.TournamentRoundsApi.Add(rr);
                                to.TournamentRounds.Add(r);
                            }
                            catch (Exception exception)
                            {
                                ErrorDatabaseManager.AddException(exception, exception.GetType());
                            }
                        }

                        if (pg != null)
                        {
                            pg.LoadState(to.TeamsForTournamentApi, to.TournamentRoundsApi);
                            try
                            {
                                var nextRound = pg.CreateNextRound(null);

                                to.IsTournamentFinished = (nextRound == null) && (tourny.Rounds.Count() > 1);

                                if (to.TournamentRoundsApi.Any())
                                {
                                    var rankings = pg.GenerateRankings();

                                    to.Rankings = new List<TournamentApi.TournamentRanking>(from rk in rankings
                                                                                            select new TournamentApi.TournamentRanking
                                                                                         {
                                                                                             TeamName = to.TeamsForTournament.Where(tm => tm.TeamId == rk.team.TeamId).Single().TeamName,
                                                                                             rank = rk.rank,
                                                                                             Loses = rk.Loses,
                                                                                             PointSpread = rk.PointSpread,
                                                                                             scoreDescription = rk.scoreDescription,
                                                                                             team = rk.team,
                                                                                             TotalPoints = rk.TotalPoints,
                                                                                             Wins = rk.Wins
                                                                                         });
                                }

                            }
                            catch (TournamentApi.InvalidTournamentStateException)
                            {
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType());
                }

                #endregion
                return to;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        public static GameViewModel getGameFromDb(Guid id)
        {
            try
            {
                ManagementContext db = new ManagementContext();
                var getGame = (from xx in db.Games.Include("GameLinks").Include("GameMemberPenalties").Include("GameMemberAssists").Include("GameMemberBlocks").Include("GameTeams").Include("GameJams").Include("GamePolicy").Include("GameScores").Include("GameTimeouts").Include("GameTeams.Logo")
                               where xx.GameId == id
                               //game must be published to be used.

                               //where xx.IsGamePublishedOnline == true
                               select xx).FirstOrDefault();

                if (getGame == null)
                    return null;
                GameViewModel game = new GameViewModel();

                if (getGame.GameTournament != null)
                {
                    game.TournamentId = getGame.GameTournament.TournamentId;
                    game.TournamentName = getGame.GameTournament.TournamentName;
                }
                if (getGame.FederationOwners.Count > 0)
                {
                    game.FederationId = getGame.FederationOwners.FirstOrDefault().Federation.FederationId;
                    game.FederationName = getGame.FederationOwners.FirstOrDefault().Federation.Name;
                }
                if (getGame.SelectedShop != null)
                    game.SelectedShop = getGame.SelectedShop.MerchantId.ToString();
                game.IsThereVideoOfGame = (GameVideoTypeEnum)Enum.Parse(typeof(GameVideoTypeEnum), getGame.IsThereVideoOfGame.ToString());
                game.StreamingUrlOfVideo = getGame.StreamingUrlOfVideo;
                game.StreamingUrlOfVideoMobile = getGame.StreamingUrlOfVideoMobile;
                game.EmbededVideoHtml = getGame.EmbededVideoHtml;
                game.LastModified = DateTime.UtcNow;
                game.IdForOnlineManagementUse = getGame.IdForOnlineManagementUse;
                game.ElapsedTimeGameClockMilliSeconds = (long)getGame.ElapsedGameTimeInMilliseconds;
                game.GameDate = getGame.GameDate;
                game.GameEndDate = getGame.GameEndDate;
                game.GameId = id;
                game.GameName = getGame.GameName;
                game.HasGameEnded = getGame.IsGameOver;
                game.HasGameStarted = getGame.HasGameStarted;
                game.GameLocation = getGame.GameLocation;
                game.PublishGameOnline = getGame.IsGameLive;
                game.SaveGameOnline = getGame.IsGameScrimmage;
                GameClock.getPeriodClock(id, game);
                GameClock.getIntermissionClock(id, game);
                GameClock.getLineUpClock(id, game);
                GameClock.getTimeOutClock(id, game);
                if (getGame.Paywall != null)
                    game.PaywallId = getGame.Paywall.PaywallId;


                if (getGame.ScoreboardType == 0)
                    game.ScoreboardMode = ScoreboardModeEnum.Debug;
                else if (getGame.ScoreboardType == 1)
                    game.ScoreboardMode = ScoreboardModeEnum.Live;

                //we order the teams so the first one in, is also the first one out.
                var getTeams = getGame.GameTeams.OrderByDescending(x => x.Created).ToList();
                if (game.ScoresTeam1 == null)
                    game.ScoresTeam1 = new List<ScoreViewModel>();
                if (game.ScoresTeam2 == null)
                    game.ScoresTeam2 = new List<ScoreViewModel>();

                game.GameLinks = new List<GameLinkViewModel>();
                var gameLinkss = getGame.GameLinks.ToList();
                for (int i = 0; i < getGame.GameLinks.Count; i++)
                {
                    GameLinkViewModel gameLink = new GameLinkViewModel();
                    gameLink.GameLink = gameLinkss[i].Link;
                    gameLink.LinkId = gameLinkss[i].GameLinkId;
                    gameLink.LinkType = (GameLinkTypeEnum)Enum.ToObject(typeof(GameLinkTypeEnum), gameLinkss[i].LinkType);
                    game.GameLinks.Add(gameLink);
                }


                for (int i = 0; i < getTeams.Count; i++)
                {
                    TeamViewModel tvm = new TeamViewModel();
                    tvm.TeamId = getTeams[i].TeamId;
                    tvm.Logo = new Portable.Classes.Team.TeamLogo();

                    tvm.TeamLinkId = getTeams[i].TeamIdLink;
                    var dc = new ManagementContext();
                    if (getTeams[i].Logo != null)
                    {
                        tvm.Logo.ImageUrl = getTeams[i].Logo.ImageUrl;
                        tvm.Logo.TeamLogoId = getTeams[i].Logo.TeamLogoId;
                    }

                    tvm.TeamName = getTeams[i].TeamName;
                    tvm.TimeOutsLeft = getTeams[i].CurrentTimeouts;
                    tvm.TeamMembers = new System.Collections.ObjectModel.ObservableCollection<TeamMembersViewModel>();
                    if (i == 0)
                    {
                        game.CurrentTeam1Score = getTeams[i].CurrentScore;
                        game.Team1 = tvm;
                    }
                    else if (i == 1)
                    {
                        game.CurrentTeam2Score = getTeams[i].CurrentScore;
                        game.Team2 = tvm;
                    }


                    foreach (var mem in getTeams[i].GameMembers)
                    {
                        TeamMembersViewModel mvm = new TeamMembersViewModel();
                        mvm.SkaterId = mem.GameMemberId;
                        mvm.SkaterName = mem.MemberName;
                        mvm.SkaterNumber = mem.MemberNumber;
                        mvm.SkaterLinkId = mem.MemberLinkId;

                        if (getTeams[i].TeamId == game.Team1.TeamId)
                            game.Team1.TeamMembers.Add(mvm);
                        else if (getTeams[i].TeamId == game.Team2.TeamId)
                            game.Team2.TeamMembers.Add(mvm);
                    }
                    //scores must come after teams  members get added.
                    var scores = getTeams[i].GameScores.OrderBy(x => x.JamNumber);
                    foreach (var score in scores)
                    {
                        try
                        {
                            ScoreViewModel svm = new ScoreViewModel(score.Point, score.PeriodTimeRemainingMilliseconds, score.JamId, score.JamNumber, score.PeriodNumber, score.DateTimeScored, score.GameScoreId);

                            if (getTeams[i].TeamId == game.Team1.TeamId)
                            {
                                if (score.MemberWhoScored != null)
                                    svm.PlayerWhoScored = game.Team1.TeamMembers.Where(x => x.SkaterId == score.MemberWhoScored.GameMemberId).FirstOrDefault();
                                game.ScoresTeam1.Add(svm);
                            }
                            else if (getTeams[i].TeamId == game.Team2.TeamId)
                            {
                                if (score.MemberWhoScored != null)
                                    svm.PlayerWhoScored = game.Team2.TeamMembers.Where(x => x.SkaterId == score.MemberWhoScored.GameMemberId).FirstOrDefault();
                                game.ScoresTeam2.Add(svm);
                            }
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType());
                        }
                    }


                }
                game.BlocksForTeam1 = new List<BlockViewModel>();
                game.BlocksForTeam2 = new List<BlockViewModel>();
                game.AssistsForTeam1 = new List<AssistViewModel>();
                game.AssistsForTeam2 = new List<AssistViewModel>();
                game.PenaltiesForTeam1 = new List<PenaltyViewModel>();
                game.PenaltiesForTeam2 = new List<PenaltyViewModel>();
                //blocks must come after teams  members get added.
                var blocks = getGame.GameMemberBlocks.OrderBy(x => x.JamNumber);
                foreach (var block in blocks)
                {
                    try
                    {
                        BlockViewModel svm = new BlockViewModel(block.PeriodTimeRemainingMilliseconds, block.JamNumber, block.PeriodNumber, block.DateTimeBlocked, block.GameBlockId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == block.MemberWhoBlocked.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == block.MemberWhoBlocked.GameMemberId).FirstOrDefault();
                            svm.PlayerWhoBlocked = member;
                            game.BlocksForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PlayerWhoBlocked = member;
                            game.BlocksForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                //blocks must come after teams  members get added.
                var assists = getGame.GameMemberAssists.OrderBy(x => x.JamNumber);
                foreach (var assist in assists)
                {
                    try
                    {
                        AssistViewModel svm = new AssistViewModel(assist.PeriodTimeRemainingMilliseconds, assist.JamNumber, assist.PeriodNumber, assist.DateTimeAssisted, assist.GameAssistId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == assist.MemberWhoAssisted.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == assist.MemberWhoAssisted.GameMemberId).FirstOrDefault();
                            svm.PlayerWhoAssisted = member;
                            game.AssistsForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PlayerWhoAssisted = member;
                            game.AssistsForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                var penal = getGame.GameMemberPenalties.OrderBy(x => x.JamNumber);
                foreach (var pen in penal)
                {
                    try
                    {
                        PenaltyViewModel svm = new PenaltyViewModel((PenaltiesEnum)Enum.Parse(typeof(PenaltiesEnum), pen.PenaltyType.ToString()), pen.PeriodTimeRemainingMilliseconds, pen.JamNumber, pen.PeriodNumber, pen.DateTimePenaltied, pen.GamePenaltyId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == pen.MemberWhoPenaltied.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == pen.MemberWhoPenaltied.GameMemberId).FirstOrDefault();
                            svm.PenaltyAgainstMember = member;
                            game.PenaltiesForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PenaltyAgainstMember = member;
                            game.PenaltiesForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                var getJams = getGame.GameJams.OrderBy(x => x.JamNumber).ToList();
                var getJamClocks = (from xx in db.GameStopWatch
                                    where xx.StopwatchForId == id
                                    where xx.Type == (int)StopWatchTypeEnum.JamClock
                                    select xx).ToList();

                foreach (var jam in getJams)
                {
                    try
                    {
                        JamViewModel jvm = new JamViewModel(jam.JamNumber, jam.GameTimeElapsedMillisecondsStart, jam.CurrentPeriod);
                        var scoresT1 = game.ScoresTeam1.Where(x => x.JamNumber == jam.JamNumber);
                        foreach (var score in scoresT1)
                            jvm.TotalPointsForJamT1 += score.Points;

                        var scoresT2 = game.ScoresTeam2.Where(x => x.JamNumber == jam.JamNumber);
                        foreach (var score in scoresT2)
                            jvm.TotalPointsForJamT2 += score.Points;

                        var getClock = getJamClocks.Where(x => x.JamNumber == jam.JamNumber).FirstOrDefault();
                        if (getClock != null)
                        {
                            StopwatchWrapper stop = new StopwatchWrapper();
                            stop.IsClockAtZero = getClock.IsClockAtZero == 1 ? true : false;
                            stop.IsRunning = getClock.IsRunning == 1 ? true : false;
                            stop.StartTime = getClock.StartDateTime;
                            stop.TimeElapsed = getClock.TimeElapsed;
                            stop.TimeRemaining = getClock.TimeRemaining;
                            stop.TimerLength = getClock.Length;
                            jvm.JamClock = stop;
                        }

                        if (jam.Blocker1Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker1Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker1Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker1Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker1Team1.MemberNumber;
                            jvm.Blocker1T1 = tmvm;
                        }
                        if (jam.Blocker2Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker2Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker2Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker2Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker2Team1.MemberNumber;
                            jvm.Blocker2T1 = tmvm;
                        }
                        if (jam.Blocker3Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker3Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker3Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker3Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker3Team1.MemberNumber;
                            jvm.Blocker3T1 = tmvm;
                        }
                        if (jam.Blocker4Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker4Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker4Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker4Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker4Team1.MemberNumber;
                            jvm.Blocker4T1 = tmvm;
                        }
                        if (jam.PivotTeam1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.PivotTeam1.GameMemberId;
                            tmvm.SkaterLinkId = jam.PivotTeam1.MemberLinkId;
                            tmvm.SkaterName = jam.PivotTeam1.MemberName;
                            tmvm.SkaterNumber = jam.PivotTeam1.MemberNumber;
                            jvm.PivotT1 = tmvm;
                        }
                        if (jam.JammerTeam1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.JammerTeam1.GameMemberId;
                            tmvm.SkaterLinkId = jam.JammerTeam1.MemberLinkId;
                            tmvm.SkaterName = jam.JammerTeam1.MemberName;
                            tmvm.SkaterNumber = jam.JammerTeam1.MemberNumber;
                            jvm.JammerT1 = tmvm;
                        }
                        if (jam.Blocker1Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker1Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker1Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker1Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker1Team2.MemberNumber;
                            jvm.Blocker1T2 = tmvm;
                        }
                        if (jam.Blocker2Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker2Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker2Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker2Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker2Team2.MemberNumber;
                            jvm.Blocker2T2 = tmvm;
                        }
                        if (jam.Blocker3Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker3Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker3Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker3Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker3Team2.MemberNumber;
                            jvm.Blocker3T2 = tmvm;
                        }
                        if (jam.Blocker4Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker4Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker4Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker4Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker4Team2.MemberNumber;
                            jvm.Blocker4T2 = tmvm;
                        }
                        if (jam.PivotTeam2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.PivotTeam2.GameMemberId;
                            tmvm.SkaterLinkId = jam.PivotTeam2.MemberLinkId;
                            tmvm.SkaterName = jam.PivotTeam2.MemberName;
                            tmvm.SkaterNumber = jam.PivotTeam2.MemberNumber;
                            jvm.PivotT2 = tmvm;
                        }
                        if (jam.JammerTeam2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.JammerTeam2.GameMemberId;
                            tmvm.SkaterLinkId = jam.JammerTeam2.MemberLinkId;
                            tmvm.SkaterName = jam.JammerTeam2.MemberName;
                            tmvm.SkaterNumber = jam.JammerTeam2.MemberNumber;
                            jvm.JammerT2 = tmvm;
                        }

                        //gets all the lead jammers for this particular jam.
                        var getLeadJammers = jam.LeadJammers.ToList();
                        foreach (var lJam in getLeadJammers)
                        {
                            try
                            {
                                if (lJam.GameMemberId != new Guid())
                                {
                                    LeadJammerViewModel ljvm = new LeadJammerViewModel();
                                    ljvm.GameTimeInMilliseconds = lJam.GameTimeInMilliseconds;
                                    ljvm.Jammer = new TeamMembersViewModel();
                                    ljvm.Jammer.SkaterId = lJam.GameMemberId;
                                    ljvm.JamTimeInMilliseconds = lJam.JamTimeInMilliseconds;
                                    ljvm.GameLeadJamId = lJam.GameJamLeadId;
                                    jvm.LeadJammers.Add(ljvm);
                                }
                            }
                            catch (Exception exception)
                            { ErrorDatabaseManager.AddException(exception, exception.GetType()); }
                        }

                        game.Jams.Add(jvm);
                    }
                    catch (Exception exception)
                    { ErrorDatabaseManager.AddException(exception, exception.GetType()); }
                }


                var Penalties = getGame.GameMemberPenaltyBox.ToList();

                for (int i = 0; i < Penalties.Count; i++)
                {
                    SkaterInPenaltyBoxViewModel skater = new SkaterInPenaltyBoxViewModel();
                    skater.GameTimeInMillisecondsReleased = Penalties[i].GameTimeMilliSecondsReturned;
                    skater.GameTimeInMillisecondsSent = Penalties[i].GameTimeMilliSecondsSent;
                    skater.JamNumberReleased = Penalties[i].JamNumberReturned;
                    skater.JamNumberSent = Penalties[i].JamNumberSent;
                    skater.JamTimeInMillisecondsReleased = Penalties[i].JamTimeMilliSecondsReturned;
                    skater.JamTimeInMillisecondsSent = Penalties[i].JamTimeMilliSecondsSent;
                    skater.PenaltyId = Penalties[i].PenaltyIdFromGame;
                    skater.PenaltyScale = (PenaltyScaleEnum)Enum.ToObject(typeof(PenaltyScaleEnum), (int)Penalties[i].PenaltyScale);
                    skater.PenaltyType = (PenaltiesEnum)Enum.Parse(typeof(PenaltiesEnum), Penalties[i].PenaltyType);
                    skater.PenaltyNumberForSkater = Penalties[i].PenaltyNumberForSkater;
                    bool checkIfPenaltyIsAssigned = false;


                    for (int j = 0; j < game.Team1.TeamMembers.Count; j++)
                    {
                        if (game.Team1.TeamMembers[j].SkaterId == Penalties[i].Member.GameMemberId)
                        {
                            skater.PlayerSentToBox = game.Team1.TeamMembers[j];
                            game.Team1.TeamMembers[j].Penalties.Add(new PenaltyViewModel(skater.PenaltyType));
                            checkIfPenaltyIsAssigned = true;
                            break;
                        }
                    }
                    if (!checkIfPenaltyIsAssigned)
                    {
                        for (int j = 0; j < game.Team2.TeamMembers.Count; j++)
                        {
                            if (game.Team2.TeamMembers[j].SkaterId == Penalties[i].Member.GameMemberId)
                            {
                                skater.PlayerSentToBox = game.Team2.TeamMembers[j];
                                game.Team2.TeamMembers[j].Penalties.Add(new PenaltyViewModel(skater.PenaltyType));
                                checkIfPenaltyIsAssigned = true;
                                break;
                            }
                        }
                    }

                    game.PenaltyBox.Add(skater);
                }

                var getPolicies = getGame.GamePolicy;
                if (getPolicies != null)
                {
                    if (game.Policy == null)
                        game.Policy = PolicyViewModel.Instance;
                    game.Policy.AdChangeAutomaticallyChangeImage = getPolicies.AdChangeAutomaticallyChangeImage == 0 ? false : true;
                    game.Policy.AdChangeDisplayChangesInMilliSeconds = (long)getPolicies.AdChangeDisplayChangesInMilliSeconds;
                    game.Policy.AdChangeShowAdsDuringIntermission = getPolicies.AdChangeShowAdsDuringIntermission == 0 ? false : true;
                    game.Policy.AdChangeShowAdsRandomly = getPolicies.AdChangeShowAdsRandomly == 0 ? false : true;
                    game.Policy.AdChangeUseLineUpClock = getPolicies.AdChangeUseLineUpClock == 0 ? false : true;
                    game.Policy.AlwaysShowJamClock = getPolicies.AlwaysShowJamClock == 0 ? false : true;
                    game.Policy.EnableAdChange = getPolicies.EnableAdChange == 0 ? false : true;
                    game.Policy.EnableIntermissionNaming = getPolicies.EnableIntermissionNaming == 0 ? false : true;
                    game.Policy.EnableIntermissionStartOfClock = getPolicies.EnableIntermissionStartOfClock == 0 ? false : true;
                    game.Policy.FirstIntermissionNameConfirmedText = getPolicies.FirstIntermissionNameConfirmedText;
                    game.Policy.FirstIntermissionNameText = getPolicies.FirstIntermissionNameText;
                    game.Policy.GameSelectionType = (GameTypeEnum)Enum.Parse(typeof(GameTypeEnum), getPolicies.GameSelectionType);
                    game.Policy.HideClockTimeAfterBout = getPolicies.HideClockTimeAfterBout == 0 ? false : true;
                    game.Policy.IntermissionOtherText = getPolicies.IntermissionOtherText;
                    game.Policy.IntermissionStartOfClockInMilliseconds = (long)getPolicies.IntermissionStartOfClockInMilliseconds;
                    game.Policy.IntermissionStopClockEnable = getPolicies.IntermissionStopClockEnable == 0 ? false : true;
                    game.Policy.IntermissionStopClockIncrementJamNumber = getPolicies.IntermissionStopClockIncrementJamNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockIncrementPeriodNumber = getPolicies.IntermissionStopClockIncrementPeriodNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetJamNumber = getPolicies.IntermissionStopClockResetJamNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetJamTime = getPolicies.IntermissionStopClockResetJamTime == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetPeriodNumber = getPolicies.IntermissionStopClockResetPeriodNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetPeriodTime = getPolicies.IntermissionStopClockResetPeriodTime == 0 ? false : true;
                    game.Policy.JamClockControlsLineUpClock = getPolicies.JamClockControlsLineUpClock == 0 ? false : true;
                    game.Policy.JamClockControlsTeamPositions = getPolicies.JamClockControlsTeamPositions == 0 ? false : true;
                    game.Policy.JamClockTimePerJam = (long)getPolicies.JamClockTimePerJam;
                    game.Policy.LineupClockControlsStartJam = getPolicies.LineupClockControlsStartJam == 0 ? false : true;
                    game.Policy.LineUpClockPerJam = (long)getPolicies.LineUpClockPerJam;
                    game.Policy.NumberOfPeriods = (int)getPolicies.NumberOfPeriods;
                    game.Policy.PenaltyBoxControlsLeadJammer = getPolicies.PenaltyBoxControlsLeadJammer == 0 ? false : true;
                    game.Policy.PeriodClock = (long)getPolicies.PeriodClock;
                    game.Policy.PeriodClockControlsLineupJamClock = getPolicies.PeriodClockControlsLineupJamClock == 0 ? false : true;
                    game.Policy.SecondIntermissionNameConfirmedText = getPolicies.SecondIntermissionNameConfirmedText;
                    game.Policy.SecondIntermissionNameText = getPolicies.SecondIntermissionNameText;
                    game.Policy.TimeOutClock = (long)getPolicies.TimeOutClock;
                    game.Policy.TimeoutClockControlsLineupClock = getPolicies.TimeoutClockControlsLineupClock == 0 ? false : true;
                    game.Policy.TimeOutsPerPeriod = (int)getPolicies.TimeOutsPerPeriod;
                }




                //TODO: get game adverts.


                var getTimeOuts = getGame.GameTimeouts.ToList();
                foreach (var time in getTimeOuts)
                {
                    TimeOutViewModel tvm = new TimeOutViewModel();

                    tvm.TimeoutId = time.TimeOutId;
                    if (time.GameTeam != null && time.GameTeam.TeamId == game.Team1.TeamId)
                        tvm.TimeOutType = TimeOutTypeEnum.Team1;
                    else if (time.GameTeam != null && time.GameTeam.TeamId == game.Team2.TeamId)
                        tvm.TimeOutType = TimeOutTypeEnum.Team2;
                    else
                        tvm.TimeOutType = TimeOutTypeEnum.Offical;

                    if (game.TimeOuts == null)
                        game.TimeOuts = new List<TimeOutViewModel>();

                    game.TimeOuts.Add(tvm);
                }

                return game;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }