public void DeleteFeedback(int Id)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         db.ExecuteCommand("Delete from feedBacks where id={0}", Id);
     }
 }
        internal static void ScheduleGames(Guid tournaId, string pairAlgo, string matchType)
        {
            //get org id
            Guid orgId = Guid.Empty;
            DateTime startDate = new DateTime();
            using (TournaDataContext db = new TournaDataContext())
            {
                var data = db.Tournaments.Where(x => x.Id == tournaId)
                                          .Select(y => new
                                          {
                                              OrgId = y.OrganisationId,
                                              StartDate = y.StartDate
                                          }).FirstOrDefault();

                if (data == null)
                    throw new DataException("Could not generate data for tournament");

                 orgId = data.OrgId;
                 startDate = data.StartDate ;

            }

            ScheduleGames(orgId, tournaId, startDate, (PairsMatchType)(Enum.Parse(typeof(PairsMatchType), matchType)),
                (PairsAlgorithmType)(Enum.Parse(typeof(PairsAlgorithmType), pairAlgo)));
        }
 internal static void FeedbackInsert(Guid orgId, string feedbackWriterName, string feedbackContent, string feedbackWriterEmail)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         db.FeedBacks.InsertOnSubmit(new FeedBack() { FeedbackWriterName = feedbackWriterName, FeedbackContent = feedbackContent, FeedbackWriterEmail = feedbackWriterEmail, OrganisationId = orgId, DateStamp = DateTime.Now });
         db.SubmitChanges();
     }
 }
 internal static void TextContentInsert(Guid orgId, string contentType, string caption, string content)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         db.TextContents.InsertOnSubmit(new TextContent() { Caption = caption, ContentType = contentType, Content = content, OrganisationId = orgId, CreateDate=DateTime.Now });
         db.SubmitChanges();
     }
 }
    internal static OrganisationBasicInfo GetOrganisationInfo(Guid organisationId)
    {
        using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
        {
            IQueryable<OrganisationBasicInfo> orgBasicInfo = (from org in db.Organisations
                                                              where org.Id == organisationId
                                                              select new OrganisationBasicInfo { Id = org.Id, Name = org.Name, Active = org.Active, Logo = org.CompanyLogo });

            return orgBasicInfo.SingleOrDefault();
        }
    }
 public List<FeedBack> GetFeedbacks(string orgId)
 {
     Guid organisationId = new Guid(orgId);
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         var z = from fb in db.FeedBacks
                 where fb.OrganisationId == organisationId
                 orderby fb.DateStamp descending
                 select fb;
         return z.ToList();
     }
 }
 public List<TextContentItem> GetTextContents(string orgId, string contentType)
 {
     Guid organisationId = new Guid(orgId);
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         var z = from tc in db.TextContents
                 where tc.OrganisationId == organisationId && tc.ContentType == contentType
                 orderby tc.CreateDate descending
                 select new TextContentItem { Id = tc.Id, Caption = tc.Caption, Content = tc.Content,
                     CreateDate = tc.CreateDate.ToShortDateString() };
         return z.ToList();
     }
 }
 internal static string GetTournamentName(Guid tournamentId)
 {
     using (TournaDataContext db = new TournaDataContext())
     {
         Tournament tournament = db.Tournaments.SingleOrDefault(t => t.Id == tournamentId);
         if (tournament != null)
         {
             string tournamentName = tournament.TournamentName;
             return tournamentName;
         }
         else
         {
             return string.Empty;
         }
     }
 }
        public IEnumerable<DateTime> GetInvalidDates(Guid orgId)
        {
            if (this._holidayCache.ContainsKey(orgId))
                return this._holidayCache[orgId];

            //cache and return
            IEnumerable<DateTime> holidays;
            using (TournaDataContext db = new TournaDataContext())
            {
                 holidays = db.OrganisationHolidays.Where(x => x.OrganisationId == orgId)
                                                      .Select(y => y.Date).ToList();
            }

            this._holidayCache.Add(orgId, holidays);

            return holidays;
        }
        protected void btnPlayer_Click(object sender, EventArgs e)
        {
            Guid updatedByPlayerId = new Guid(Request.QueryString["PlayerId"].ToString());
            int tournamentMatchupId = int.Parse(Request.QueryString["MatchupId"].ToString());
            Button btn = sender as Button;
            //btn.CssClass = "playerSelected";

            Guid winnerPlayerId = new Guid(btn.CommandArgument);
            using (TournaDataContext tdc = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ToString()))
            {
                TournamentMatchup tm = tdc.TournamentMatchups.Single(tmu => tmu.Id == tournamentMatchupId);
                tm.Winner = winnerPlayerId;
                if (updatedByPlayerId != Guid.Empty)
                    tm.UpdatedBy = updatedByPlayerId;
                tdc.SubmitChanges();
                if (tm.NextMatchId != 0)
                {
                    TournamentMatchup nextTm = tdc.TournamentMatchups.Single(tmu => tmu.TournamentId == tm.TournamentId && tmu.MatchUpId == tm.NextMatchId);
                    TournamentMatchupManager.SetNextMatchup(tm.TournamentId, tm.MatchUpId, tm.NextMatchId, winnerPlayerId);

                    if (nextTm.PlayerA != Guid.Empty && nextTm.PlayerB != Guid.Empty) // notify A & B
                    {
                        BL.DL.MatchupsToNotifyGetResult matchupToNotify = StrongerOrg.BL.Jobs.TournamentMatchupManager.GetMatchupsToNotify(nextTm.Id).First();
                        StrongerOrg.BL.Jobs.TournamentMatchupManager.NotifyPlayers(matchupToNotify);
                        if (nextTm.NextMatchId == 0) //Final Game i sent different email template to all tournament's players.
                        {
                            StrongerOrg.BL.Jobs.TournamentMatchupManager.NotifyFinalMatchup(matchupToNotify);
                        }
                    }

                    this.lblUpdateMessage.Text = "Thank you for update the score and congratulations to the winner";
                }
                else
                {
                    tdc.Tournaments.First(t => t.Id == tm.TournamentId).IsTournamentOver = true;

                    this.lblUpdateMessage.Text = "The winner of the tournament !!!";
                    tdc.SubmitChanges();
                }

                this.btnPlayerB.Enabled = false;
                this.btnPlayerA.Enabled = false;
                this.SelectButton(btn);
            }
        }
        public List<MetaPlayer> Execute(Guid tournamentId)
        {
            //argument check
            if (tournamentId.Equals(Guid.Empty))
                throw new ArgumentNullException("tournamentId");

            List<MetaPlayer> players = null;
            using (TournaDataContext db = new TournaDataContext())
            {
                players = db.PlayersGet(null, tournamentId)
                            .Select(p => new MetaPlayer()
                            {
                                Id = p.Id,
                                PlayerName = p.Name
                            }).ToList();
            }

            return players;
        }
        private string GetEmailBody()
        {
            ListDictionary replacements = new ListDictionary();
            using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
            {
                var tournametInfo = (from t in db.Tournaments
                                     join g in db.Games on t.GameId equals g.Id
                                     where t.Id == new Guid(Request.QueryString["TournamentId"].ToString())
                                     select new
                                     {
                                         t.TournamentName,
                                         t.StartDate,
                                         t.TimeWindowStart,
                                         t.TimeWindowEnd,
                                         t.Locations,
                                         g.Title,
                                         g.ConsoleName,
                                         t.FirstPrize,
                                         t.SecondPrize,
                                         t.ThirdPrize,
                                         t.Abstract
                                     }).Single();

                replacements.Add("<% OrgId %>", this.Master.OrgBasicInfo.Id.ToString());
                replacements.Add("<% TournamentName %>", tournametInfo.TournamentName);
                replacements.Add("<% When %>", tournametInfo.StartDate.ToString("D"));
                replacements.Add("<% StartTime %>", tournametInfo.TimeWindowStart.TruncateSeconds());
                replacements.Add("<% EndTime %>", tournametInfo.TimeWindowEnd.TruncateSeconds());
                replacements.Add("<% Where %>", tournametInfo.Locations ?? string.Empty);
                replacements.Add("<% GameName %>", tournametInfo.Title ?? string.Empty);
                replacements.Add("<% FirstPrize %>", string.IsNullOrEmpty(tournametInfo.FirstPrize) ? "N/A" : tournametInfo.FirstPrize);
                replacements.Add("<% SecondPrize %>", string.IsNullOrEmpty(tournametInfo.SecondPrize) ? "N/A" : tournametInfo.SecondPrize);
                replacements.Add("<% ThirdPrize %>", string.IsNullOrEmpty(tournametInfo.ThirdPrize) ? "N/A" : tournametInfo.ThirdPrize);
                replacements.Add("<% TournamentId %>", Request.QueryString["TournamentId"].ToString());
                replacements.Add("<% Abstract %>", tournametInfo.Abstract ?? string.Empty);
                replacements.Add("<% ConsoleName %>", tournametInfo.ConsoleName ?? string.Empty);
            }

            MailDefinition message = new MailDefinition();
            message.BodyFileName = @"~\EmailTemplate\TournamentInvintation.htm";
            MailMessage msgHtml = message.CreateMailMessage("*****@*****.**", replacements, new LiteralControl());
            return msgHtml.Body;
        }
        public static List<Matchup> GetTournamentMatchups(Guid tournamentId)
        {
            using (TournaDataContext db = new TournaDataContext())
            {
                List<Matchup> matchups = db.TournamentMatchups.Where(y => y.TournamentId == tournamentId).
                     Select(y =>
                         new Matchup
                         {
                             Id = y.Id,
                             Start = y.Start,
                             PlayerAId = y.PlayerA,
                             PlayerA = db.Players.Where(p => p.Id == y.PlayerA).Select(n => n.Name).First(),
                             PlayerBId = y.PlayerB,
                             PlayerB = db.Players.Where(p => p.Id == y.PlayerB).Select(n => n.Name).First(),
                             ScoreA = y.ScoreA,
                             ScoreB = y.ScoreB,
                             WinnerId = y.Winner,
                             //WinnerName = (y.Winner.HasValue) ? (y.PlayerA == y.Winner) ? db.Players.Where(p => p.Id == y.PlayerA).Select(n => n.Name).First() :
                             //db.Players.Where(p => p.Id == y.PlayerB).Select(n => n.Name).First() : string.Empty,
                             MatchupId = y.MatchUpId,
                             Round = y.Round,
                             NextMatchId = y.NextMatchId

                             //Score = (y.ScoreA.HasValue && y.ScoreB.HasValue) ? string.Format("{0}-{1}", y.ScoreA.Value.ToString(), y.ScoreB.Value.ToString()) : string.Empty
                         })
                     .ToList();
                matchups.ForEach(m =>
                {
                    if (m.WinnerId.HasValue)
                    {
                        m.WinnerName = (m.PlayerAId == m.WinnerId.Value) ? m.PlayerA : m.PlayerB;
                    }
                    else
                    {
                        m.WinnerName = "--";
                    }
                    m.PlayerA = (string.IsNullOrEmpty(m.PlayerA)) ? "--" : m.PlayerA;
                    m.PlayerB = (string.IsNullOrEmpty(m.PlayerB)) ? "--" : m.PlayerB;
                });
                return matchups;
            }
        }
 public static void Save(Guid tournamentId, List<Matchup> matchupList)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         IEnumerable<TournamentMatchup> e = matchupList.Select(ml => new TournamentMatchup()
         {
             MatchUpId = ml.MatchupId,
             Start = ml.Start,
             PlayerA = ml.PlayerAId,
             PlayerB = ml.PlayerBId,
             TournamentId = tournamentId,
             End = ml.End,
             Round = ml.Round,
             NextMatchId = ml.NextMatchId
         });
         //db.Tournaments.Single(t => t.Id == tournamentId).IsOpen = false;
         db.TournamentMatchups.InsertAllOnSubmit(e);
         db.SubmitChanges();
     }
 }
        public List<MetaPlayer> Execute(Guid tournamentId)
        {
            //argument check
            if (tournamentId.Equals(Guid.Empty))
                throw new ArgumentNullException("tournamentId");

            //use LINQ to order?
            //will we be using LINQ?
            //convert datareader to LINQ using yield keyword.
            List<MetaPlayer> players = null;
            using (TournaDataContext db = new TournaDataContext())
            {
                players = db.PlayersGet(null, tournamentId)
                            .OrderBy(x => x.Id)
                            .Select(p => new MetaPlayer(){
                                                            Id = p.Id,
                                                            PlayerName = p.Name
                                                         }).ToList();
            }

            return players;
        }
        private void SetPageValues(Guid orgId, int tournamentMatchupId)
        {
            using (TournaDataContext tdc = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ToString()))
            {
                List<MatchupGetResult> matchUps = tdc.MatchupGet(tournamentMatchupId).ToList();
                if (matchUps.Count > 0 && matchUps[0].PlayerBId.HasValue)
                {
                    MatchupGetResult matchUp = matchUps.First();
                    this.btnPlayerA.Text = matchUp.PlayerAName;
                    this.btnPlayerA.CommandArgument = matchUp.PlayerAId.ToString();
                    this.btnPlayerB.Text = matchUp.PlayerBName;
                    this.btnPlayerB.CommandArgument = matchUp.PlayerBId.ToString();
                    this.dvGameDetails.DataSource = matchUps;
                    this.dvGameDetails.DataBind();

                    //if (matchUp.End < DateTime.Now)
                    {
                        if (matchUp.Winner.HasValue)
                        {
                            this.SelectButton(matchUp.Winner.Equals(matchUp.PlayerAId) ? this.btnPlayerA : this.btnPlayerB);

                            this.btnPlayerB.Enabled = false;
                            this.btnPlayerA.Enabled = false;
                            this.lblClickOnWinner.Visible = false;
                            string scoreUpdatedBy = string.Empty;
                            if (matchUp.UpdatedBy != null)
                            {
                                scoreUpdatedBy = (matchUp.UpdatedBy.Value.Equals(matchUp.PlayerAId)) ? matchUp.PlayerAName : matchUp.PlayerBName;
                            }
                            else
                            {
                                scoreUpdatedBy = "Moderator";
                            }

                            this.lblUpdateMessage.Text = string.Format("The score was updated by <i>{0}</i>. In case of discrepancy contact moderator", scoreUpdatedBy);
                        }
                        else
                        {
                            this.btnPlayerB.Enabled = true;
                            this.btnPlayerA.Enabled = true;
                        }
                    }
                    //else
                    //{

                    //    this.btnPlayerB.Enabled = true;
                    //    this.btnPlayerA.Enabled = false;

                    //    this.lblUpdateMessage.Text = string.Format("The score update will be open from {0:f}", matchUp.End);
                    //}
                }
                else
                {

                    this.lblUpdateMessage.Text = "The Link is not valid any more, contact your moderator to find out why";
                    this.btnPlayerB.Enabled = false;
                    this.btnPlayerA.Enabled = false;
                }

            }
        }
        internal static void ScheduleGames(TournamentInfo tournamentInfo)
        {
            //check arguments that are needed
            if (tournamentInfo == null)
                throw new ArgumentNullException("tournamentInfo");

            if (tournamentInfo.TournamentId == Guid.Empty)
                throw new ArgumentNullException("TorunamentId");

            if (tournamentInfo.OrganisationId == Guid.Empty)
                throw new ArgumentNullException("OrganisationId");

            if (tournamentInfo.StartDate == new DateTime())
                throw new ArgumentException("Incorrect tournament start date");

            //set up helpers.
            //need current culture.
            CultureManager cultManager = new CultureManager(tournamentInfo.OrganisationId);

            PlayerManager playerManager = new PlayerManager();
            playerManager.AlgoType = tournamentInfo.PairAlgo;
            playerManager.MatchType = tournamentInfo.MatchType;

            DateTime startDate = tournamentInfo.StartDate;

            IEnumerable<PlayersEntity> playerPairs = playerManager.BuildPairs( tournamentInfo.TournamentId);

            int i = 0;
            int numberOfGamesPerDay = 3;
            DateTime dts = startDate;
            List<Matchup> scheds = new List<Matchup>();
            //schedule 3 games per day within 15 min intervals

            IEnumerator<DateTime> dayEnumerator = cultManager.GetNextBusinessDay(startDate).GetEnumerator();

            foreach (PlayersEntity matches in playerPairs)
            {
                if ((i % numberOfGamesPerDay) == 0)
                {
                    dayEnumerator.MoveNext();
                    dts = dayEnumerator.Current;
                    dts = new DateTime(dts.Year, dts.Month, dts.Day, tournamentInfo.TimeWindowStart, 0, 0);
                }

                DateTime dte = dts.AddMinutes(15);
                //insert here
                scheds.Add(new Matchup()
                                {
                                    TournamentId = tournamentInfo.TournamentId,
                                    PlayerAId = matches.PlayerAId,
                                    PlayerA = matches.PlayerAName,
                                    PlayerBId = matches.PlayerBId,
                                    PlayerB = matches.PlayerBName,
                                    Start = dts,
                                    End = dts.AddMinutes(15) // i need end date, otherwise i cant insert.
                                });
                dts = dte;
                i++;
            }

            using (TournaDataContext db = new TournaDataContext())
            {

                //db.TournamentMatchups.DeleteAllOnSubmit(db.TournamentMatchups.Where(x => x.TournamentId == tournamentInfo.TournamentId));
                //db.TournamentMatchups.InsertAllOnSubmit(scheds);
                //db.SubmitChanges();
            }
        }
 internal static DateTime GetTournamentStartDate(Guid tournamentId)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         DateTime d = (from t in db.Tournaments
                       where t.Id == tournamentId
                       select t.StartDate).SingleOrDefault<DateTime>();
         return d;
     }
 }
 internal static bool IsTournamentOpen(Guid orgId, Guid tournamentId)
 {
     using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
     {
         Tournament tournament = db.Tournaments.Single(t => t.Id == tournamentId && t.StartDate >= DateTime.Now
             && t.IsTournamentOver == false
             && t.NumberOfPlayersLimit >= db.Players2Tournaments.Where(p2t => p2t.TournamentId == tournamentId).Count());
         return (tournament != null);
     }
 }
 internal static MatchupGetResult GetMatchupInfo(int matchupId)
 {
     using (TournaDataContext db = new TournaDataContext())
     {
         MatchupGetResult tmup = db.MatchupGet(matchupId).First();
         return tmup;
     }
 }
 internal static void ResetScore(int id)
 {
     using (TournaDataContext db = new TournaDataContext())
     {
         db.TournamentMatchups.Single(tm => tm.Id == id).Winner = null;
         db.SubmitChanges();
     }
 }
 internal static void Delete(Guid tournamentId)
 {
     using (TournaDataContext db = new TournaDataContext())
     {
         db.TournamentMatchups.DeleteAllOnSubmit(
             db.TournamentMatchups.Where(t => t.TournamentId == tournamentId));
         // need to be fix
         //db.Players2Tournaments.DeleteAllOnSubmit(db.Players2Tournaments.Where(t => t.TournamentId == tournamentId));
         db.SubmitChanges();
     }
 }
 internal static void SetNextMatchup(Guid tournamentId, int matchUpId, int nextMatchId, Guid winnerPlayerId)
 {
     using (TournaDataContext tdc = new TournaDataContext())
     {
         if (nextMatchId != 0)
         {
             TournamentMatchup nextTm = tdc.TournamentMatchups.Single(tmu => tmu.TournamentId == tournamentId && tmu.MatchUpId == nextMatchId);
             var nextMatchup2Players = tdc.TournamentMatchups.Where(tmu => tmu.TournamentId == tournamentId && tmu.NextMatchId == nextMatchId).Select(tmu => new { tmu.Id, tmu.MatchUpId }).OrderBy(t => t.Id);
             if (nextMatchup2Players.Count() > 0)
             {
                 if (nextMatchup2Players.First().MatchUpId == matchUpId)
                 {
                     nextTm.PlayerA = winnerPlayerId;
                 }
                 else
                 {
                     nextTm.PlayerB = winnerPlayerId;
                 }
             }
             else
             {
                 throw new ArgumentException("expected 2 matchups for next round id");
             }
             tdc.SubmitChanges();
         }
     }
 }
 internal static void UpdateMatchup(Guid tournamentId, int matchUpId, DateTime newStartDate, Guid playerAId, Guid playerBId, Guid winnerId)
 {
     using (TournaDataContext db = new TournaDataContext())
     {
         TournamentMatchup tmu = db.TournamentMatchups.Single(tm => tm.TournamentId == tournamentId && tm.MatchUpId == matchUpId);
         tmu.Start = newStartDate;
         tmu.PlayerA = playerAId;
         tmu.PlayerB = playerBId;
         if (winnerId == Guid.Empty)
         {
             tmu.Winner = null;
         }
         else
         {
             tmu.Winner = winnerId;
         }
         db.SubmitChanges();
     }
 }