async private void timerRoundBtn_Clicked(object sender, EventArgs e)
        {
            if (dteRoundTimeEnd > DateTime.Now)
            {
                var answer = await DisplayAlert("Round In Progress", "Would you like to cancel the current timer?", "Yes", "No");

                if (answer)
                {
                    //Update round's end-time
                    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                    {
                        TournamentMainRound round = new TournamentMainRound();
                        round = conn.GetWithChildren <TournamentMainRound>(intRoundId);
                        round.RoundTimeEnd = DateTime.Now;
                        conn.Update(round);
                        dteRoundTimeEnd = round.RoundTimeEnd ?? DateTime.Now;
                    }

                    //Cancel any pending notifications
                    CrossLocalNotifications.Current.Cancel(cintMidNotifyId);
                    CrossLocalNotifications.Current.Cancel(cintEndNotifyId);

                    App.MasterMainPage.CancelRoundTimer();
                }
                return;
            }
            else
            {
                timerPopup.IsVisible   = true;
                timerOptionsEntry.Text = intDefaultRoundLength.ToString();
            }
        }
        //Delete the last round
        async private void deleteRoundBtn_Activated(object sender, EventArgs e)
        {
            if (objTournMain.Rounds.Count == 0)
            {
                await DisplayAlert("Warning!", "There are no rounds to actually delete!", "Ugh");

                return;
            }

            var confirmed = await DisplayAlert("Confirm", "Do you want to delete Round " + objTournMain.Rounds.Count + "?  This cannot be undone!", "Yes", "No");

            if (confirmed)
            {
                using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                {
                    this.IsBusy = true;
                    try
                    {
                        //Grab the latest round and delete it
                        TournamentMainRound round = objTournMain.Rounds[objTournMain.Rounds.Count - 1];
                        conn.Delete(round, true);
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert("Warning!", "Error deleting round from tournament! " + ex.Message, "OK");
                    }

                    OnAppearing();
                }
            }
        }
        public Tournaments_RoundInfo(string strTitle, int intRoundId, int intRoundCount)
        {
            InitializeComponent();
            Title           = strTitle;
            this.intRoundId = intRoundId;

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                TournamentMainRound round = new TournamentMainRound();
                round = conn.GetWithChildren <TournamentMainRound>(intRoundId);

                bool blnEnableRows = (round.Number < intRoundCount ? false : true);

                //Set using the ViewModel version.  This allows being able to manipulate back and forth across the class properties, while displaying as intended on the GUI
                //while also ensuring none of the goings ons of the properties touching each other don't occur without this specific view model (such as the SQL table updates)
                ObservableCollection <TournamentMainRoundTable_ViewModel> lstTables = new ObservableCollection <TournamentMainRoundTable_ViewModel>();
                foreach (TournamentMainRoundTable table in round.Tables)
                {
                    lstTables.Add(new TournamentMainRoundTable_ViewModel(table, blnEnableRows));
                }
                tournamentTableListView.ItemsSource = lstTables;

                if (!blnEnableRows)
                {
                    timerRoundBtn.IsVisible             = false;
                    tournamentTableListView.ItemTapped -= tournamentTableListView_ItemTapped;
                }
                else
                {
                    timerRoundBtn.IsVisible = true;
                }
            }
        }
        public Tournaments_RoundInfo(Tournaments_AllInfo allInfoPage, string strTitle, int intRoundId, int intRoundCount)
        {
            InitializeComponent();
            Title = strTitle;
            intDefaultRoundLength = allInfoPage.intDefaultRoundLength;
            this.intRoundId       = intRoundId;

            //Tie the loading Overlay to the main page since this is what will be flagged as "IsBusy" when generating new rounds etc.
            loadingOverlay.BindingContext = allInfoPage;

            timerRoundBtn_VM             = new TournamentMainRoundInfoTimer_ViewModel();
            timerRoundBtn.BindingContext = timerRoundBtn_VM;

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                TournamentMainRound round = new TournamentMainRound();
                round          = conn.GetWithChildren <TournamentMainRound>(intRoundId);
                intRoundNumber = round.Number;

                bool blnEnableRows = (round.Number < intRoundCount ? false : true);

                blnEnableRows = true;  //Keeping them all enabled for now

                //Set using the ViewModel version.  This allows being able to manipulate back and forth across the class properties, while displaying as intended on the GUI
                //while also ensuring none of the goings ons of the properties touching each other don't occur without this specific view model (such as the SQL table updates)
                ObservableCollection <TournamentMainRoundTable_ViewModel> lstTables = new ObservableCollection <TournamentMainRoundTable_ViewModel>();
                foreach (TournamentMainRoundTable table in round.Tables)
                {
                    lstTables.Add(new TournamentMainRoundTable_ViewModel(table, blnEnableRows));
                }
                tournamentTableListView.ItemsSource = lstTables;

                if (!blnEnableRows)
                {
                    timerRoundBtn.IsVisible             = false;
                    tournamentTableListView.ItemTapped -= tournamentTableListView_ItemTapped;
                }
                else
                {
                    timerRoundBtn.IsVisible = true;

                    //If the round time started previously, keep it going
                    if (round.RoundTimeEnd > DateTime.Now)
                    {
                        dteRoundTimeEnd = round.RoundTimeEnd ?? DateTime.Now;
                        TimeSpan time = (round.RoundTimeEnd ?? DateTime.Now) - DateTime.Now;
                        App.MasterMainPage.RoundTimer(time, Convert.ToInt32(time.TotalSeconds), ref timerRoundBtn_VM);
                    }
                }
            }
        }
Beispiel #5
0
        // POST api/values (CREATE)
        public string Post([FromBody] string value)
        {
            if (!Utilities.IsValidated(Request.Headers))
            {
                return("Validation fail");
            }

            try
            {
                TournamentMainRound round = JsonConvert.DeserializeObject <TournamentMainRound>(JsonConvert.DeserializeObject(value).ToString());

                using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["XWTWebConnectionString"].ToString()))
                {
                    sqlConn.Open();

                    using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentRoundTimer_UPDATE", sqlConn))
                    {
                        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@RoundId", round.Id);
                        sqlCmd.Parameters.AddWithValue("@RoundTimeEnd", round.RoundTimeEnd);

                        using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                        {
                            while (sqlReader.Read())
                            {
                                TournamentsController tourns = new TournamentsController();

                                //returnTournaments.Add(JsonConvert.DeserializeObject<TournamentMain>(JsonConvert.DeserializeObject(tourns.Get(sqlReader.GetInt32(sqlReader.GetOrdinal("UserAccountId")), sqlReader.GetInt32(sqlReader.GetOrdinal("Id")))).ToString()));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return("POST: SUCCESS");
        }
        private void saveTimerRoundBtn_Clicked(object sender, EventArgs e)
        {
            this.IsBusy = true;

            //int intTime = Convert.ToInt16(timerOptionsPicker.Items[timerOptionsPicker.SelectedIndex]);
            int intTime = Convert.ToInt16(timerOptionsEntry.Text);

            intTime *= 60; //Converting to seconds

            //Set the end time for the round
            DateTime roundTimeMid = DateTime.Now.AddSeconds(intTime / 2);
            DateTime roundTimeEnd = DateTime.Now.AddSeconds(intTime);

            //Set phone notification
            CrossLocalNotifications.Current.Cancel(cintMidNotifyId);
            CrossLocalNotifications.Current.Cancel(cintEndNotifyId);

            CrossLocalNotifications.Current.Show("Round " + intRoundNumber.ToString() + " is halfway over.", "Almost there!", cintMidNotifyId, roundTimeMid);
            CrossLocalNotifications.Current.Show("Round " + intRoundNumber.ToString() + " is over.", "Finish your round.", cintEndNotifyId, roundTimeEnd);

            //Get the TimeSpan and set the round timer right away
            TimeSpan time = roundTimeEnd - DateTime.Now;

            App.MasterMainPage.RoundTimer(time, intTime, ref timerRoundBtn_VM);

            //Save what the end time is at so that the timer is accurate if returning later
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                TournamentMainRound round = new TournamentMainRound();
                round = conn.GetWithChildren <TournamentMainRound>(intRoundId);
                round.RoundTimeEnd = roundTimeEnd;
                conn.Update(round);

                dteRoundTimeEnd = roundTimeEnd;
            }

            timerPopup.IsVisible = false;
            this.IsBusy          = false;
        }
        private bool StartRoundPreCheck(ref bool blnSwiss)
        {
            //Make sure we actually have players
            if (objTournMain.Players.Count == 0)
            {
                DisplayAlert("Warning!", "You must add players first to this tournament!", "D'oh!");
                return(false);
            }

            //Housekeeping with the latest round
            if (objTournMain.Rounds.Count > 0)
            {
                //Grab the latest information before checking the scores and calculating them
                using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                {
                    objTournMain = new TournamentMain();
                    objTournMain = conn.GetWithChildren <TournamentMain>(intTournID, true);
                    Utilities.CalculatePlayerScores(ref objTournMain);

                    conn.UpdateWithChildren(objTournMain); //Update any other information that was saved such as Bye counts and such
                }

                TournamentMainRound latestRound = objTournMain.Rounds[objTournMain.Rounds.Count - 1];
                blnSwiss = latestRound.Swiss; //Check if the last round was a Swiss Round or not

                //Before starting a new round, make sure we're not missing any scores
                foreach (TournamentMainRoundTable table in latestRound.Tables)
                {
                    if (!table.Player1Winner && !table.Player2Winner)
                    {
                        DisplayAlert("Warning!", "Verify that all tables are completed for the current round!", "D'oh!");
                        return(false);
                    }
                }
            }

            return(true);
        }
        private void StartRound(bool blnSwiss, int intTableCount)
        {
            bool blnProceed = false;

            //Create a new round
            TournamentMainRound round = new TournamentMainRound();

            round.TournamentId = intTournID;
            round.Number       = objTournMain.Rounds.Count + 1;
            round.Swiss        = blnSwiss;

            List <TournamentMainPlayer> lstActiveTournamentPlayers      = new List <TournamentMainPlayer>();
            List <TournamentMainPlayer> lstActiveTournamentPlayers_Byes = new List <TournamentMainPlayer>();

            if (blnSwiss)
            {
                blnProceed = SetupSwissPlayers(ref lstActiveTournamentPlayers, ref lstActiveTournamentPlayers_Byes);
            }
            else
            {
                blnProceed = SetupSingleEliminationPlayers(ref lstActiveTournamentPlayers, intTableCount);
            }

            //If players weren't able to be successfully setup correctly, don't create a new round
            if (!blnProceed)
            {
                return;
            }

            //Create each table, pair 'em up
            TournamentMainRoundTable roundTable = new TournamentMainRoundTable();

            foreach (TournamentMainPlayer player in lstActiveTournamentPlayers)
            {
                if (roundTable.Player1Id != 0 && roundTable.Player2Id != 0)
                {
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                    roundTable = new TournamentMainRoundTable();
                }

                if (roundTable.Player1Id == 0)
                {
                    roundTable.Number    = round.Tables.Count + 1;
                    roundTable.Player1Id = player.PlayerId;
                }
                else if (roundTable.Player2Id == 0)
                {
                    roundTable.Player2Id = player.PlayerId;
                }
            }

            //If the last table of non-manual byes is an odd-man, set table/player as a bye
            if (roundTable.Player2Id == 0)
            {
                roundTable.Bye           = true;
                roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                roundTable.Player1Winner = true;
            }

            setRoundTableNames(ref roundTable);
            round.Tables.Add(roundTable);


            //If a manual bye (such as first-round byes at a tournament), add these players now
            if (lstActiveTournamentPlayers_Byes.Count > 0)
            {
                lstActiveTournamentPlayers_Byes.Shuffle();
                foreach (TournamentMainPlayer player in lstActiveTournamentPlayers_Byes)
                {
                    roundTable               = new TournamentMainRoundTable();
                    roundTable.Number        = round.Tables.Count + 1;
                    roundTable.Player1Id     = player.PlayerId;
                    roundTable.Bye           = true;
                    roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                    roundTable.Player1Winner = true;
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                }
            }

            //Add/Save the round
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                try
                {
                    conn.Update(objTournMain); //Update any other information that was saved such as Bye counts and such
                    foreach (TournamentMainPlayer player in objTournMain.Players)
                    {
                        conn.Update(player);  //Player info can change due to flagging/unflagging a player Bye
                    }
                    conn.InsertWithChildren(round, true);
                }
                catch (Exception ex)
                {
                    DisplayAlert("Warning!", "Error adding round to tournament! " + ex.Message, "OK");
                }

                OnAppearing();
            }
        }
Beispiel #9
0
        public void GetAllTournamentInfo(SqlConnection sqlConn, ref List <TournamentMain> returnTournaments)
        {
            //Grab all the players associated with this tournament
            foreach (TournamentMain newTournament in returnTournaments)
            {
                using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsPlayers_GET", sqlConn))
                {
                    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@TournamentId", newTournament.Id);
                    using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                    {
                        while (sqlReader.Read())
                        {
                            TournamentMainPlayer player = new TournamentMainPlayer
                            {
                                Id                 = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                TournamentId       = sqlReader.GetInt32(sqlReader.GetOrdinal("TournamentId")),
                                PlayerId           = sqlReader.GetInt32(sqlReader.GetOrdinal("PlayerId")),
                                OpponentIdsBlobbed = sqlReader.GetString(sqlReader.GetOrdinal("OpponentIds")),
                                PlayerName         = sqlReader.GetString(sqlReader.GetOrdinal("PlayerName")),
                                Active             = sqlReader.GetBoolean(sqlReader.GetOrdinal("Active")),
                                Bye                = sqlReader.GetBoolean(sqlReader.GetOrdinal("Bye")),
                                ByeCount           = sqlReader.GetInt32(sqlReader.GetOrdinal("ByeCount")),
                                RoundsPlayed       = sqlReader.GetInt32(sqlReader.GetOrdinal("RoundsPlayed")),
                                Rank               = sqlReader.GetInt32(sqlReader.GetOrdinal("Rank")),
                                Score              = sqlReader.GetInt32(sqlReader.GetOrdinal("Score")),
                                MOV                = sqlReader.GetInt32(sqlReader.GetOrdinal("MOV")),
                                SOS                = sqlReader.GetDecimal(sqlReader.GetOrdinal("SOS")),
                                API_UserAccountId  = sqlReader.GetInt32(sqlReader.GetOrdinal("UserAccountId"))
                            };

                            newTournament.Players.Add(player);
                        }
                    }
                }

                using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRounds_GET", sqlConn))
                {
                    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@TournamentId", newTournament.Id);
                    using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                    {
                        while (sqlReader.Read())
                        {
                            TournamentMainRound round = new TournamentMainRound
                            {
                                Id           = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                TournamentId = sqlReader.GetInt32(sqlReader.GetOrdinal("TournamentId")),
                                Number       = sqlReader.GetInt32(sqlReader.GetOrdinal("Number")),
                                Swiss        = sqlReader.GetBoolean(sqlReader.GetOrdinal("Swiss"))
                            };

                            if (!sqlReader.IsDBNull(sqlReader.GetOrdinal("RoundTimeEnd")))
                            {
                                round.RoundTimeEnd = sqlReader.GetDateTime(sqlReader.GetOrdinal("RoundTimeEnd"));
                            }

                            newTournament.Rounds.Add(round);
                        }
                    }
                }

                foreach (TournamentMainRound round in newTournament.Rounds)
                {
                    using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRoundsTables_GET", sqlConn))
                    {
                        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@RoundId", round.Id);
                        using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                        {
                            while (sqlReader.Read())
                            {
                                TournamentMainRoundTable table = new TournamentMainRoundTable
                                {
                                    Id            = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                    RoundId       = sqlReader.GetInt32(sqlReader.GetOrdinal("RoundId")),
                                    Number        = sqlReader.GetInt32(sqlReader.GetOrdinal("Number")),
                                    TableName     = sqlReader.GetString(sqlReader.GetOrdinal("TableName")),
                                    ScoreTied     = sqlReader.GetBoolean(sqlReader.GetOrdinal("ScoreTied")),
                                    Bye           = sqlReader.GetBoolean(sqlReader.GetOrdinal("Bye")),
                                    Player1Id     = sqlReader.GetInt32(sqlReader.GetOrdinal("Player1Id")),
                                    Player1Name   = sqlReader.GetString(sqlReader.GetOrdinal("Player1Name")),
                                    Player1Winner = sqlReader.GetBoolean(sqlReader.GetOrdinal("Player1Winner")),
                                    Player1Score  = sqlReader.GetInt32(sqlReader.GetOrdinal("Player1Score")),
                                    Player2Id     = sqlReader.GetInt32(sqlReader.GetOrdinal("Player2Id")),
                                    Player2Name   = sqlReader.GetString(sqlReader.GetOrdinal("Player2Name")),
                                    Player2Winner = sqlReader.GetBoolean(sqlReader.GetOrdinal("Player2Winner")),
                                    Player2Score  = sqlReader.GetInt32(sqlReader.GetOrdinal("Player2Score"))
                                };
                                round.Tables.Add(table);
                            }
                        }
                    }
                }
            }
        }
        public Tournaments_RoundInfoTableEdit(int intRoundId, int intTableId)
        {
            InitializeComponent();

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                currentRound = new TournamentMainRound();
                currentRound = conn.GetWithChildren <TournamentMainRound>(intRoundId);

                lstPlayers = new List <clsPlayerInfo>();

                foreach (TournamentMainRoundTable table in currentRound.Tables)
                {
                    if (table.Player1Id > 0)
                    {
                        lstPlayers.Add(new clsPlayerInfo(table.Player1Id, table.Player1Name, table.Id));
                    }

                    if (table.Player2Id > 0)
                    {
                        lstPlayers.Add(new clsPlayerInfo(table.Player2Id, table.Player2Name, table.Id));
                    }

                    if (table.Id == intTableId)
                    {
                        currentTable = table;

                        Title           = table.TableName;
                        lblPlayer1.Text = table.Player1Name;
                        lblPlayer2.Text = table.Player2Name;

                        intPlayer1Id = table.Player1Id;
                        intPlayer2Id = table.Player2Id;
                    }
                }

                pckPlayer1.ItemsSource = lstPlayers.OrderBy(obj => obj.PlayerName).Where(o => o.PlayerId != intPlayer2Id).ToList();
                pckPlayer2.ItemsSource = lstPlayers.OrderBy(obj => obj.PlayerName).Where(o => o.PlayerId != intPlayer1Id).ToList();

                //Set the first selected item as the current player
                pckPlayer1.SelectedIndexChanged -= pckPlayer1_SelectedIndexChanged;
                pckPlayer2.SelectedIndexChanged -= pckPlayer2_SelectedIndexChanged;

                for (int i = 1; i <= 2; i++)
                {
                    int    intIndex  = -1;
                    Picker pckPlayer = (i == 1 ? pckPlayer1 : pckPlayer2);

                    foreach (clsPlayerInfo item in pckPlayer.ItemsSource)
                    {
                        intIndex++;
                        if (item.PlayerId == (i == 1 ? intPlayer1Id : intPlayer2Id))
                        {
                            pckPlayer.SelectedIndex = intIndex;
                            break;
                        }
                    }
                }

                pckPlayer1.SelectedIndexChanged += pckPlayer1_SelectedIndexChanged;
                pckPlayer2.SelectedIndexChanged += pckPlayer2_SelectedIndexChanged;
            }
        }
        //Start next round
        private void startRoundBtn_ToolbarItem_Activated(object sender, EventArgs e)
        {
            //Make sure we actually have players
            if (objTournMain.Players.Count == 0)
            {
                DisplayAlert("Warning!", "You must add players first to this tournament!", "D'oh!");
                return;
            }

            //Housekeeping with the latest round
            if (objTournMain.Rounds.Count > 0)
            {
                //Grab the latest information before checking the scores and calculating them
                using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                {
                    objTournMain = new TournamentMain();
                    objTournMain = conn.GetWithChildren <TournamentMain>(intTournID, true);
                }

                TournamentMainRound latestRound = objTournMain.Rounds[objTournMain.Rounds.Count - 1];

                //Before starting a new round, make sure we're not missing any scores
                foreach (TournamentMainRoundTable table in latestRound.Tables)
                {
                    if (!table.Player1Winner && !table.Player2Winner)
                    {
                        DisplayAlert("Warning!", "Verify that all tables are completed for the current round!", "D'oh!");
                        return;
                    }
                }

                Utilities.CalculatePlayerScores(ref objTournMain);
            }

            //Grab list of currently active players in the tournament
            Dictionary <int, List <TournamentMainPlayer> > dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();

            List <TournamentMainPlayer> lstActiveTournamentPlayers      = new List <TournamentMainPlayer>();
            List <TournamentMainPlayer> lstActiveTournamentPlayers_Byes = new List <TournamentMainPlayer>();

            foreach (TournamentMainPlayer player in objTournMain.Players)
            {
                if (player.Active)
                {
                    TournamentMainPlayer roundPlayer = new TournamentMainPlayer();
                    roundPlayer.PlayerId = player.PlayerId;
                    roundPlayer.Score    = player.Score;

                    if (!player.Bye)
                    {
                        lstActiveTournamentPlayers.Add(roundPlayer);
                    }
                    else
                    {
                        lstActiveTournamentPlayers_Byes.Add(roundPlayer);
                        player.Bye = false;  //No longer has a Bye for the next round
                        player.ByeCount++;
                    }
                }
            }



            //Create a new round
            TournamentMainRound round = new TournamentMainRound();

            round.TournmentId = intTournID;
            round.Number      = objTournMain.Rounds.Count + 1;

            if (objTournMain.Rounds.Count == 0)
            {
                //First round, completely random player pairings
                lstActiveTournamentPlayers.Shuffle();
            }
            else
            {
                //Subsequent rounds, group up players with same win count as much as possible and randomize
                dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    dctActiveTournamentPlayerScores.Add(i, new List <TournamentMainPlayer>());
                    foreach (TournamentMainPlayer activePlayer in lstActiveTournamentPlayers)
                    {
                        if (i == activePlayer.Score)
                        {
                            dctActiveTournamentPlayerScores[i].Add(activePlayer);
                        }
                    }

                    dctActiveTournamentPlayerScores[i].Shuffle(); //Shuffle all the players in each win bracket
                }

                //Clear out the active list, then go down the list and re-add them back in.
                lstActiveTournamentPlayers.Clear();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    if (dctActiveTournamentPlayerScores.ContainsKey(i))
                    {
                        foreach (TournamentMainPlayer activePlayer in dctActiveTournamentPlayerScores[i])
                        {
                            lstActiveTournamentPlayers.Add(activePlayer);
                        }
                    }
                }

                //If odd number of players, the last in the list will get a Bye
                //Get the lowest ranked player that hasn't had a bye already
                if (lstActiveTournamentPlayers.Count % 2 != 0)
                {
                    foreach (TournamentMainPlayer player in objTournMain.Players.OrderByDescending(obj => obj.Rank).ToList())
                    {
                        if (player.ByeCount == 0)
                        {
                            for (int i = lstActiveTournamentPlayers.Count - 1; i > 0; i--)
                            {
                                if (lstActiveTournamentPlayers[i].PlayerId == player.PlayerId)
                                {
                                    TournamentMainPlayer roundPlayer = lstActiveTournamentPlayers[i];
                                    lstActiveTournamentPlayers.RemoveAt(i);
                                    lstActiveTournamentPlayers.Add(roundPlayer);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }

            //Create each table, pair 'em up
            TournamentMainRoundTable roundTable = new TournamentMainRoundTable();

            foreach (TournamentMainPlayer player in lstActiveTournamentPlayers)
            {
                if (roundTable.Player1Id != 0 && roundTable.Player2Id != 0)
                {
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                    roundTable = new TournamentMainRoundTable();
                }

                if (roundTable.Player1Id == 0)
                {
                    roundTable.Number    = round.Tables.Count + 1;
                    roundTable.Player1Id = player.PlayerId;
                }
                else if (roundTable.Player2Id == 0)
                {
                    roundTable.Player2Id = player.PlayerId;
                }
            }

            //If the last table of non-manual byes is an odd-man, set table/player as a bye
            if (roundTable.Player2Id == 0)
            {
                roundTable.Bye           = true;
                roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                roundTable.Player1Winner = true;

                foreach (TournamentMainPlayer player in objTournMain.Players)
                {
                    if (player.Id == roundTable.Player2Id)
                    {
                        player.ByeCount++;
                        break;
                    }
                }
            }

            setRoundTableNames(ref roundTable);
            round.Tables.Add(roundTable);


            //If a manual bye (such as first-round byes at a tournament), add these players now
            if (lstActiveTournamentPlayers_Byes.Count > 0)
            {
                lstActiveTournamentPlayers_Byes.Shuffle();
                foreach (TournamentMainPlayer player in lstActiveTournamentPlayers_Byes)
                {
                    roundTable               = new TournamentMainRoundTable();
                    roundTable.Number        = round.Tables.Count + 1;
                    roundTable.Player1Id     = player.PlayerId;
                    roundTable.Bye           = true;
                    roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                    roundTable.Player1Winner = true;
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                }
            }

            //Add/Save the round
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                try
                {
                    conn.Update(objTournMain); //Update any other information that was saved such as Bye counts and such
                    conn.InsertWithChildren(round, true);
                }
                catch (Exception ex)
                {
                    DisplayAlert("Warning!", "Error adding round to tournament! " + ex.Message, "OK");
                }

                OnAppearing();
            }
        }
Beispiel #12
0
        private void StartRound(bool blnSwiss, int intTopCut)
        {
            //Create a new round
            TournamentMainRound round = new TournamentMainRound();

            round.TournamentId = tournamentId;
            round.Number       = objTournActivity.TournamentMain.Rounds.Count + 1;
            round.Swiss        = blnSwiss;

            List <TournamentMainPlayer> lstActiveTournamentPlayers      = new List <TournamentMainPlayer>();
            List <TournamentMainPlayer> lstActiveTournamentPlayers_Byes = new List <TournamentMainPlayer>();

            if (blnSwiss)
            {
                SetupSwissPlayers(ref lstActiveTournamentPlayers, ref lstActiveTournamentPlayers_Byes);
            }
            else
            {
                SetupSingleEliminationPlayers(ref lstActiveTournamentPlayers, intTopCut);
            }

            //Create each table, pair 'em up
            TournamentMainRoundTable roundTable = new TournamentMainRoundTable();

            foreach (TournamentMainPlayer player in lstActiveTournamentPlayers)
            {
                if (roundTable.Player1Id != 0 && roundTable.Player2Id != 0)
                {
                    //setRoundTableNames(ref roundTable);
                    roundTable.TableName = string.Format("{0} vs {1}", roundTable.Player1Name, roundTable.Player2Name);
                    round.Tables.Add(roundTable);
                    roundTable = new TournamentMainRoundTable();
                }

                if (roundTable.Player1Id == 0)
                {
                    roundTable.Number      = round.Tables.Count + 1;
                    roundTable.Player1Id   = player.PlayerId;
                    roundTable.Player1Name = player.PlayerName;
                }
                else if (roundTable.Player2Id == 0)
                {
                    roundTable.Player2Id   = player.PlayerId;
                    roundTable.Player2Name = player.PlayerName;
                }
            }

            //If the last table of non-manual byes is an odd-man, set table/player as a bye
            if (roundTable.Player2Id == 0)
            {
                roundTable.Bye           = true;
                roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                roundTable.Player1Winner = true;
            }

            roundTable.TableName = string.Format("{0} vs {1}", roundTable.Player1Name, roundTable.Player2Name);
            round.Tables.Add(roundTable);

            //If a manual bye (such as first-round byes at a tournament), add these players now
            if (lstActiveTournamentPlayers_Byes.Count > 0)
            {
                lstActiveTournamentPlayers_Byes.Shuffle();
                foreach (TournamentMainPlayer player in lstActiveTournamentPlayers_Byes)
                {
                    roundTable               = new TournamentMainRoundTable();
                    roundTable.Number        = round.Tables.Count + 1;
                    roundTable.Player1Id     = player.PlayerId;
                    roundTable.Player1Name   = player.PlayerName;
                    roundTable.Bye           = true;
                    roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                    roundTable.Player1Winner = true;
                    roundTable.TableName     = string.Format("{0} vs {1}", roundTable.Player1Name, "N/A");
                    round.Tables.Add(roundTable);
                }
            }

            objTournMain.Rounds.Add(round);


            //Create round and associated tables on database
            var request = new RestRequest("TournamentsRounds/{userid}/{id}", Method.POST);

            request.AddUrlSegment("userid", Utilities.CurrentUser.Id);
            request.AddUrlSegment("id", round.Id);
            request.AddJsonBody(JsonConvert.SerializeObject(round));

            // execute the request
            IRestResponse response = client.Execute(request);
            var           content  = response.Content;
        }
        // POST api/values (CREATE)
        public string Post(int userid, int id, [FromBody] string value)
        {
            if (!Utilities.IsValidated(Request.Headers))
            {
                return("Validation fail");
            }

            try
            {
                TournamentMainRound round = JsonConvert.DeserializeObject <TournamentMainRound>(JsonConvert.DeserializeObject(value).ToString());

                using (SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["XWTWebConnectionString"].ToString()))
                {
                    sqlConn.Open();

                    //Create new round
                    using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRounds_UPDATEINSERT", sqlConn))
                    {
                        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@TournamentId", round.TournamentId);
                        sqlCmd.Parameters.AddWithValue("@Number", round.Number);
                        sqlCmd.Parameters.AddWithValue("@Swiss", round.Swiss);
                        //sqlCmd.Parameters.AddWithValue("@RoundTimeEnd", round.RoundTimeEnd); Creating round, so no need to pass this at all

                        SqlParameter outputParameter = new SqlParameter("@Id", SqlDbType.Int);
                        outputParameter.Value     = id;
                        outputParameter.Direction = ParameterDirection.InputOutput;

                        sqlCmd.Parameters.Add(outputParameter);

                        //Grab the new ID, if applicable
                        using (SqlDataReader sqlRdr = sqlCmd.ExecuteReader())
                        {
                            id = Convert.ToInt32(outputParameter.Value);
                        }
                    }


                    //Create/update table data sent in
                    DataTable dt = new DataTable();
                    dt.Columns.Add("Id", typeof(int));
                    dt.Columns.Add("RoundId", typeof(int));
                    dt.Columns.Add("Number", typeof(int));
                    dt.Columns.Add("TableName", typeof(string));
                    dt.Columns.Add("ScoreTied", typeof(bool));
                    dt.Columns.Add("Bye", typeof(bool));
                    dt.Columns.Add("Player1Id", typeof(int));
                    dt.Columns.Add("Player1Name", typeof(string));
                    dt.Columns.Add("Player1Score", typeof(int));
                    dt.Columns.Add("Player1Winner", typeof(bool));
                    dt.Columns.Add("Player2Id", typeof(int));
                    dt.Columns.Add("Player2Name", typeof(string));
                    dt.Columns.Add("Player2Score", typeof(int));
                    dt.Columns.Add("Player2Winner", typeof(bool));

                    foreach (TournamentMainRoundTable table in round.Tables)
                    {
                        dt.Rows.Add(table.Id, table.RoundId, table.Number, table.TableName, table.ScoreTied, table.Bye
                                    , table.Player1Id, table.Player1Name, table.Player1Score, table.Player1Winner
                                    , table.Player2Id, table.Player2Name, table.Player2Score, table.Player2Winner);
                    }

                    using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRoundsTable_UPDATEINSERT_DT", sqlConn))
                    {
                        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@RoundId", id);
                        sqlCmd.Parameters.Add("@TableDataTable", SqlDbType.Structured).Value = dt;
                        sqlCmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return("POST: Success");
        }
Beispiel #14
0
        public static async System.Threading.Tasks.Task <string> ImportAllAsync()
        {
            client = Utilities.InitializeRestClient();

            if (App.IsUserLoggedIn)
            {
                try
                {
                    //Get the current players saved locally
                    List <Player>         lstCurrentPlayers     = new List <Player>();
                    List <TournamentMain> lstCurrentTournaments = new List <TournamentMain>();

                    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                    {
                        Utilities.InitializeTournamentMain(conn);

                        lstCurrentPlayers     = conn.Query <Player>("SELECT * FROM Player WHERE Active = ? AND DateDeleted IS NULL ORDER BY Name", true);
                        lstCurrentTournaments = conn.Query <TournamentMain>("SELECT * FROM TournamentMain WHERE DateDeleted IS NULL ORDER BY StartDate");
                    }

                    //Import general Players and general Tournament info
                    await ImportPlayersAsync(lstCurrentPlayers);
                    await ImportTournamentsAsync(lstCurrentTournaments);


                    //Import specific player, round, and table data for each tournament
                    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                    {
                        //Collect most up-to-date Player info since they've been imported, collecting API Ids
                        lstCurrentPlayers = new List <Player>();
                        lstCurrentPlayers = conn.Query <Player>("SELECT * FROM Player WHERE Active = ? AND DateDeleted IS NULL ORDER BY Name", true);

                        Dictionary <int, int> dctAPIPlayerId = new Dictionary <int, int>();
                        foreach (Player player in lstCurrentPlayers)
                        {
                            if (!dctAPIPlayerId.ContainsKey(player.API_Id))
                            {
                                dctAPIPlayerId.Add(player.API_Id, player.Id);
                            }
                        }


                        lstCurrentTournaments = new List <TournamentMain>();
                        lstCurrentTournaments = conn.Query <TournamentMain>("SELECT * FROM TournamentMain WHERE DateDeleted IS NULL ORDER BY StartDate");

                        //Go through each saved Tournament on device, pulling the detailed round/table data for each
                        TournamentMain objTournMain;
                        foreach (TournamentMain localTournament in lstCurrentTournaments)
                        {
                            objTournMain = new TournamentMain();
                            objTournMain = conn.GetWithChildren <TournamentMain>(localTournament.Id, true);

                            if (objTournMain.API_Id > 0)
                            {
                                var request = new RestRequest("Tournaments/{userid}/{id}", Method.GET);
                                request.AddUrlSegment("userid", App.CurrentUser.Id);
                                request.AddUrlSegment("id", objTournMain.API_Id);

                                // execute the request
                                var response = await client.ExecuteTaskAsync(request);

                                var content = response.Content;

                                List <TournamentMain> result = JsonConvert.DeserializeObject <List <TournamentMain> >(JsonConvert.DeserializeObject(content).ToString());
                                foreach (TournamentMain ApiTournament in result)
                                {
                                    //Add/update Tournament Player data
                                    foreach (TournamentMainPlayer ApiTournPlayer in ApiTournament.Players)
                                    {
                                        TournamentMainPlayer updatePlayer = new TournamentMainPlayer()
                                        {
                                            Active       = ApiTournPlayer.Active,
                                            API_Id       = ApiTournPlayer.Id,
                                            Bye          = ApiTournPlayer.Bye,
                                            ByeCount     = ApiTournPlayer.ByeCount,
                                            MOV          = ApiTournPlayer.MOV,
                                            PlayerId     = (dctAPIPlayerId.ContainsKey(ApiTournPlayer.PlayerId) ? dctAPIPlayerId[ApiTournPlayer.PlayerId] : 0),
                                            PlayerName   = ApiTournPlayer.PlayerName,
                                            Rank         = ApiTournPlayer.Rank,
                                            RoundsPlayed = ApiTournPlayer.RoundsPlayed,
                                            TournamentId = objTournMain.Id
                                        };

                                        foreach (TournamentMainPlayer localPlayer in objTournMain.Players)
                                        {
                                            if (localPlayer.PlayerId == updatePlayer.PlayerId)
                                            {
                                                updatePlayer.Id = localPlayer.Id;
                                                break;
                                            }
                                        }

                                        if (updatePlayer.Id == 0)
                                        {
                                            conn.Insert(updatePlayer);
                                        }
                                        else
                                        {
                                            conn.Update(updatePlayer);
                                        }
                                    }

                                    //Add/Update/Delete Rounds
                                    foreach (TournamentMainRound ApiRound in ApiTournament.Rounds)
                                    {
                                        TournamentMainRound updateRound = new TournamentMainRound()
                                        {
                                            API_Id       = ApiRound.Id,
                                            Number       = ApiRound.Number,
                                            RoundTimeEnd = ApiRound.RoundTimeEnd,
                                            Swiss        = ApiRound.Swiss,
                                            TournamentId = objTournMain.Id
                                        };

                                        //Grab the device's SQL round Id
                                        foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                        {
                                            if (localRound.API_Id == updateRound.API_Id)
                                            {
                                                updateRound.Id = localRound.Id;
                                                break;
                                            }
                                        }
                                        if (updateRound.Id == 0)
                                        {
                                            conn.Insert(updateRound);
                                            TournamentMainRound tmp = conn.Query <TournamentMainRound>("SELECT * FROM TournamentMainRound WHERE TournamentId = ? ORDER BY Id DESC", updateRound.TournamentId)[0];
                                            updateRound.Id = tmp.Id; //We need this latest RoundId so that the tables will be associated with the correct round
                                        }
                                        else
                                        {
                                            conn.Update(updateRound);
                                        }


                                        //Add/update table data
                                        foreach (TournamentMainRoundTable ApiTable in ApiRound.Tables)
                                        {
                                            TournamentMainRoundTable updateTable = new TournamentMainRoundTable()
                                            {
                                                API_Id        = ApiTable.Id,
                                                Bye           = ApiTable.Bye,
                                                Number        = ApiTable.Number,
                                                Player1Id     = (dctAPIPlayerId.ContainsKey(ApiTable.Player1Id) ? dctAPIPlayerId[ApiTable.Player1Id] : 0),
                                                Player1Name   = ApiTable.Player1Name,
                                                Player1Score  = ApiTable.Player1Score,
                                                Player1Winner = ApiTable.Player1Winner,
                                                Player2Id     = (dctAPIPlayerId.ContainsKey(ApiTable.Player2Id) ? dctAPIPlayerId[ApiTable.Player2Id] : 0),
                                                Player2Name   = ApiTable.Player2Name,
                                                Player2Score  = ApiTable.Player2Score,
                                                Player2Winner = ApiTable.Player2Winner,
                                                ScoreTied     = ApiTable.ScoreTied,
                                                TableName     = ApiTable.TableName,
                                                RoundId       = updateRound.Id
                                            };


                                            //Grab the device's SQL table Id
                                            foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                            {
                                                if (localRound.Id == updateTable.RoundId)
                                                {
                                                    foreach (TournamentMainRoundTable localTable in localRound.Tables)
                                                    {
                                                        if (localTable.API_Id == updateTable.API_Id)
                                                        {
                                                            updateTable.Id = localTable.Id;
                                                            break;
                                                        }
                                                    }
                                                    break;
                                                }
                                            }

                                            if (updateTable.Id == 0)
                                            {
                                                conn.Insert(updateTable);
                                            }
                                            else
                                            {
                                                conn.Update(updateTable);
                                            }
                                        }
                                    }

                                    //Delete any local rounds that are saved, but were removed online
                                    foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                    {
                                        bool blnDeleteRound = true;
                                        foreach (TournamentMainRound ApiRound in ApiTournament.Rounds)
                                        {
                                            if (ApiRound.Id == localRound.API_Id)
                                            {
                                                blnDeleteRound = false;
                                                break;
                                            }
                                        }
                                        if (blnDeleteRound)
                                        {
                                            conn.Delete(localRound);
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Error:" + ex.Message);
                    return("Error: " + ex.Message);
                }

                return("Import success");
            }

            return("");
        }
        private async void LoadOnlineActiveTournamentsAsync()
        {
            loadingOverlay_LogScore.IsVisible  = true;
            loadingOverlay_Standings.IsVisible = true;

            //Pull tournaments user is registered for
            IRestRequest request = new RestRequest("TournamentsSearch/{userid}", Method.GET);

            request.AddUrlSegment("userid", App.CurrentUser.Id.ToString());

            // execute the request
            var response = await client.ExecuteTaskAsync(request);

            string content = response.Content;

            List <TournamentMain> returnedTournaments = JsonConvert.DeserializeObject <List <TournamentMain> >(JsonConvert.DeserializeObject(content).ToString());

            associatedTournaments = new List <TournamentMain>();
            if (returnedTournaments.Count > 0)
            {
                tournamentStandingsTableListView.ItemsSource = returnedTournaments;
                associatedTournaments.AddRange(returnedTournaments);
            }

            associatedLogScoreTables = new List <TournamentMainRoundTable>();

            //Go through the returned associated tournaments, grab the latest round's info and ensure the user is at one of the tables
            foreach (TournamentMain tournament in returnedTournaments)
            {
                if (tournament.Rounds.Count > 0)
                {
                    TournamentMainRound lastestRound = tournament.Rounds[tournament.Rounds.Count - 1];

                    int intTournPlayerId = 0;
                    foreach (TournamentMainPlayer player in tournament.Players)
                    {
                        if (player.API_UserAccountId == App.CurrentUser.Id)
                        {
                            intTournPlayerId = player.PlayerId;
                            break;
                        }
                    }

                    if (intTournPlayerId > 0)
                    {
                        foreach (TournamentMainRoundTable table in lastestRound.Tables)
                        {
                            if (table.Player1Id == intTournPlayerId || table.Player2Id == intTournPlayerId)
                            {
                                table.TableName = string.Format("{0}: {1}", tournament.Name, table.TableName);
                                if (table.Bye)
                                {
                                    table.TableName += " (BYE)";
                                }
                                table.Bye = !table.Bye; //Flip this since the Binding can't do that
                                associatedLogScoreTables.Add(table);
                                break;
                            }
                        }
                    }
                }
            }

            logScoreTableListView.ItemsSource = associatedLogScoreTables;

            loadingOverlay_LogScore.IsVisible  = false;
            loadingOverlay_Standings.IsVisible = false;
        }