private void ResetStatus(OdbcConnection connection) { BiddingStarted = false; BiddingComplete = false; PlayComplete = false; LastBid = new Bid("", 0, "", "", false, "", 0, -1); LastPlay = new Play("", 0, "", -999); ClaimExpose = false; ClaimDirection = ""; string SQLString = $"UPDATE Tables SET CurrentRound={RoundNumber}, CurrentBoard={BoardNumber}, BiddingStarted=False, BiddingComplete=False, PlayComplete=False WHERE Section={SectionID} AND [Table]={TableNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } }
public static string GetNameFromPlayerNumbersTableIndividual(OdbcConnection conn, int sectionID, int round, int playerNo) { string number = "###"; string name = ""; string SQLString = $"SELECT Number, Name, Round, TimeLog FROM PlayerNumbers WHERE Section={sectionID} AND TabPlayPairNo={playerNo}"; OdbcCommand cmd = new OdbcCommand(SQLString, conn); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); DateTime latestTimeLog = new DateTime(2010, 1, 1); while (reader.Read()) { try { int readerRound = reader.GetInt32(2); DateTime timeLog; if (reader.IsDBNull(3)) { timeLog = new DateTime(2010, 1, 1); } else { timeLog = reader.GetDateTime(3); } if (readerRound <= round && timeLog >= latestTimeLog) { number = reader.GetString(0); name = reader.GetString(1); latestTimeLog = timeLog; } } catch // Record found, but format cannot be parsed { if (number == "###") { number = ""; } } } }); } finally { cmd.Dispose(); reader.Close(); } if (number == "###") // Nothing found { number = ""; } return(FormatName(name, number)); }
// Constructor to set declarer for intermediate result public Result(int deviceNumber, int boardNumber, int contractLevel, string contractSuit, string contractX) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; BoardNumber = boardNumber; ContractLevel = contractLevel; ContractSuit = contractSuit; ContractX = contractX; List <DatabaseBid> databaseBidList = new List <DatabaseBid>(); using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = $"SELECT Counter, Bid, Direction FROM BiddingData WHERE Section={device.SectionID} AND Table={device.TableNumber} AND Round={device.RoundNumber} AND Board={boardNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { int tempCounter = reader.GetInt32(0); string tempBid = reader.GetString(1); string tempDirection = reader.GetString(2); DatabaseBid databaseBid = new DatabaseBid { Counter = tempCounter, Bid = tempBid, Direction = tempDirection }; databaseBidList.Add(databaseBid); } }); } finally { reader.Close(); cmd.Dispose(); } } databaseBidList.Sort((x, y) => x.Counter.CompareTo(y.Counter)); DatabaseBid contractBid = databaseBidList.FindLast(x => x.Bid != "PASS" && x.Bid != "x" && x.Bid != "xx"); if (contractBid.Direction == "N" || contractBid.Direction == "S") { DeclarerNSEW = databaseBidList.Find(x => (x.Direction == "N" || x.Direction == "S") && x.Bid.Length > 1 && x.Bid.Substring(1, 1) == contractBid.Bid.Substring(1, 1)).Direction; } else { DeclarerNSEW = databaseBidList.Find(x => (x.Direction == "E" || x.Direction == "W") && x.Bid.Length > 1 && x.Bid.Substring(1, 1) == contractBid.Bid.Substring(1, 1)).Direction; } }
public static void Refresh() { if (DateTime.Now.Subtract(UpdateTime).TotalMinutes < 1.0) { return; // Settings updated recently, so don't bother } UpdateTime = DateTime.Now; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = "SELECT ShowResults, ShowPercentage, BM2Ranking, BM2ViewHandRecord, BM2NumberEntryEachRound, BM2NameSource, PollInterval FROM Settings"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { ShowResults = reader.GetBoolean(0); ShowPercentage = reader.GetBoolean(1); ShowRanking = reader.GetInt32(2); ShowHandRecord = reader.GetBoolean(3); NumberEntryEachRound = reader.GetBoolean(4); NameSource = reader.GetInt32(5); PollInterval = reader.GetInt32(6); } }); } catch { ShowResults = true; ShowPercentage = true; ShowRanking = 1; ShowHandRecord = true; NumberEntryEachRound = true; NameSource = 0; PollInterval = 1000; } finally { reader.Close(); cmd.Dispose(); } } }
public static string GetNameFromExternalDatabase(int playerNumber) { string name = ""; OdbcConnectionStringBuilder externalDB = new OdbcConnectionStringBuilder { Driver = "Microsoft Access Driver (*.mdb)" }; externalDB.Add("Dbq", @"C:\Bridgemate\BMPlayerDB.mdb"); externalDB.Add("Uid", "Admin"); using (OdbcConnection connection = new OdbcConnection(externalDB.ToString())) { object queryResult = null; string SQLString = $"SELECT Name FROM PlayerNameDatabase WHERE ID={playerNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { connection.Open(); ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd.ExecuteScalar(); if (queryResult == null) { name = "Unknown #" + playerNumber; } else { name = queryResult.ToString(); } }); } catch (OdbcException) // If we can't read the external database for whatever reason... { name = "#" + playerNumber; } finally { cmd.Dispose(); } } return(name); }
// Find out how many rounds there are in the event // Need to re-query database in case rounds are added/removed by scoring program public static int NumberOfRoundsInEvent(int sectionID) { object queryResult = null; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = SQLString = $"SELECT MAX(Round) FROM RoundData WHERE Section={sectionID}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd.ExecuteScalar(); }); } finally { cmd.Dispose(); } } return(Convert.ToInt32(queryResult)); }
public void UpdateDB(int deviceNumber, int boardNumber) { Device device = AppData.DeviceList[deviceNumber]; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); // Delete any spurious previously made plays string SQLString = $"DELETE FROM PlayData WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={boardNumber} AND Counter={PlayCounter}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } SQLString = $"INSERT INTO PlayData (Section, [Table], Round, Board, Counter, Direction, Card, DateLog, TimeLog) VALUES ({device.SectionID}, {device.TableNumber}, {device.RoundNumber}, {boardNumber}, {PlayCounter}, '{PlayDirection.Substring(0, 1)}', '{CardString}', #{DateTime.Now:yyyy-MM-dd}#, #{DateTime.Now:yyyy-MM-dd hh:mm:ss}#)"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } } }
private static List <Ranking> CalculateRankingFromReceivedData(OdbcConnection conn, int sectionID) { List <Ranking> rankingList = new List <Ranking>(); List <Result> resList = new List <Result>(); int Winners = 0; // Check Winners object queryResult = null; string SQLString = $"SELECT Winners FROM Section WHERE ID={sectionID}"; OdbcCommand cmd1 = new OdbcCommand(SQLString, conn); try { ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd1.ExecuteScalar(); }); Winners = Convert.ToInt32(queryResult); } catch (OdbcException) { // If Winners column doesn't exist, or any other error, can't calculate ranking return(null); } finally { cmd1.Dispose(); } if (Winners == 0) { // Winners not set, so no chance of calculating ranking return(null); } // No Results table and Winners = 1 or 2, so use ReceivedData to calculate ranking SQLString = $"SELECT Board, PairNS, PairEW, [NS/EW], Contract, Result FROM ReceivedData WHERE Section={sectionID}"; OdbcCommand cmd2 = new OdbcCommand(SQLString, conn); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd2.ExecuteReader(); while (reader.Read()) { Result result = new Result() { BoardNumber = reader.GetInt32(0), PairNS = reader.GetInt32(1), PairEW = reader.GetInt32(2), DeclarerNSEW = reader.GetString(3), Contract = reader.GetString(4), TricksTakenSymbol = reader.GetString(5) }; if (result.Contract.Length > 2) // Testing for unplayed boards and corrupt ReceivedData table { result.CalculateScore(); resList.Add(result); } } }); } catch (OdbcException) { return(null); } finally { reader.Close(); cmd2.Dispose(); } // Calculate MPs List <Result> currentBoardResultList = new List <Result>(); int currentBoard; int currentScore; foreach (Result result in resList) { currentScore = result.Score; currentBoard = result.BoardNumber; currentBoardResultList = resList.FindAll(x => x.BoardNumber == currentBoard); result.MatchpointsNS = 2 * currentBoardResultList.FindAll(x => x.Score < currentScore).Count + currentBoardResultList.FindAll(x => x.Score == currentScore).Count - 1; result.MatchpointsMax = 2 * currentBoardResultList.Count - 2; result.MatchpointsEW = result.MatchpointsMax - result.MatchpointsNS; } if (Winners == 1) { // Add up MPs for each pair, creating Ranking List entries as we go foreach (Result result in resList) { Ranking rankingListFind = rankingList.Find(x => x.PairNumber == result.PairNS); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairNS, Orientation = "0", MP = result.MatchpointsNS, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsNS; rankingListFind.MPMax += result.MatchpointsMax; } rankingListFind = rankingList.Find(x => x.PairNumber == result.PairEW); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairEW, Orientation = "0", MP = result.MatchpointsEW, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsEW; rankingListFind.MPMax += result.MatchpointsMax; } } // Calculate percentages foreach (Ranking ranking in rankingList) { if (ranking.MPMax == 0) { ranking.ScoreDecimal = 50.0; } else { ranking.ScoreDecimal = 100.0 * ranking.MP / ranking.MPMax; } ranking.Score = ranking.ScoreDecimal.ToString("0.##"); } // Calculate ranking foreach (Ranking ranking in rankingList) { double currentScoreDecimal = ranking.ScoreDecimal; int rank = rankingList.FindAll(x => x.ScoreDecimal > currentScoreDecimal).Count + 1; ranking.Rank = rank.ToString(); if (rankingList.FindAll(x => x.ScoreDecimal == currentScoreDecimal).Count > 1) { ranking.Rank += "="; } } } else // Winners = 2 { // Add up MPs for each pair, creating Ranking List entries as we go foreach (Result result in resList) { Ranking rankingListFind = rankingList.Find(x => x.PairNumber == result.PairNS && x.Orientation == "N"); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairNS, Orientation = "N", MP = result.MatchpointsNS, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsNS; rankingListFind.MPMax += result.MatchpointsMax; } rankingListFind = rankingList.Find(x => x.PairNumber == result.PairEW && x.Orientation == "E"); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairEW, Orientation = "E", MP = result.MatchpointsEW, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsEW; rankingListFind.MPMax += result.MatchpointsMax; } } // Calculate percentages foreach (Ranking ranking in rankingList) { if (ranking.MPMax == 0) { ranking.ScoreDecimal = 50.0; } else { ranking.ScoreDecimal = 100.0 * ranking.MP / ranking.MPMax; } ranking.Score = ranking.ScoreDecimal.ToString("0.##"); } // Sort and calculate ranking within Orientation subsections foreach (Ranking ranking in rankingList) { double currentScoreDecimal = ranking.ScoreDecimal; string currentOrientation = ranking.Orientation; int rank = rankingList.FindAll(x => x.Orientation == currentOrientation && x.ScoreDecimal > currentScoreDecimal).Count + 1; ranking.Rank = rank.ToString(); if (rankingList.FindAll(x => x.Orientation == currentOrientation && x.ScoreDecimal == currentScoreDecimal).Count > 1) { ranking.Rank += "="; } } } return(rankingList); }
public static string GetNameFromPlayerNumbersTable(OdbcConnection conn, int sectionID, int round, int pairNo, string direction) { string number = "###"; string name = ""; string dir = direction.Substring(0, 1); // First look for entries in the same direction // If the player has changed (eg in teams), there will be more than one PlayerNumbers record for this pair number and direction // We need the most recently added name applicable to this round string SQLString = $"SELECT Number, Name, Round, TimeLog FROM PlayerNumbers WHERE Section={sectionID} AND TabPlayPairNo={pairNo} AND Direction='{dir}'"; OdbcCommand cmd1 = new OdbcCommand(SQLString, conn); OdbcDataReader reader1 = null; try { ODBCRetryHelper.ODBCRetry(() => { reader1 = cmd1.ExecuteReader(); DateTime latestTimeLog = new DateTime(2010, 1, 1); while (reader1.Read()) { try { int readerRound = reader1.GetInt32(2); DateTime timeLog; if (reader1.IsDBNull(3)) { timeLog = new DateTime(2010, 1, 1); } else { timeLog = reader1.GetDateTime(3); } if (readerRound <= round && timeLog >= latestTimeLog) { number = reader1.GetString(0); name = reader1.GetString(1); latestTimeLog = timeLog; } } catch // Record found, but format cannot be parsed { if (number == "###") { number = ""; } } } }); } finally { reader1.Close(); cmd1.Dispose(); } if (number == "###") // Nothing found so try Round 0 entries in the other direction (for Howell type pairs movement) { string otherDir; switch (dir) { case "N": otherDir = "E"; break; case "S": otherDir = "W"; break; case "E": otherDir = "N"; break; case "W": otherDir = "S"; break; default: otherDir = ""; break; } SQLString = $"SELECT Number, Name, TimeLog FROM PlayerNumbers WHERE Section={sectionID} AND TabPlayPairNo={pairNo} AND Direction='{otherDir}' AND Round=0"; OdbcCommand cmd2 = new OdbcCommand(SQLString, conn); OdbcDataReader reader2 = null; try { ODBCRetryHelper.ODBCRetry(() => { reader2 = cmd2.ExecuteReader(); DateTime latestTimeLog = new DateTime(2010, 1, 1); while (reader2.Read()) { try { DateTime timeLog; if (reader2.IsDBNull(2)) { timeLog = new DateTime(2010, 1, 1); } else { timeLog = reader2.GetDateTime(2); } if (timeLog >= latestTimeLog) { number = reader2.GetString(0); name = reader2.GetString(1); latestTimeLog = timeLog; } } catch // Record found, but format cannot be parsed { if (number == "###") { number = ""; } } } }); } finally { reader2.Close(); cmd2.Dispose(); } } if (number == "###") // Nothing found in either direction!! { number = ""; } return(FormatName(name, number)); }
public static void CheckTabPlayPairNos(OdbcConnection conn) { object queryResult = null; // Check to see if TabPlayPairNo exists (it may get overwritten if the scoring program recreates the PlayerNumbers table) string SQLString = $"SELECT 1 FROM PlayerNumbers WHERE TabPlayPairNo IS NULL"; OdbcCommand cmd1 = new OdbcCommand(SQLString, conn); try { ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd1.ExecuteScalar(); }); } finally { cmd1.Dispose(); } if (queryResult != null) { // TabPlayPairNo doesn't exist, so recreate it. This duplicates the code in TabPlayStarter SQLString = "SELECT Section, [Table], Direction FROM PlayerNumbers"; OdbcCommand cmd2 = new OdbcCommand(SQLString, conn); OdbcDataReader reader2 = null; try { ODBCRetryHelper.ODBCRetry(() => { reader2 = cmd2.ExecuteReader(); while (reader2.Read()) { int tempSectionID = reader2.GetInt32(0); int tempTable = reader2.GetInt32(1); string tempDirection = reader2.GetString(2); if (AppData.IsIndividual) { switch (tempDirection) { case "N": SQLString = $"SELECT NSPair FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; case "S": SQLString = $"SELECT South FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; case "E": SQLString = $"SELECT EWPair FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; case "W": SQLString = $"SELECT West FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; } } else { switch (tempDirection) { case "N": case "S": SQLString = $"SELECT NSPair FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; case "E": case "W": SQLString = $"SELECT EWPair FROM RoundData WHERE Section={tempSectionID} AND [Table]={tempTable} AND ROUND=1"; break; } } OdbcCommand cmd3 = new OdbcCommand(SQLString, conn); try { ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd3.ExecuteScalar(); }); } finally { cmd3.Dispose(); } string TSpairNo = queryResult.ToString(); SQLString = $"UPDATE PlayerNumbers SET TabPlayPairNo={TSpairNo} WHERE Section={tempSectionID} AND [Table]={tempTable} AND Direction='{tempDirection}'"; OdbcCommand cmd4 = new OdbcCommand(SQLString, conn); try { ODBCRetryHelper.ODBCRetry(() => { cmd4.ExecuteNonQuery(); }); } finally { cmd4.Dispose(); } } }); } finally { reader2.Close(); cmd2.Dispose(); } } }
public static void Refresh() { if (File.Exists(PathToTabPlayDB)) { // Only do an update if TabPlayStarter has updated TabPlayDB.txt DateTime lastWriteTime = File.GetLastWriteTime(PathToTabPlayDB); if (lastWriteTime > TabPlayDBTime) { DBConnectionString = File.ReadAllText(PathToTabPlayDB); TabPlayDBTime = lastWriteTime; if (DBConnectionString != "") { using (OdbcConnection connection = new OdbcConnection(DBConnectionString)) { connection.Open(); // Check if new event is an individual (in which case there will be a field 'South' in the RoundData table) string SQLString = $"SELECT TOP 1 South FROM RoundData"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteScalar(); IsIndividual = true; }); } catch (OdbcException e) { if (e.Errors.Count > 1 || e.Errors[0].SQLState != "07002") // Error other than field 'South' doesn't exist { throw (e); } else { IsIndividual = false; } } finally { cmd.Dispose(); } // Create list of sections SQLString = "SELECT ID, Letter, Tables, MissingPair FROM Section"; SectionList.Clear(); cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { Section s = new Section { SectionID = reader.GetInt32(0), SectionLetter = reader.GetString(1), NumTables = reader.GetInt32(2), MissingPair = reader.GetInt32(3) }; SectionList.Add(s); } }); } finally { reader.Close(); cmd.Dispose(); } // Retrieve global PlayerNames table SQLString = $"SELECT Name, ID FROM PlayerNames"; PlayerNamesTable.Clear(); cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { PlayerRecord playerRecord = new PlayerRecord { Name = reader.GetString(0), Number = reader.GetInt32(1) }; PlayerNamesTable.Add(playerRecord); } ; }); } catch (OdbcException e) { if (e.Errors.Count > 1 || e.Errors[0].SQLState != "42S02") // Error other than PlayerNames table does not exist { throw (e); } } finally { reader.Close(); cmd.Dispose(); } } } } } }
public Table(int sectionID, int tableNumber) { SectionID = sectionID; TableNumber = tableNumber; LastBid = new Bid("", 0, "", "", false, "", 0, -1); LastPlay = new Play("", 0, "", -999); using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { object queryResult = null; connection.Open(); // Get the status of this table string SQLString = $"SELECT CurrentRound, CurrentBoard, BiddingStarted, BiddingComplete, PlayComplete FROM Tables WHERE Section={sectionID} AND [Table]={tableNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { queryResult = reader.GetValue(0); if (queryResult != DBNull.Value && queryResult != null) { RoundNumber = Convert.ToInt32(queryResult); } queryResult = reader.GetValue(1); if (queryResult != DBNull.Value && queryResult != null) { BoardNumber = Convert.ToInt32(queryResult); } BiddingStarted = reader.GetBoolean(2); BiddingComplete = reader.GetBoolean(3); PlayComplete = reader.GetBoolean(4); } }); } finally { reader.Close(); cmd.Dispose(); } // Ensure this table is recorded as logged on SQLString = $"UPDATE Tables SET LogOnOff=1 WHERE Section={sectionID} AND [Table]={tableNumber}"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } // Get the pair numbers and boards for this round GetRoundData(connection); } // Check for invalid board number and set accordingly if (BoardNumber < LowBoard || BoardNumber > HighBoard) { BoardNumber = LowBoard; } }
public void UpdateDB(string dataTable) { int declarerNumber = 0; string remarks = ""; Device device = AppData.DeviceList[DeviceNumber]; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = ""; OdbcCommand cmd = null; // Get pair numbers if (AppData.IsIndividual) { SQLString = $"SELECT NSPair, EWPair, South, West FROM RoundData WHERE Section={device.SectionID} AND Table={device.TableNumber} AND Round={device.RoundNumber}"; cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { PairNS = reader.GetInt32(0); PairEW = reader.GetInt32(1); South = reader.GetInt32(2); West = reader.GetInt32(3); } }); } finally { reader.Close(); cmd.Dispose(); } } else // Not individual { SQLString = $"SELECT NSPair, EWPair FROM RoundData WHERE Section={device.SectionID} AND Table={device.TableNumber} AND Round={device.RoundNumber}"; cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { PairNS = reader.GetInt32(0); PairEW = reader.GetInt32(1); } }); } finally { reader.Close(); cmd.Dispose(); } } // Set remarks and declarer if (ContractLevel == -1) { remarks = "Not played"; tricksTakenSymbol = ""; } if (ContractLevel > 0) { if (DeclarerNSEW == "N" || DeclarerNSEW == "S") // Only use N or E player numbers for both pairs and individuals { declarerNumber = PairNS; } else { declarerNumber = PairEW; } } // Delete any previous result SQLString = $"DELETE FROM {dataTable} WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } // Add new result if (AppData.IsIndividual) { SQLString = $"INSERT INTO {dataTable} (Section, [Table], Round, Board, PairNS, PairEW, South, West, Declarer, [NS/EW], Contract, Result, LeadCard, Remarks, DateLog, TimeLog, Processed, Processed1, Processed2, Processed3, Processed4, Erased) VALUES ({device.SectionID}, {device.TableNumber}, {device.RoundNumber}, {BoardNumber}, {PairNS}, {PairEW}, {South}, {West}, {declarerNumber}, '{DeclarerNSEW}', '{Contract}', '{TricksTakenSymbol}', '{LeadCard}', '{remarks}', #{DateTime.Now:yyyy-MM-dd}#, #{DateTime.Now:yyyy-MM-dd hh:mm:ss}#, False, False, False, False, False, False)"; } else { SQLString = $"INSERT INTO {dataTable} (Section, [Table], Round, Board, PairNS, PairEW, Declarer, [NS/EW], Contract, Result, LeadCard, Remarks, DateLog, TimeLog, Processed, Processed1, Processed2, Processed3, Processed4, Erased) VALUES ({device.SectionID}, {device.TableNumber}, {device.RoundNumber}, {BoardNumber}, {PairNS}, {PairEW}, {declarerNumber}, '{DeclarerNSEW}', '{Contract}', '{TricksTakenSymbol}', '{LeadCard}', '{remarks}', #{DateTime.Now:yyyy-MM-dd}#, #{DateTime.Now:yyyy-MM-dd hh:mm:ss}#, False, False, False, False, False, False)"; } cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } // Update table status if (dataTable == "IntermediateData") { SQLString = $"UPDATE Tables SET BiddingComplete=True WHERE Section={device.SectionID} AND [Table]={device.TableNumber}"; } else { SQLString = $"UPDATE Tables SET PlayComplete=True WHERE Section={device.SectionID} AND [Table]={device.TableNumber}"; } cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } } }
private void GetRoundData(OdbcConnection connection) { Utilities.CheckTabPlayPairNos(connection); if (AppData.IsIndividual) { string SQLString = $"SELECT NSPair, EWPair, South, West, LowBoard, HighBoard FROM RoundData WHERE Section={SectionID} AND Table={TableNumber} AND Round={RoundNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { PairNumber[0] = reader.GetInt32(0); PairNumber[1] = reader.GetInt32(1); PairNumber[2] = reader.GetInt32(2); PairNumber[3] = reader.GetInt32(3); LowBoard = reader.GetInt32(4); HighBoard = reader.GetInt32(5); } }); } finally { reader.Close(); cmd.Dispose(); } for (int i = 0; i < 4; i++) { PlayerName[i] = Utilities.GetNameFromPlayerNumbersTableIndividual(connection, SectionID, RoundNumber, PairNumber[i]); } } else // Not individual { string SQLString = $"SELECT NSPair, EWPair, LowBoard, HighBoard FROM RoundData WHERE Section={SectionID} AND Table={TableNumber} AND Round={RoundNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { PairNumber[0] = PairNumber[2] = reader.GetInt32(0); PairNumber[1] = PairNumber[3] = reader.GetInt32(1); LowBoard = reader.GetInt32(2); HighBoard = reader.GetInt32(3); } }); } finally { reader.Close(); cmd.Dispose(); } PlayerName[0] = Utilities.GetNameFromPlayerNumbersTable(connection, SectionID, RoundNumber, PairNumber[0], "North"); PlayerName[1] = Utilities.GetNameFromPlayerNumbersTable(connection, SectionID, RoundNumber, PairNumber[1], "East"); PlayerName[2] = Utilities.GetNameFromPlayerNumbersTable(connection, SectionID, RoundNumber, PairNumber[2], "South"); PlayerName[3] = Utilities.GetNameFromPlayerNumbersTable(connection, SectionID, RoundNumber, PairNumber[3], "West"); } }
// Database read constructor public Result(int deviceNumber, int boardNumber, string dataTable) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; BoardNumber = boardNumber; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = ""; if (AppData.IsIndividual) { SQLString = $"SELECT [NS/EW], Contract, Result, LeadCard, Remarks, PairNS, PairEW, South, West FROM {dataTable} WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; } else { SQLString = $"SELECT [NS/EW], Contract, Result, LeadCard, Remarks, PairNS, PairEW FROM {dataTable} WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; } OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { if (reader.GetString(4) == "Not played") { ContractLevel = -1; ContractSuit = ""; ContractX = ""; DeclarerNSEW = ""; TricksTakenNumber = -1; LeadCard = ""; } else { string temp = reader.GetString(1); Contract = temp; // Sets ContractLevel, etc if (ContractLevel == 0) // Passed out { DeclarerNSEW = ""; TricksTakenNumber = -1; LeadCard = ""; } else { DeclarerNSEW = reader.GetString(0); TricksTakenSymbol = reader.GetString(2); LeadCard = reader.GetString(3); } } PairNS = reader.GetInt32(5); PairEW = reader.GetInt32(6); if (AppData.IsIndividual) { South = reader.GetInt32(7); West = reader.GetInt32(8); } } else // No result in database { ContractLevel = -999; ContractSuit = ""; ContractX = ""; DeclarerNSEW = ""; TricksTakenNumber = -1; LeadCard = ""; PairNS = 0; PairEW = 0; if (AppData.IsIndividual) { South = 0; West = 0; } } }); } finally { reader.Close(); cmd.Dispose(); } } }
public void UpdateDB(int deviceNumber, int boardNumber) { Device device = AppData.DeviceList[deviceNumber]; string dbBid; if (PassCount > 0) { dbBid = "PASS"; } else if (LastBidX != "") { dbBid = LastBidX; } else { dbBid = LastBidLevel.ToString() + LastBidSuit; } using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); // Delete any spurious previously made bids string SQLString = $"DELETE FROM BiddingData WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={boardNumber} AND Counter={BidCounter}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } SQLString = $"INSERT INTO BiddingData (Section, [Table], Round, Board, Counter, Direction, Bid, DateLog, TimeLog) VALUES ({device.SectionID}, {device.TableNumber}, {device.RoundNumber}, {boardNumber}, {BidCounter}, '{LastCallDirection.Substring(0, 1)}', '{dbBid}', #{DateTime.Now:yyyy-MM-dd}#, #{DateTime.Now:yyyy-MM-dd hh:mm:ss}#)"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } if (BidCounter == 0) { // Update table status in database SQLString = $"UPDATE Tables SET BiddingStarted=True WHERE Section={device.SectionID} AND [Table]={device.TableNumber}"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd.ExecuteNonQuery(); }); } finally { cmd.Dispose(); } } } }
public Bidding(int deviceNumber, Table table) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; BoardNumber = table.BoardNumber; Direction = device.Direction; int directionNumber = Utilities.DirectionToNumber(Direction); PairNumber = table.PairNumber[directionNumber]; PlayerName = table.PlayerName[directionNumber]; NSVulnerable = Utilities.NSVulnerability[(BoardNumber - 1) % 16]; EWVulnerable = Utilities.EWVulnerability[(BoardNumber - 1) % 16]; BidTable = new string[10, 4]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 4; j++) { BidTable[i, j] = ""; } } LastCallDirection = ""; LastBidLevel = 0; LastBidSuit = ""; LastBidX = ""; LastBidDirection = ""; PassCount = 0; BidCounter = -1; ToBidDirection = ""; PollInterval = Settings.PollInterval; if (AppData.IsIndividual) { PairOrPlayer = "Player"; } else { PairOrPlayer = "Pair"; } List <DatabaseBid> databaseBidList = new List <DatabaseBid>(); using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); Utilities.CheckTabPlayPairNos(connection); string SQLString = $"SELECT Counter, Bid, Direction FROM BiddingData WHERE Section={device.SectionID} AND Table={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { int tempCounter = reader.GetInt32(0); string tempBid = reader.GetString(1); string tempDirection = reader.GetString(2); DatabaseBid databaseBid = new DatabaseBid { Counter = tempCounter, Bid = tempBid, Direction = tempDirection }; databaseBidList.Add(databaseBid); } }); } finally { reader.Close(); cmd.Dispose(); } } databaseBidList.Sort((x, y) => x.Counter.CompareTo(y.Counter)); foreach (DatabaseBid databaseBid in databaseBidList) { BidCounter = databaseBid.Counter; if (databaseBid.Direction == "N") { LastCallDirection = "North"; ToBidDirection = "East"; } else if (databaseBid.Direction == "E") { LastCallDirection = "East"; ToBidDirection = "South"; } else if (databaseBid.Direction == "S") { LastCallDirection = "South"; ToBidDirection = "West"; } else if (databaseBid.Direction == "W") { LastCallDirection = "West"; ToBidDirection = "North"; } if (databaseBid.Bid == "PASS") { PassCount++; BidTable[BidCounter / 4, BidCounter % 4] = "<span style='color:darkgreen'>Pass</span>"; } else if (databaseBid.Bid == "x") { PassCount = 0; BidTable[BidCounter / 4, BidCounter % 4] = "<span style='color:darkred'>X</span>"; LastBidX = "x"; LastBidDirection = LastCallDirection; } else if (databaseBid.Bid == "xx") { PassCount = 0; BidTable[BidCounter / 4, BidCounter % 4] = "<span style='color:darkblue'>XX</span>"; LastBidX = "xx"; LastBidDirection = LastCallDirection; } else { LastBidLevel = Convert.ToInt32(databaseBid.Bid.Substring(0, 1)); LastBidX = ""; LastBidDirection = LastCallDirection; LastBidSuit = databaseBid.Bid.Substring(1); if (LastBidSuit == "S") { BidTable[BidCounter / 4, BidCounter % 4] = LastBidLevel.ToString() + "<span style='color:black'>♠</span>"; } else if (LastBidSuit == "H") { BidTable[BidCounter / 4, BidCounter % 4] = LastBidLevel.ToString() + "<span style='color:red'>♥</span>"; } else if (LastBidSuit == "D") { BidTable[BidCounter / 4, BidCounter % 4] = LastBidLevel.ToString() + "<span style='color:orangered'>♦</span>"; } else if (LastBidSuit == "C") { BidTable[BidCounter / 4, BidCounter % 4] = LastBidLevel.ToString() + "<span style='color:darkblue'>♣</span>"; } else { BidTable[BidCounter / 4, BidCounter % 4] = LastBidLevel.ToString() + "NT"; } } } HandRecord handRecord = HandRecords.HandRecordsList.Find(x => x.SectionID == device.SectionID && x.BoardNumber == BoardNumber); if (handRecord == null) // Can't find matching hand record, so use default SectionID = 1 { handRecord = HandRecords.HandRecordsList.Find(x => x.SectionID == 1 && x.BoardNumber == BoardNumber); } CardString = handRecord.HandRow(device.Direction); DisplayRank = new string[13]; DisplaySuit = new string[13]; for (int i = 0; i < 13; i++) { DisplayRank[i] = Utilities.DisplayRank(CardString[i]); DisplaySuit[i] = Utilities.DisplaySuit(CardString[i]); } Dealer = handRecord.Dealer; BidDirections = new string[4]; int northDirectionNumber = (4 - Utilities.DirectionToNumber(Dealer)) % 4; BidDirections[northDirectionNumber] = "North"; BidDirections[(northDirectionNumber + 1) % 4] = "East"; BidDirections[(northDirectionNumber + 2) % 4] = "South"; BidDirections[(northDirectionNumber + 3) % 4] = "West"; if (ToBidDirection == "") { ToBidDirection = Dealer; } // Set table info table.LastBid = new Bid(LastCallDirection, LastBidLevel, LastBidSuit, LastBidX, false, LastBidDirection, PassCount, BidCounter); }
public void UpdatePlayerName(int playerNumber) { PlayerName = ""; // First get the name from the name source string dir = Direction.Substring(0, 1); // Need just N, S, E or W if (playerNumber == 0) { PlayerName = "Unknown"; } else { switch (Settings.NameSource) { case 0: PlayerName = AppData.GetNameFromPlayerNamesTable(playerNumber); break; case 1: PlayerName = Utilities.GetNameFromExternalDatabase(playerNumber); break; case 2: PlayerName = ""; break; case 3: PlayerName = AppData.GetNameFromPlayerNamesTable(playerNumber); if (PlayerName == "" || PlayerName.Substring(0, 1) == "#" || (PlayerName.Length >= 7 && PlayerName.Substring(0, 7) == "Unknown")) { PlayerName = Utilities.GetNameFromExternalDatabase(playerNumber); } break; } } // Now update the PlayerNumbers table in the database // Numbers entered at the start (when round = 1) need to be set as round 0 in the database int roundNumber = RoundNumber; if (roundNumber == 1) { roundNumber = 0; } PlayerName = PlayerName.Replace("'", "''"); // Deal with apostrophes in names, eg O'Connor using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); object queryResult = null; // Check if PlayerNumbers entry exists already; if it does update it, if not create it string SQLString = $"SELECT [Number] FROM PlayerNumbers WHERE Section={SectionID} AND [Table]={TableNumber} AND ROUND={roundNumber} AND Direction='{dir}'"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { queryResult = cmd.ExecuteScalar(); }); } finally { cmd.Dispose(); } if (queryResult == DBNull.Value || queryResult == null) { SQLString = $"INSERT INTO PlayerNumbers (Section, [Table], Direction, [Number], Name, Round, Processed, TimeLog, TabPlayPairNo) VALUES ({SectionID}, {TableNumber}, '{dir}', '{playerNumber}', '{PlayerName}', {roundNumber}, False, #{DateTime.Now:yyyy-MM-dd hh:mm:ss}#, {PairNumber})"; } else { SQLString = $"UPDATE PlayerNumbers SET [Number]='{playerNumber}', [Name]='{PlayerName}', Processed=False, TimeLog=#{DateTime.Now:yyyy-MM-dd hh:mm:ss}# WHERE Section={SectionID} AND [Table]={TableNumber} AND Round={roundNumber} AND Direction='{dir}'"; } OdbcCommand cmd2 = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { cmd2.ExecuteNonQuery(); }); } finally { cmd2.Dispose(); } } return; }
public Playing(int deviceNumber, Table table) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; BoardNumber = table.BoardNumber; // All directionNumbers are relative to the direction that is 0 int directionNumber = Utilities.DirectionToNumber(device.Direction); int northDirectionNumber = (4 - directionNumber) % 4; Direction = new string[4]; Direction[northDirectionNumber] = "North"; Direction[(northDirectionNumber + 1) % 4] = "East"; Direction[(northDirectionNumber + 2) % 4] = "South"; Direction[(northDirectionNumber + 3) % 4] = "West"; PairNumber = new int[4]; PlayerName = new string[4]; for (int i = 0; i < 4; i++) { PairNumber[i] = table.PairNumber[(directionNumber + i) % 4]; PlayerName[i] = table.PlayerName[(directionNumber + i) % 4]; } if (northDirectionNumber % 2 == 0) { Vuln02 = Utilities.NSVulnerability[(BoardNumber - 1) % 16]; Vuln13 = Utilities.EWVulnerability[(BoardNumber - 1) % 16]; } else { Vuln02 = Utilities.EWVulnerability[(BoardNumber - 1) % 16]; Vuln13 = Utilities.NSVulnerability[(BoardNumber - 1) % 16]; } // Set default values for no plays PlayCounter = -999; LastCardNumber = -1; LastCardString = ""; TrickNumber = 1; TricksNS = 0; TricksEW = 0; TrickLeadSuit = ""; TrickCardString = new string[4]; TrickRank = new int[4]; TrickSuit = new string[4]; TrickDisplayRank = new string[4]; TrickDisplaySuit = new string[4]; PreviousTrickDisplayRank = new string[4]; PreviousTrickDisplaySuit = new string[4]; for (int i = 0; i < 4; i++) { TrickCardString[i] = ""; TrickRank[i] = 0; TrickSuit[i] = ""; TrickDisplayRank[i] = ""; TrickDisplaySuit[i] = ""; PreviousTrickDisplayRank[i] = ""; PreviousTrickDisplaySuit[i] = ""; } PollInterval = Settings.PollInterval; if (AppData.IsIndividual) { PairOrPlayer = "Player"; } else { PairOrPlayer = "Pair"; } List <Play> playList = new List <Play>(); using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); // Get contract details string SQLString = $"SELECT [NS/EW], Contract FROM IntermediateData WHERE Section={device.SectionID} AND [Table]={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; string declarerNSEW = ""; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); if (reader.Read()) { declarerNSEW = reader.GetString(0); string contractString = reader.GetString(1); string[] temp = contractString.Split(' '); ContractLevel = Convert.ToInt32(temp[0]); ContractSuit = temp[1]; if (temp.Length > 2) { ContractX = temp[2]; } else { ContractX = ""; } } }); } finally { reader.Close(); cmd.Dispose(); } DisplayContract = Utilities.DisplayContract(ContractLevel, ContractSuit, ContractX); if (declarerNSEW == "N") { Declarer = "North"; } else if (declarerNSEW == "E") { Declarer = "East"; } else if (declarerNSEW == "S") { Declarer = "South"; } else if (declarerNSEW == "W") { Declarer = "West"; } PlayDirectionNumber = (northDirectionNumber + Utilities.DirectionToNumber(Declarer) + 1) % 4; DummyDirectionNumber = (northDirectionNumber + Utilities.DirectionToNumber(Declarer) + 2) % 4; // Get hand records and set cards HandRecord handRecord = HandRecords.HandRecordsList.Find(x => x.SectionID == device.SectionID && x.BoardNumber == BoardNumber); if (handRecord == null) // Can't find matching hand record, so use default SectionID = 1 { handRecord = HandRecords.HandRecordsList.Find(x => x.SectionID == 1 && x.BoardNumber == BoardNumber); } CardString = handRecord.HandTable(northDirectionNumber, ContractSuit); DisplayRank = new string[4, 13]; DisplaySuit = new string[4, 13]; CardPlayed = new bool[4, 13]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 13; j++) { DisplayRank[i, j] = Utilities.DisplayRank(CardString[i, j]); DisplaySuit[i, j] = Utilities.DisplaySuit(CardString[i, j]); CardPlayed[i, j] = false; } } SuitLengths = handRecord.SuitLengths(northDirectionNumber, ContractSuit); // Check PlayData table for any previous plays SQLString = $"SELECT Counter, Direction, Card FROM PlayData WHERE Section={device.SectionID} AND Table={device.TableNumber} AND Round={device.RoundNumber} AND Board={BoardNumber}"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { string tempPlayDirection = reader.GetString(1); string tempCardString = reader.GetString(2); int tempPlayCounter = Convert.ToInt32(reader.GetValue(0)); if (tempPlayDirection == "N") { tempPlayDirection = "North"; } else if (tempPlayDirection == "E") { tempPlayDirection = "East"; } else if (tempPlayDirection == "S") { tempPlayDirection = "South"; } else if (tempPlayDirection == "W") { tempPlayDirection = "West"; } Play play = new Play(tempPlayDirection, 0, tempCardString, tempPlayCounter); playList.Add(play); } }); } finally { reader.Close(); cmd.Dispose(); } } playList.Sort((x, y) => x.PlayCounter.CompareTo(y.PlayCounter)); // Run through each played card (if any) in turn and work out the implications foreach (Play play in playList) { PlayDirectionNumber = (northDirectionNumber + Utilities.DirectionToNumber(play.PlayDirection)) % 4; PlayCounter = play.PlayCounter; int cardNumber; for (cardNumber = 0; cardNumber < 13; cardNumber++) { if (play.CardString == CardString[PlayDirectionNumber, cardNumber]) { break; } } CardPlayed[PlayDirectionNumber, cardNumber] = true; LastCardNumber = cardNumber; LastCardString = CardString[PlayDirectionNumber, cardNumber]; TrickCardString[PlayDirectionNumber] = LastCardString; TrickRank[PlayDirectionNumber] = Utilities.Rank(LastCardString); TrickSuit[PlayDirectionNumber] = Utilities.Suit(LastCardString); TrickDisplayRank[PlayDirectionNumber] = Utilities.DisplayRank(LastCardString); TrickDisplaySuit[PlayDirectionNumber] = Utilities.DisplaySuit(LastCardString); if (PlayCounter % 4 == 0) // First card in trick { TrickLeadSuit = TrickSuit[PlayDirectionNumber]; } if (PlayCounter % 4 == 3) // Last card in trick, so find out which card won the trick... { int winningDirectionNumber = -1; string winningSuit = TrickLeadSuit; int winningRank = 0; for (int i = 0; i < 4; i++) { string suit = Utilities.Suit(TrickCardString[i]); int rank = Utilities.Rank(TrickCardString[i]); if ((winningSuit == TrickLeadSuit && suit == TrickLeadSuit && rank > winningRank) || (winningSuit == ContractSuit && suit == ContractSuit && rank > winningRank)) { winningDirectionNumber = i; winningRank = rank; } else if (TrickLeadSuit != ContractSuit && winningSuit == TrickLeadSuit && suit == ContractSuit) { winningDirectionNumber = i; winningRank = rank; winningSuit = ContractSuit; } } // ... and update trick counts if (Direction[winningDirectionNumber] == "North" || Direction[winningDirectionNumber] == "South") { TricksNS++; } else { TricksEW++; } TrickNumber++; if (PlayCounter == 51) // The unlikely event that all cards played, but no result recorded to database { Result result = new Result(deviceNumber, BoardNumber, "IntermediateData"); result.TricksTakenNumber = (Declarer == "North" || Declarer == "South") ? TricksNS : TricksEW; result.UpdateDB("ReceivedData"); AppData.TableList.Find(x => x.SectionID == device.SectionID && x.TableNumber == device.TableNumber).PlayComplete = true; } else { PlayDirectionNumber = winningDirectionNumber; // Reset current trick info TrickLeadSuit = ""; for (int i = 0; i < 4; i++) { TrickCardString[i] = ""; TrickRank[i] = 0; TrickSuit[i] = ""; PreviousTrickDisplayRank[i] = TrickDisplayRank[i]; PreviousTrickDisplaySuit[i] = TrickDisplaySuit[i]; TrickDisplayRank[i] = ""; TrickDisplaySuit[i] = ""; } } } else { // Not last card in trick, so move play on to next hand. Only used if this is the last played card; otherwise overwritten PlayDirectionNumber = (PlayDirectionNumber + 1) % 4; } } // Update table info table.LastPlay = new Play(Utilities.Directions[PlayDirectionNumber], LastCardNumber, LastCardString, PlayCounter); }
public Traveller(int deviceNumber, Table table) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; BoardNumber = table.BoardNumber; using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString; OdbcCommand cmd = null; OdbcDataReader reader = null; try { if (AppData.IsIndividual) { SQLString = $"SELECT PairNS, PairEW, South, West, [NS/EW], Contract, LeadCard, Result FROM ReceivedData WHERE Section={device.SectionID} AND Board={BoardNumber}"; cmd = new OdbcCommand(SQLString, connection); ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { Result result = new Result() { BoardNumber = BoardNumber, PairNS = reader.GetInt32(0), PairEW = reader.GetInt32(1), South = reader.GetInt32(2), West = reader.GetInt32(3), DeclarerNSEW = reader.GetString(4), Contract = reader.GetString(5), LeadCard = reader.GetString(6), TricksTakenSymbol = reader.GetString(7) }; if (result.Contract.Length > 2) // Testing for unplayed boards and corrupt ReceivedData table { result.CalculateScore(); if (table.PairNumber[0] == result.PairNS) { ContractLevel = result.ContractLevel; DisplayContract = Utilities.DisplayContract(ContractLevel, result.ContractSuit, result.ContractX) + " " + result.TricksTakenSymbol; Declarer = result.Declarer; Score = result.Score; result.CurrentResult = true; } Add(result); } } }); } else { SQLString = $"SELECT PairNS, PairEW, [NS/EW], Contract, LeadCard, Result FROM ReceivedData WHERE Section={device.SectionID} AND Board={BoardNumber}"; cmd = new OdbcCommand(SQLString, connection); ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { Result result = new Result() { BoardNumber = BoardNumber, PairNS = reader.GetInt32(0), PairEW = reader.GetInt32(1), DeclarerNSEW = reader.GetString(2), Contract = reader.GetString(3), LeadCard = reader.GetString(4), TricksTakenSymbol = reader.GetString(5) }; if (result.Contract.Length > 2) // Testing for unplayed boards and corrupt ReceivedData table { result.CalculateScore(); if (table.PairNumber[0] == result.PairNS) { ContractLevel = result.ContractLevel; DisplayContract = Utilities.DisplayContract(ContractLevel, result.ContractSuit, result.ContractX) + " " + result.TricksTakenSymbol; Declarer = result.Declarer; Score = result.Score; result.CurrentResult = true; } Add(result); } } }); } } finally { reader.Close(); cmd.Dispose(); } }; // Sort traveller and calculate percentage for current result Sort((x, y) => y.Score.CompareTo(x.Score)); if (Settings.ShowPercentage) { if (Count == 1) { PercentageNS = 50; } else { int currentMP = 2 * FindAll((x) => x.Score < Score).Count + FindAll((x) => x.Score == Score).Count - 1; PercentageNS = Convert.ToInt32(50.0 * currentMP / (Count - 1)); } } else { PercentageNS = -1; // Don't show percentage } }
public RankingList(int deviceNumber) { DeviceNumber = deviceNumber; Device device = AppData.DeviceList[deviceNumber]; Direction = device.Direction; PairNumber = device.PairNumber; if (AppData.IsIndividual) { PairOrPlayer = "Player"; } else { PairOrPlayer = "Pair"; } using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); string SQLString = $"SELECT Orientation, Number, Score, Rank FROM Results WHERE Section={device.SectionID}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader1 = null; try { ODBCRetryHelper.ODBCRetry(() => { reader1 = cmd.ExecuteReader(); while (reader1.Read()) { Ranking ranking = new Ranking { Orientation = reader1.GetString(0), PairNumber = reader1.GetInt32(1), Score = reader1.GetString(2), Rank = reader1.GetString(3) }; ranking.ScoreDecimal = Convert.ToDouble(ranking.Score); Add(ranking); } }); } catch (OdbcException e) { if (e.Errors.Count > 1 || e.Errors[0].SQLState != "42S02") // Any error other than results table doesn't exist { throw (e); } } finally { reader1.Close(); cmd.Dispose(); } if (Count == 0) // Results table either doesn't exist or contains no entries, so try to calculate rankings { if (AppData.IsIndividual) { InsertRange(0, CalculateIndividualRankingFromReceivedData(connection, device.SectionID)); } else { InsertRange(0, CalculateRankingFromReceivedData(connection, device.SectionID)); } } } // Make sure that ranking list is sorted into presentation order Sort((x, y) => { int sortValue = y.Orientation.CompareTo(x.Orientation); // N's first then E's if (sortValue == 0) { sortValue = y.ScoreDecimal.CompareTo(x.ScoreDecimal); } if (sortValue == 0) { sortValue = x.PairNumber.CompareTo(y.PairNumber); } return(sortValue); }); // Work out if one- or two-winner movement TwoWinners = !AppData.IsIndividual && Exists(x => x.Orientation == "E"); }
private static List <Ranking> CalculateIndividualRankingFromReceivedData(OdbcConnection conn, int sectionID) { List <Ranking> rankingList = new List <Ranking>(); List <Result> resList = new List <Result>(); string SQLString = $"SELECT Board, PairNS, PairEW, South, West, [NS/EW], Contract, Result FROM ReceivedData WHERE Section={sectionID}"; OdbcCommand cmd = new OdbcCommand(SQLString, conn); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { Result result = new Result() { BoardNumber = reader.GetInt32(0), PairNS = reader.GetInt32(1), PairEW = reader.GetInt32(2), South = reader.GetInt32(3), West = reader.GetInt32(4), DeclarerNSEW = reader.GetString(5), Contract = reader.GetString(6), TricksTakenSymbol = reader.GetString(7) }; if (result.Contract.Length > 2) // Testing for unplayed boards and corrupt ReceivedData table { result.CalculateScore(); resList.Add(result); } } }); } catch (OdbcException) { return(null); } finally { reader.Close(); cmd.Dispose(); } // Calculate MPs List <Result> currentBoardResultList = new List <Result>(); int currentBoard; int currentScore; foreach (Result result in resList) { currentScore = result.Score; currentBoard = result.BoardNumber; currentBoardResultList = resList.FindAll(x => x.BoardNumber == currentBoard); result.MatchpointsNS = 2 * currentBoardResultList.FindAll(x => x.Score < currentScore).Count + currentBoardResultList.FindAll(x => x.Score == currentScore).Count - 1; result.MatchpointsMax = 2 * currentBoardResultList.Count - 2; result.MatchpointsEW = result.MatchpointsMax - result.MatchpointsNS; } // Add up MPs for each pair, creating Ranking List entries as we go foreach (Result result in resList) { Ranking rankingListFind = rankingList.Find(x => x.PairNumber == result.PairNS); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairNS, Orientation = "0", MP = result.MatchpointsNS, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsNS; rankingListFind.MPMax += result.MatchpointsMax; } rankingListFind = rankingList.Find(x => x.PairNumber == result.PairEW); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.PairEW, Orientation = "0", MP = result.MatchpointsEW, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsEW; rankingListFind.MPMax += result.MatchpointsMax; } rankingListFind = rankingList.Find(x => x.PairNumber == result.South); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.South, Orientation = "0", MP = result.MatchpointsNS, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsNS; rankingListFind.MPMax += result.MatchpointsMax; } rankingListFind = rankingList.Find(x => x.PairNumber == result.West); if (rankingListFind == null) { Ranking ranking = new Ranking() { PairNumber = result.West, Orientation = "0", MP = result.MatchpointsEW, MPMax = result.MatchpointsMax }; rankingList.Add(ranking); } else { rankingListFind.MP += result.MatchpointsEW; rankingListFind.MPMax += result.MatchpointsMax; } } // Calculate percentages foreach (Ranking ranking in rankingList) { if (ranking.MPMax == 0) { ranking.ScoreDecimal = 50.0; } else { ranking.ScoreDecimal = 100.0 * ranking.MP / ranking.MPMax; } ranking.Score = ranking.ScoreDecimal.ToString("0.##"); } // Calculate ranking rankingList.Sort((x, y) => y.ScoreDecimal.CompareTo(x.ScoreDecimal)); foreach (Ranking ranking in rankingList) { double currentScoreDecimal = ranking.ScoreDecimal; int rank = rankingList.FindAll(x => x.ScoreDecimal > currentScoreDecimal).Count + 1; ranking.Rank = rank.ToString(); if (rankingList.FindAll(x => x.ScoreDecimal == currentScoreDecimal).Count > 1) { ranking.Rank += "="; } } return(rankingList); }
public Move(int deviceNumber, int tableNotReadyNumber) { DeviceNumber = deviceNumber; TableNotReadyNumber = tableNotReadyNumber; Device device = AppData.DeviceList[deviceNumber]; NewRoundNumber = device.RoundNumber + 1; List <MoveOption> moveOptionsList = new List <MoveOption>(); using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { connection.Open(); if (AppData.IsIndividual) { string SQLString = $"SELECT Table, NSPair, EWPair, South, West FROM RoundData WHERE Section={device.SectionID} AND Round={NewRoundNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { MoveOption tempMoveOption = new MoveOption() { TableNumber = reader.GetInt32(0), North = reader.GetInt32(1), East = reader.GetInt32(2), South = reader.GetInt32(3), West = reader.GetInt32(4), }; moveOptionsList.Add(tempMoveOption); } }); } finally { reader.Close(); cmd.Dispose(); } // Try Direction = North MoveOption moveOption = moveOptionsList.Find(x => x.North == device.PairNumber); if (moveOption != null) { NewTableNumber = moveOption.TableNumber; NewDirection = "North"; Stay = (NewTableNumber == device.TableNumber && NewDirection == device.Direction); } else { // Try Direction = South moveOption = moveOptionsList.Find(x => x.South == device.PairNumber); if (moveOption != null) { NewTableNumber = moveOption.TableNumber; NewDirection = "South"; Stay = (NewTableNumber == device.TableNumber && NewDirection == device.Direction); } else { // Try Direction = East moveOption = moveOptionsList.Find(x => x.East == device.PairNumber); if (moveOption != null) { NewTableNumber = moveOption.TableNumber; NewDirection = "East"; Stay = (NewTableNumber == device.TableNumber && NewDirection == device.Direction); } else { // Try Direction = West moveOption = moveOptionsList.Find(x => x.West == device.PairNumber); if (moveOption != null) { NewTableNumber = moveOption.TableNumber; NewDirection = "West"; Stay = (NewTableNumber == device.TableNumber && NewDirection == device.Direction); } else // No move info found - move to sit out { NewTableNumber = 0; NewDirection = ""; Stay = false; } } } } } else // Not individual, so find pair { string SQLString = $"SELECT Table, NSPair, EWPair FROM RoundData WHERE Section={device.SectionID} AND Round={NewRoundNumber}"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { MoveOption tempMoveOption = new MoveOption() { TableNumber = reader.GetInt32(0), North = reader.GetInt32(1), East = reader.GetInt32(2), }; moveOptionsList.Add(tempMoveOption); } }); } finally { reader.Close(); cmd.Dispose(); } MoveOption moveOption = null; if (device.Direction == "North" || device.Direction == "South") { moveOption = moveOptionsList.Find(x => x.North == device.PairNumber); } else { moveOption = moveOptionsList.Find(x => x.East == device.PairNumber); } if (moveOption != null) { NewTableNumber = moveOption.TableNumber; NewDirection = device.Direction; } else { // Pair changes Direction if (device.Direction == "North" || device.Direction == "South") { moveOption = moveOptionsList.Find(x => x.East == device.PairNumber); } else { moveOption = moveOptionsList.Find(x => x.North == device.PairNumber); } if (moveOption != null) { NewTableNumber = moveOption.TableNumber; if (device.Direction == "North") { NewDirection = "East"; } else if (device.Direction == "East") { NewDirection = "North"; } else if (device.Direction == "South") { NewDirection = "West"; } else if (device.Direction == "West") { NewDirection = "South"; } } else // No move info found - move to sit out { NewTableNumber = 0; NewDirection = device.Direction; } } Stay = (NewTableNumber == device.TableNumber && NewDirection == device.Direction); } } }
public static void Set() { if (HandRecordsList.Count > 0) { return; // Hand records already set } using (OdbcConnection connection = new OdbcConnection(AppData.DBConnectionString)) { string SQLString = $"SELECT Section, Board, NorthSpades, NorthHearts, NorthDiamonds, NorthClubs, EastSpades, EastHearts, EastDiamonds, EastClubs, SouthSpades, SouthHearts, SouthDiamonds, SouthClubs, WestSpades, WestHearts, WestDiamonds, WestClubs FROM HandRecord"; OdbcCommand cmd = new OdbcCommand(SQLString, connection); OdbcDataReader reader = null; connection.Open(); try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { HandRecord handRecord = new HandRecord { SectionID = reader.GetInt16(0), BoardNumber = reader.GetInt16(1), NorthSpades = reader.GetString(2), NorthHearts = reader.GetString(3), NorthDiamonds = reader.GetString(4), NorthClubs = reader.GetString(5), EastSpades = reader.GetString(6), EastHearts = reader.GetString(7), EastDiamonds = reader.GetString(8), EastClubs = reader.GetString(9), SouthSpades = reader.GetString(10), SouthHearts = reader.GetString(11), SouthDiamonds = reader.GetString(12), SouthClubs = reader.GetString(13), WestSpades = reader.GetString(14), WestHearts = reader.GetString(15), WestDiamonds = reader.GetString(16), WestClubs = reader.GetString(17) }; handRecord.Dealer = Utilities.GetDealerForBoard(handRecord.BoardNumber); HandRecordsList.Add(handRecord); } }); } finally { reader.Close(); cmd.Dispose(); } SQLString = $"SELECT Section, Board, NorthSpades, NorthHearts, NorthDiamonds, NorthClubs, NorthNotrump, EastSpades, EastHearts, EastDiamonds, EastClubs, EastNotrump, SouthSpades, SouthHearts, SouthDiamonds, SouthClubs, SouthNotrump, WestSpades, WestHearts, WestDiamonds, WestClubs, WestNoTrump, NorthHcp, EastHcp, SouthHcp, WestHcp FROM HandEvaluation"; cmd = new OdbcCommand(SQLString, connection); try { ODBCRetryHelper.ODBCRetry(() => { reader = cmd.ExecuteReader(); while (reader.Read()) { HandRecord handRecord = HandRecordsList.Find(x => x.SectionID == reader.GetInt16(0) && x.BoardNumber == reader.GetInt16(1)); if (handRecord != null) { if (reader.GetInt16(2) > 6) { handRecord.EvalNorthSpades = (reader.GetInt16(2) - 6).ToString(); } else { handRecord.EvalNorthSpades = ""; } if (reader.GetInt16(3) > 6) { handRecord.EvalNorthHearts = (reader.GetInt16(3) - 6).ToString(); } else { handRecord.EvalNorthHearts = ""; } if (reader.GetInt16(4) > 6) { handRecord.EvalNorthDiamonds = (reader.GetInt16(4) - 6).ToString(); } else { handRecord.EvalNorthDiamonds = ""; } if (reader.GetInt16(5) > 6) { handRecord.EvalNorthClubs = (reader.GetInt16(5) - 6).ToString(); } else { handRecord.EvalNorthClubs = ""; } if (reader.GetInt16(6) > 6) { handRecord.EvalNorthNT = (reader.GetInt16(6) - 6).ToString(); } else { handRecord.EvalNorthNT = ""; } if (reader.GetInt16(7) > 6) { handRecord.EvalEastSpades = (reader.GetInt16(7) - 6).ToString(); } else { handRecord.EvalEastSpades = ""; } if (reader.GetInt16(8) > 6) { handRecord.EvalEastHearts = (reader.GetInt16(8) - 6).ToString(); } else { handRecord.EvalEastHearts = ""; } if (reader.GetInt16(9) > 6) { handRecord.EvalEastDiamonds = (reader.GetInt16(9) - 6).ToString(); } else { handRecord.EvalEastDiamonds = ""; } if (reader.GetInt16(10) > 6) { handRecord.EvalEastClubs = (reader.GetInt16(10) - 6).ToString(); } else { handRecord.EvalEastClubs = ""; } if (reader.GetInt16(11) > 6) { handRecord.EvalEastNT = (reader.GetInt16(11) - 6).ToString(); } else { handRecord.EvalEastNT = ""; } if (reader.GetInt16(12) > 6) { handRecord.EvalSouthSpades = (reader.GetInt16(12) - 6).ToString(); } else { handRecord.EvalSouthSpades = ""; } if (reader.GetInt16(13) > 6) { handRecord.EvalSouthHearts = (reader.GetInt16(13) - 6).ToString(); } else { handRecord.EvalSouthHearts = ""; } if (reader.GetInt16(14) > 6) { handRecord.EvalSouthDiamonds = (reader.GetInt16(14) - 6).ToString(); } else { handRecord.EvalSouthDiamonds = ""; } if (reader.GetInt16(15) > 6) { handRecord.EvalSouthClubs = (reader.GetInt16(15) - 6).ToString(); } else { handRecord.EvalSouthClubs = ""; } if (reader.GetInt16(16) > 6) { handRecord.EvalSouthNT = (reader.GetInt16(16) - 6).ToString(); } else { handRecord.EvalSouthNT = ""; } if (reader.GetInt16(17) > 6) { handRecord.EvalWestSpades = (reader.GetInt16(17) - 6).ToString(); } else { handRecord.EvalWestSpades = ""; } if (reader.GetInt16(18) > 6) { handRecord.EvalWestHearts = (reader.GetInt16(18) - 6).ToString(); } else { handRecord.EvalWestHearts = ""; } if (reader.GetInt16(19) > 6) { handRecord.EvalWestDiamonds = (reader.GetInt16(19) - 6).ToString(); } else { handRecord.EvalWestDiamonds = ""; } if (reader.GetInt16(20) > 6) { handRecord.EvalWestClubs = (reader.GetInt16(20) - 6).ToString(); } else { handRecord.EvalWestClubs = ""; } if (reader.GetInt16(21) > 6) { handRecord.EvalWestNT = (reader.GetInt16(21) - 6).ToString(); } else { handRecord.EvalWestNT = ""; } handRecord.HCPNorth = reader.GetInt16(22).ToString(); handRecord.HCPEast = reader.GetInt16(23).ToString(); handRecord.HCPSouth = reader.GetInt16(24).ToString(); handRecord.HCPWest = reader.GetInt16(25).ToString(); } } }); } catch (OdbcException e) { if (e.Errors.Count > 1 || e.Errors[0].SQLState != "42S02") // Error other than HandEvaluation table does not exist { throw (e); } } finally { reader.Close(); cmd.Dispose(); } } return; }