Ejemplo n.º 1
0
        private void AddPendingGameAndState(long id, GameSettings settings)
        {
            if (id >= UserDatabase.START_FOR_NEXT_GAME_IDS)
            {
                throw new InvalidOperationException("START_FOR_NEXT_GAME_IDS too low!");
            }
            var    now            = SystemClock.Instance.UtcNow();
            string capConstraints = settings.CaptureConstraints switch
            {
                GameSettings.DraughtsCaptureConstraints.AnyFinishedSequence => "seq",
                GameSettings.DraughtsCaptureConstraints.MaximumPieces => "max",
                _ => throw new InvalidOperationException("Unknown capture constraint")
            };

            GamesTable.Add(new DbGame {
                Id                    = id,
                BoardSize             = settings.BoardSize,
                FirstMoveColorIsWhite = settings.FirstMove == Color.White,
                FlyingKings           = settings.FlyingKings,
                MenCaptureBackwards   = settings.MenCaptureBackwards,
                CaptureConstraints    = capConstraints,
                Victor                = null,
                CreatedAt             = now, StartedAt = null, FinishedAt = null,
                TurnPlayerId          = null, TurnCreatedAt = null, TurnExpiresAt = null
            });
            GameStatesTable.Add(new DbGameState {
                Id = id,
                CurrentGameState    = GameState.InitialState(new GameId(id), settings.BoardSize).StorageString(),
                CaptureSequenceFrom = null
            });
        }
Ejemplo n.º 2
0
        public async Task <Game> GetGame(int invitationNumber)
        {
            await SyncAsync();

            var games = await GamesTable.Where(x => x.InvitationNumber == invitationNumber).ToListAsync();

            return(games.FirstOrDefault());
        }
Ejemplo n.º 3
0
    //Loads the party from the database.
    private void loadGameTable()
    {
        GamesTable dbGameTable = new GamesTable(new DatabaseConnection());

        games     = dbGameTable.getJoinableGames();
        gameTable = new GameTable(games);
        JoinGameTablePlaceHolder.Controls.Add(gameTable);
    }
Ejemplo n.º 4
0
        public async Task <NewGameDto> GetNewGame(string gameId)
        {
            var result = new NewGameDto
            {
                Game    = await GamesTable.LookupAsync(gameId).ConfigureAwait(false),
                Players = await GetPlayersForGame(gameId).ConfigureAwait(false),
            };

            result.Venue = await GetVenue(result.Game.VenueId).ConfigureAwait(false);

            return(result);
        }
Ejemplo n.º 5
0
        public async Task SyncAsync()
        {
            if (!IsOnline)
            {
                return;
            }
            ReadOnlyCollection <MobileServiceTableOperationError> syncErrors = null;

            try
            {
                await App.MobileService.SyncContext.PushAsync().ConfigureAwait(false);

                await GamesTable.PullAsync("AllGames", this.GamesTable.CreateQuery()).ConfigureAwait(false);

                await PlayersTable.PullAsync("AllPlayers", this.PlayersTable.CreateQuery()).ConfigureAwait(false);

                await VenuesTable.PullAsync("AllVenues", this.PlayersTable.CreateQuery()).ConfigureAwait(false);

                await GamePlayersTable.PullAsync("AllGamePlayers", this.GamePlayersTable.CreateQuery()).ConfigureAwait(false);

                await TeesTable.PullAsync("AllTees", this.TeesTable.CreateQuery()).ConfigureAwait(false);

                await ScoresTable.PullAsync("AllScores", this.ScoresTable.CreateQuery()).ConfigureAwait(false);
            }
            catch (MobileServicePushFailedException exc)
            {
                if (exc.PushResult != null)
                {
                    syncErrors = exc.PushResult.Errors;
                }
            }

            // Simple error/conflict handling.
            if (syncErrors != null)
            {
                foreach (var error in syncErrors)
                {
                    if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
                    {
                        //Update failed, reverting to server's copy.
                        await error.CancelAndUpdateItemAsync(error.Result).ConfigureAwait(false);
                    }
                    else
                    {
                        // Discard local change.
                        await error.CancelAndDiscardItemAsync().ConfigureAwait(false);
                    }

                    Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.",
                                    error.TableName, error.Item["id"]);
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <PlayGameDto> GetPlayGame(string gameId)
        {
            var result = new PlayGameDto
            {
                Game    = await GamesTable.LookupAsync(gameId).ConfigureAwait(false),
                Players = (await GetPlayersForGame(gameId).ConfigureAwait(false)).OrderBy(x => x.Abbreviation).ToList(),
                Tees    = Mapper.Map <List <Tee>, List <TeeDto> >(await TeesTable.Where(x => x.GameId == gameId).OrderBy(x => x.Number).ToListAsync().ConfigureAwait(false)),
                Scores  = Mapper.Map <List <Score>, List <ScoreDto> >(await ScoresTable.Where(x => x.GameId == gameId).ToListAsync().ConfigureAwait(false)),
            };

            result.Venue = await GetVenue(result.Game.VenueId).ConfigureAwait(false);

            return(result);
        }
    //Loads all the details of the current game
    private void loadGame()
    {
        //Check if Im dealing with a fully loaded game object, if not fully load it.
        if (game.FullyLoaded == false)
        {
            GamesTable gamesTable = new GamesTable(new DatabaseConnection());
            game = gamesTable.getGame(game.GameID);
            Session["activeGame"] = game;
        }

        nameTextBox.Text        = game.GameName;
        settingTextBox.Text     = game.GameSetting;
        descriptionTextBox.Text = game.GameDescription;
        additionalTextBox.Text  = game.GameAdditionalInfo;
    }
    //Saves all the details of the current game
    protected void saveButton_Click(object sender, EventArgs e)
    {
        GamesTable gameTable = new GamesTable(new DatabaseConnection());

        //Check if a name is written
        if (nameTextBox.Text == "")
        {
            angryLabel.Text = "A game name is required!";
            return;
        }

        //Check if game name is alrdy taken, or is equal to the current name
        if (nameTextBox.Text != game.GameName)
        {
            bool alreadyExists = gameTable.checkGameExistsByName(nameTextBox.Text);
            if (alreadyExists)
            {
                angryLabel.Text  = "Game Name already taken!";
                nameTextBox.Text = game.GameName;
                return;
            }
        }

        game.GameName           = nameTextBox.Text;
        game.GameSetting        = settingTextBox.Text;
        game.GameDescription    = descriptionTextBox.Text;
        game.GameAdditionalInfo = additionalTextBox.Text;
        if (acceptingPlayersList.SelectedIndex == 0)
        {
            game.AcceptsPlayers = true;
        }
        else
        {
            game.AcceptsPlayers = false;
        }

        gameTable.updateGame(game);
        Session["activeGame"] = game;

        //Handle message
        Session["message"] = new Message("Game Saved!", System.Drawing.Color.Green);

        //Reload page to clear any nonsense before loading
        Response.Redirect("GameInformationGM");
    }
Ejemplo n.º 9
0
        private async Task CleanupGames()
        {
            var now   = DateTimeOffset.Now.AddDays(-2);
            var games = await GamesTable.Where(x => x.CreatedAt < now).ToListAsync().ConfigureAwait(false);

            foreach (var game in games)
            {
                if ((int)game.GameStatus < (int)GameStatus.Started)
                {
                    var gamePlayers = await GamePlayersTable.Where(x => x.GameId == game.Id).ToListAsync().ConfigureAwait(false);

                    foreach (var gamePlayer in gamePlayers)
                    {
                        await GamePlayersTable.DeleteAsync(gamePlayer).ConfigureAwait(false);
                    }
                    await GamesTable.DeleteAsync(game).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 10
0
        /**
         * <summary>
         * This event handler saves the updated game data to the database, updating the game's previous data
         * </summary>
         *
         * @method SaveButton_Click
         * @param {object} sender
         * @param {EventArgs} e
         * @returns {void}
         */
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            int GameID = Convert.ToInt32(Request.QueryString["GameID"]);

            using (GamesConnection db = new GamesConnection())
            {
                // use the student model to save a new record
                GamesTable updatedGameSave = new GamesTable();


                updatedGameSave = (from game in db.GamesTables
                                   where game.GameID == GameID
                                   select game).FirstOrDefault();

                updatedGameSave.Description   = DescriptionTextBox.Text;
                updatedGameSave.TeamOneID     = Convert.ToInt32(TeamOneDropDown.SelectedValue);
                updatedGameSave.TeamTwoID     = Convert.ToInt32(TeamTwoDropDown.SelectedValue);
                updatedGameSave.TeamOnePoints = Convert.ToInt32(TeamOnePointsTextBox.Text);
                updatedGameSave.TeamTwoPoints = Convert.ToInt32(TeamTwoPointsTextBox.Text);
                updatedGameSave.Spectators    = Convert.ToInt32(SpectatorsTextBox.Text);

                if (TeamOnePointsTextBox.Text == TeamTwoPointsTextBox.Text)
                {
                    updatedGameSave.Winner = 5;
                }
                else if (Convert.ToInt32(TeamOnePointsTextBox.Text) > Convert.ToInt32(TeamTwoPointsTextBox.Text))
                {
                    updatedGameSave.Winner = Convert.ToInt32(TeamOneDropDown.SelectedValue);
                }
                else
                {
                    updatedGameSave.Winner = Convert.ToInt32(TeamTwoDropDown.SelectedValue);
                }

                // run insert in DB
                db.SaveChanges();

                // redirect to the updated students page
                Response.Redirect("~/Default.aspx?week=" + updatedGameSave.Week);
            }
        }
Ejemplo n.º 11
0
    protected void createGameButton_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        string gameName    = gameNameTextBox.Text;
        string gameSetting = gameSettingTextBox.Text;
        bool   acceptingPlayers;

        if (acceptPlayersRadioList.SelectedValue == "true")
        {
            acceptingPlayers = true;
        }
        else
        {
            acceptingPlayers = false;
        }

        Game game = new Game();

        game.GameName       = gameName;
        game.GameSetting    = gameSetting;
        game.AcceptsPlayers = acceptingPlayers;

        GamesTable gameTable     = new GamesTable(new DatabaseConnection());
        bool       alreadyExists = gameTable.checkGameExistsByName(gameName);

        if (alreadyExists)
        {
            angryLabel.ForeColor = System.Drawing.Color.Red;
            angryLabel.Text      = "Game Name already taken!  Please try another.";
            return;
        }
        gameTable.insertGame(game, (int)Session["userID"]);

        //Load Home page
        Session["message"] = new Message("Game Created!  You may find it listed under 'Game Master Games'.", System.Drawing.Color.Green);
        Response.Redirect("CreateGame");
    }
Ejemplo n.º 12
0
    protected void deleteAccountButton_Click(object sender, EventArgs e)
    {
        GamesTable gameTable = new GamesTable(new DatabaseConnection());

        //Check if deleteable
        if (gameTable.getGMGames(userID).Count != 0 || gameTable.getPlayerGames(userID).Count != 0)
        {
            angryLabel.ForeColor = System.Drawing.Color.Red;
            angryLabel.Text      = "You cannot delete your account whilst you are still in games.";
            return;
        }

        //Delete the user
        UsersTable userTable = new UsersTable(new DatabaseConnection());

        userTable.deleteUser(userID);

        //Return to login
        Session.Clear();
        Response.Redirect("Login");
    }
Ejemplo n.º 13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Gate Keeper
        if (Session["userID"] == null)
        {
            Response.Redirect("~/Login");
        }
        else
        {
            userID = (int)Session["userID"];
        }

        //Populate User's Games
        GamesTable gameTable = new GamesTable(new DatabaseConnection());

        gmGamesList     = gameTable.getGMGames(userID);
        playerGamesList = gameTable.getPlayerGames(userID);

        loadPlayerGames();
        loadGMGames();
        loadCookies();
    }
Ejemplo n.º 14
0
        public async Task <List <Game> > GetGames(string playerId)
        {
            if (string.IsNullOrEmpty(playerId))
            {
                return(new List <Game>());
            }
            var gamePlayers = await GamePlayersTable.Where(x => x.PlayerId == playerId && x.Hide == false).ToListAsync().ConfigureAwait(false);

            var games = await GamesTable.ToListAsync().ConfigureAwait(false);

            var result = new List <Game>();

            foreach (var gamePlayer in gamePlayers)
            {
                var game = games.FirstOrDefault(x => x.Id == gamePlayer.GameId);
                if (game != null)
                {
                    result.Add(game);
                }
            }

            return(result);
        }
Ejemplo n.º 15
0
        /**
         * <summary>
         * This event handler grabs the data for the game being edited and displays it on the page
         * </summary>
         *
         * @method GetGame
         * @returns {void}
         */
        protected void GetGame()
        {
            int GameID = Convert.ToInt32(Request.QueryString["GameID"]);

            using (GamesConnection db = new GamesConnection())
            {
                //Populate student object instance with Student ID from URL parameter
                GamesTable updatedGame = (from game in db.GamesTables
                                          where game.GameID == GameID
                                          select game).FirstOrDefault();

                //Map student properties to form controls
                if (updatedGame != null)
                {
                    DescriptionTextBox.Text       = updatedGame.Description.ToString();
                    TeamOneDropDown.SelectedValue = updatedGame.TeamOneID.ToString();
                    TeamTwoDropDown.SelectedValue = updatedGame.TeamTwoID.ToString();
                    TeamOnePointsTextBox.Text     = updatedGame.TeamOnePoints.ToString();
                    TeamTwoPointsTextBox.Text     = updatedGame.TeamTwoPoints.ToString();
                    SpectatorsTextBox.Text        = updatedGame.Spectators.ToString();
                }
            }
        }
    //Deletes everythin there is about the game
    protected void deleteButton_Click(object sender, EventArgs e)
    {
        //Remove all game files
        string folderUrl = Server.MapPath("~/Resources\\") + game.GameID;

        if (Directory.Exists(folderUrl))
        {
            string[] files = Directory.GetFiles(folderUrl, "*", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                File.Delete(file);
            }
            Directory.Delete(folderUrl);
        }

        //Delete everything in the database, ragnarok has come.
        GamesTable gamesTable = new GamesTable(new DatabaseConnection());

        gamesTable.deleteGame(game.GameID);

        //Reload to the Home Page
        Session.Remove("activeGame");
        Response.Redirect("~/Home");
    }
Ejemplo n.º 17
0
        private List<Dto.Action> GetAll(StatementValue where)
        {
            List<string> columnNames = new List<string> ();
            columnNames.Add ("id");
            columnNames.Add ("gameId");
            columnNames.Add ("playerId");
            columnNames.Add ("time");
            columnNames.Add ("description");

            List<List<string>> result;
            if (where != null) {
                result = this.Select (columnNames, where);
            } else {
                result = this.Select (columnNames);
            }

            PlayersTable playersTable = new PlayersTable (entity);
            GamesTable gamesTable = new GamesTable (entity);

            List<Dto.Action> actions = new List<Dto.Action> ();
            for (int i = 0; i < result[0].Count; i++) {
                Game game = gamesTable.Get (result [1] [i]);
                Player player = null;
                if (!string.IsNullOrEmpty (result [2] [i]))
                    player = playersTable.Get (int.Parse (result [2] [i]));
                actions.Add (new Dto.Action (int.Parse (result [0] [i]), result [4] [i], game, player, DateTime.Parse (result [3] [i])));
            }
            return actions;
        }
Ejemplo n.º 18
0
        public async Task <Game> GetGame(string gameId)
        {
            await SyncAsync();

            return(await GamesTable.LookupAsync(gameId));
        }
    //Uploads a new image, deletes the old (if applicable), and updates the database
    protected void uploadButton_Click(object sender, EventArgs e)
    {
        string[] acceptedExtensions = new string[] { ".jpg", ".bmp", ".png" };

        if (this.imageUploader.HasFile)
        {
            if (acceptedExtensions.Contains(Path.GetExtension(imageUploader.PostedFile.FileName)))
            {
                if (imageUploader.PostedFile.ContentLength < 26214400)
                {
                    string filename  = Path.GetFileName(imageUploader.FileName);
                    string folderUrl = Server.MapPath("~/Resources\\") + game.GameID;
                    string url       = folderUrl + "\\" + filename;

                    if (!Directory.Exists(folderUrl))
                    {
                        Directory.CreateDirectory(folderUrl);
                    }

                    //If image already exists, delete it and overwrite
                    if (File.Exists(url))
                    {
                        File.Delete(url);
                        imageUploader.SaveAs(url);

                        //Resize the image so it fits properly and doesnt take up a ton of space.
                        ImageResizer.ImageBuilder.Current.Build(url, url, new ResizeSettings("maxwidth=200&maxheight=200"));
                    }
                    //Else make the new image, and add it to the database and pages list
                    else
                    {
                        //Delete existing image if it exists
                        if (game.ImagePath != "")
                        {
                            File.Delete(Server.MapPath("~/") + game.ImagePath);
                        }

                        //Upload new file
                        imageUploader.SaveAs(url);

                        //Set Image Path at end of existing pages
                        game.ImagePath = "Resources/" + game.GameID + "/" + imageUploader.FileName;

                        //Resize the image so it fits properly and doesnt take up a ton of space.
                        ImageResizer.ImageBuilder.Current.Build(url, url, new ResizeSettings("maxwidth=200&maxheight=200"));

                        //Update Game in the db
                        GamesTable gamesTable = new GamesTable(new DatabaseConnection());
                        gamesTable.updateGameImage(game);
                    }
                    angryUploadLabel.ForeColor = System.Drawing.Color.ForestGreen;
                    angryUploadLabel.Text      = "Upload successful!";
                }
                else
                {
                    angryUploadLabel.ForeColor = System.Drawing.Color.Red;
                    angryUploadLabel.Text      = "Upload failed: The image has to be less than 25 mb!";
                }
            }
            else
            {
                angryUploadLabel.ForeColor = System.Drawing.Color.Red;
                angryUploadLabel.Text      = "Upload failed: Only .jpg, .bmp, or .png files are accepted!";
            }
        }
        else
        {
            angryUploadLabel.ForeColor = System.Drawing.Color.Red;
            angryUploadLabel.Text      = "Upload failed: You must select an image to upload!";
        }

        this.Page.Session["activeGame"] = game;
    }
Ejemplo n.º 20
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="line"></param>
        /// <param name="e"></param>
        /// <param name="payload"></param>
        private void ProcessRequest(string line, Exception e, object payload)
        {
            // Make sure socket hasn't closed or thrown an exception
            if (ReferenceEquals(line, null) && ReferenceEquals(e, null) || !ReferenceEquals(e, null))
            {
                return;
            }

            // The StringSocket to talk to this client.
            StringSocket ss = (StringSocket)payload;

            // Lowercase the line so we can process requests case-insensitively
            line = line.ToLower();

            // Remove whitespace from the end of the string that browsers seem to tack on and I can't seem to do a match for
            line = line.Trim();

            // Send valid HTTP connection message
            ss.BeginSend("HTTP/1.1 200 OK\r\n", (ee, pp) => { }, null);
            ss.BeginSend("Connection: close\r\n", (ee, pp) => { }, null);
            ss.BeginSend("Content-Type: text/html; charset=UTF-8\r\n", (ee, pp) => { }, null);
            ss.BeginSend("\r\n", (ee, pp) => { }, null);

            // Upon receiving "GET /players HTTP/1.1" the server will send back an HTML web page containing a table of information 
            // reporting all games played. The table should have one row for each player in the database and four columns. 
            // Each row should consist of the player's name, the number of games won by the player, the number of games lost by the player, 
            // and the number of games tied by the player. 
            if (line == "get /players http/1.1" || line == "get /players/ http/1.1")
            {
                PlayersTable pt = new PlayersTable();

                // Connect to the DB
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    try
                    {
                        // Open a connection
                        conn.Open();

                        // Create a command
                        MySqlCommand command = conn.CreateCommand();
                        command.CommandText = "SELECT * from Players";

                        // Execute the command and cycle through the DataReader object
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                pt.name.Add(reader["Name"].ToString());
                                pt.won.Add((int)reader["Won"]);
                                pt.tied.Add((int)reader["Tied"]);
                                pt.lost.Add((int)reader["Lost"]);
                            }
                        }
                    }
                    catch (Exception f)
                    {
                        Console.WriteLine(f.Message);
                    }
                }
                // Start sending data back to web page as HTML table
                ss.BeginSend("All Games Played: " +
                            "<table width=\"100%\" border=\"2\">" +
                            "<tr>" +
                            "<td>Player Name</td>" +
                            "<td>Games Won</td>" +
                            "<td>Games Tied</td>" +
                            "<td>Games Lost</td>" +
                            "</tr>" +

                            "<tr>", (ee, pp) => { }, null);

                for (int i = 0; i < pt.name.Count; i++)
                {
                    ss.BeginSend("<tr>" +
                        string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", pt.name[i]) +
                        string.Format("<td>{0}</td>", pt.won[i]) +
                        string.Format("<td>{0}</td>", pt.tied[i]) +
                        string.Format("<td>{0}</td>", pt.lost[i]) +
                        "</tr>", (ee, pp) => { }, null);
                }
                // Link to all Players and all Games
                ss.BeginSend("</table>" +
                    "<p>" +
                    "<a href=\"/players\">List of all Players</a>" +
                    "</p>" +
                    "<p>" +
                    "<a href=\"/games\">List of all Games</a>" +
                    "</p>", (ee, pp) => { }, null); 
            }

            // Upon receiving "GET /games?player=Joe HTTP/1.1" the server will send back an HTML web page containing 
            // a table of information reporting all games by the player "Joe". There should be one row for each 
            // game played by the player named in the line of text (e.g., "Joe" in the example above) and six columns. 
            // Each row should consist of a number that uniquely identifies the game (see the next paragraph for how that number will be used), 
            // the date and time when the game was played, the name of the opponent, the score for the named player, and the score for the opponent.
            else if (Regex.IsMatch(line, @"^get /games\?player=[a-z0-9_]{1,20} http/1\.1")) // Player names are capped at 20 max (see Player class)
            {
                GamesTable gt = new GamesTable();
                bool player1 = false;
              
                // Extract the player's name from the line
                string playerName = line.Substring(18, line.Length - 27);

                // Connect to the DB
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    try
                    {
                        // Open a connection
                        conn.Open();

                        // Create a command
                        MySqlCommand command = conn.CreateCommand();

                        // Check to see if player exists in Player1 field or Player2 field
                        command.CommandText = "SELECT Player1 from Games WHERE Player1 = '" + playerName + "'";
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                player1 = true;
                            }
                        }

                        // If player exists in Player1 field, get opponents data
                        if (player1)
                        {
                            command.CommandText = "SELECT GameID, DateTime, Player2, Player1Score, Player2Score from Games WHERE Player1 = '" + playerName + "'";
                            using (MySqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    gt.gameID.Add((int)reader["GameID"]);
                                    gt.dateTime.Add(reader["DateTime"].ToString());
                                    gt.player2.Add(reader["Player2"].ToString());
                                    gt.player1Score.Add((int)reader["Player1Score"]);
                                    gt.player2Score.Add((int)reader["Player2Score"]);
                                }
                            }
                        }
                        // Player must be in Player2 field
                        else
                        {
                            command.CommandText = "SELECT GameID, DateTime, Player1, Player1Score, Player2Score from Games WHERE Player2 = '" + playerName + "'";
                            using (MySqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    gt.gameID.Add((int)reader["GameID"]);
                                    gt.dateTime.Add(reader["DateTime"].ToString());
                                    gt.player1.Add(reader["Player1"].ToString());
                                    gt.player1Score.Add((int)reader["Player1Score"]);
                                    gt.player2Score.Add((int)reader["Player2Score"]);
                                }
                            }
                        }
                    }
                    catch (Exception f)
                    {
                        Console.WriteLine(f.Message);
                    }
                }

                ss.BeginSend(string.Format("<p>Player {0} Stats:</p>", playerName) +
                        "<table width=\"100%\" border=\"2\">" +
                            "<tr>"+
                            "<td>Game ID</td>" +
                            "<td>Date & Time</td>" +
                            "<td>Opponent Name</td>" +
                            "<td>Your Score</td>" +
                            "<td>Opponent Score</td>" +
                            "</tr>" , (ee, pp) => { }, null);

                // If the player is in Player1 field, post data on Player2 as opponent
                if (player1)
                {
                    for (int i = 0; i < gt.gameID.Count; i++)
                    {
                        ss.BeginSend("<tr>" +
                            string.Format("<td><a href=\"/game?id={0}\">{0}</a></td>", gt.gameID[i]) +
                            string.Format("<td>{0}</td>", gt.dateTime[i]) +
                            string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player2[i]) +
                            string.Format("<td>{0}</td>", gt.player1Score[i]) +
                            string.Format("<td>{0}</td>", gt.player2Score[i]) +
                            "</tr>", (ee, pp) => { }, null);
                    }
                }
                // Player is in Player2 field, post data on Player1 as opponent
                else
                {
                    for (int i = 0; i < gt.gameID.Count; i++)
                    {
                        ss.BeginSend("<tr>" +
                            string.Format("<td><a href=\"/game?id={0}\">{0}</a></td>", gt.gameID[i]) +
                            string.Format("<td>{0}</td>", gt.dateTime[i]) +
                            string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player1[i]) +
                            string.Format("<td>{0}</td>", gt.player2Score[i]) +
                            string.Format("<td>{0}</td>", gt.player1Score[i]) +
                            "</tr>", (ee, pp) => { }, null);
                    }
                }
                // Link to all Players and all Games
                ss.BeginSend("</table>" +
                    "<p>" +
                    "<a href=\"/players\">List of all Players</a>" +
                    "</p>" +
                    "<p>" +
                    "<a href=\"/games\">List of all Games</a>" +
                    "</p>", (ee, pp) => { }, null);  

            }
            // Upon receiving "GET /game?id=35 HTTP/1.1" the server should send back an HTML page containing information 
            // about the specified game (e.g., 35 in this example). The page should contain the names and scores of 
            // the two players involved, the date and time when the game was played, a 4x4 table containing the Boggle board that was used, 
            // the time limit that was used for the game, and the five-part word summary.
            else if (Regex.IsMatch(line, @"get /game\?id=[1-9][0-9]{0,11} http/1\.1")) // Put a cap on game numbers (11 integers long)
            {                
                GamesTable gt = new GamesTable();
                WordsTable wt = new WordsTable();

                // Extract the gameID from the line
                string gameIDAsString = line.Substring(13, line.Length-22);
                int gameID;
                int.TryParse(gameIDAsString, out gameID); // This cannot fail because of the Regex above (0-11 ints long)

                // Connect to the DB
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    try
                    {
                        // Open a connection
                        conn.Open();

                        // Create a command
                        MySqlCommand command = conn.CreateCommand();
                        command.CommandText = "SELECT Player1, Player2, Player1Score, Player2Score, DateTime, Board, TimeLimit, Word, Status " +
                                              "FROM Games, Words WHERE Games.GameID = " + gameID + " AND Words.Game = " + gameID;

                        gt.gameID.Add(gameID);

                        // Execute the command and cycle through the DataReader object
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                gt.player1.Add(reader["Player1"].ToString());
                                gt.player2.Add(reader["Player2"].ToString());
                                gt.player1Score.Add((int)reader["Player1Score"]);
                                gt.player2Score.Add((int)reader["Player2Score"]);
                                gt.dateTime.Add(reader["DateTime"].ToString());
                                gt.board = reader["Board"].ToString();
                                gt.timeLimit = (int)reader["TimeLimit"];
                                wt.word.Add(reader["Word"].ToString());
                                wt.status.Add(reader["Status"].ToString());
                            }
                        }
                    }
                    catch (Exception f)
                    {
                        Console.WriteLine(f.Message);
                    }
                }

                // Send game stats
                ss.BeginSend(string.Format("<p>Game {0} Stats:</p>", gameID) +
                        "<table width=\"100%\" border=\"2\">" +
                            "<tr>" +
                            "<td>Player 1 Name</td>" +
                            "<td>Player 2 Name</td>" +
                            "<td>Player 1 Score</td>" +
                            "<td>Player 2 Score</td>" +
                            "<td>Date & Time</td>" +
                            "<td>Time Limit</td>" +
                            "</tr>", (ee, pp) => { }, null);

                ss.BeginSend("<tr>" +
                        string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player1[0]) +
                        string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player2[0]) + 
                        string.Format("<td>{0}</td>", gt.player1Score[0]) +
                        string.Format("<td>{0}</td>", gt.player2Score[0]) +
                        string.Format("<td>{0}</td>", gt.dateTime[0]) +
                        string.Format("<td>{0}</td>", gt.timeLimit) +
                        "</tr>" +
                        "</table>", (ee, pp) => { }, null);


                // Send board configuration as a 4x4 table
                ss.BeginSend("<p>Board Configuration:</p>" +
                        "<table width=\"10%\" border=\"2\">", (ee, pp) => { }, null);
                // first row
                string board1 = gt.board.Substring(0, 4);
                ss.BeginSend("<tr>", (ee, pp) => { }, null);
                for(int i = 0; i < 4; i++) 
                {
                    ss.BeginSend(string.Format("<td>{0}</td>", board1[i]), (ee, pp) => { }, null);
                }
                ss.BeginSend("</tr>", (ee, pp) => { }, null);
                
                // second row
                string board2 = gt.board.Substring(4, 4);
                ss.BeginSend("<tr>", (ee, pp) => { }, null);
                for (int i = 0; i < 4; i++)
                {
                    ss.BeginSend(string.Format("<td>{0}</td>", board2[i]), (ee, pp) => { }, null);
                }
                ss.BeginSend("</tr>", (ee, pp) => { }, null);

                // third row
                string board3 = gt.board.Substring(8, 4);
                ss.BeginSend("<tr>", (ee, pp) => { }, null);
                for (int i = 0; i < 4; i++)
                {
                    ss.BeginSend(string.Format("<td>{0}</td>", board3[i]), (ee, pp) => { }, null);
                }
                ss.BeginSend("</tr>", (ee, pp) => { }, null);

                // fourth row
                string board4 = gt.board.Substring(12, 4);
                ss.BeginSend("<tr>", (ee, pp) => { }, null);
                for (int i = 0; i < 4; i++)
                {
                    ss.BeginSend(string.Format("<td>{0}</td>", board4[i]), (ee, pp) => { }, null);
                }
                ss.BeginSend("</tr>", (ee, pp) => { }, null); 
                ss.BeginSend("</table>", (ee, pp) => { }, null);

                // Send word summary
                ss.BeginSend("<p>Word Summary</p>" +
                        "<table width=\"15%\" border=\"2\">", (ee, pp) => { }, null);

                for (int i = 0; i < wt.word.Count; i++)
                {
                    ss.BeginSend("<tr>"+
                            string.Format("<td>{0}</td>", wt.word[i]) +
                            string.Format("<td>{0}</td>", wt.status[i])
                            , (ee, pp) => { }, null);
                }
                // Link to all Players and all Games
                ss.BeginSend("</table>" +
                    "<p>" +
                    "<a href=\"/players\">List of all Players</a>" +
                    "</p>"+
                    "<p>" +
                    "<a href=\"/games\">List of all Games</a>" +
                    "</p>", (ee, pp) => { }, null);                  
            }
            else if (line == "get /games http/1.1" || line == "get /games/ http/1.1") 
            {
                GamesTable gt = new GamesTable();

                // Connect to the DB
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    try
                    {
                        // Open a connection
                        conn.Open();

                        // Create a command
                        MySqlCommand command = conn.CreateCommand();
                        command.CommandText = "SELECT GameID, Player1, Player2, DateTime FROM Games";

                        // Execute the command and cycle through the DataReader object
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                gt.gameID.Add((int)reader["GameID"]);
                                gt.player1.Add(reader["Player1"].ToString());
                                gt.player2.Add(reader["Player2"].ToString());
                                gt.dateTime.Add(reader["DateTime"].ToString());
                            }
                        }
                    }
                    catch (Exception f)
                    {
                        Console.WriteLine(f.Message);
                    }
                }

                // Send game stats
                ss.BeginSend("<p>List of all Games in Database:</p>" +
                        "<table width=\"50%\" border=\"2\">" +
                            "<tr>" +
                            "<td>Game ID</td>" +
                            "<td>Player 1 Name</td>" +
                            "<td>Player 2 Name</td>" +
                            "<td>Date & Time</td>" +
                            "</tr>", (ee, pp) => { }, null);

                for (int i = 0; i < gt.player1.Count; i++)
                {
                    ss.BeginSend("<tr>" +
                        string.Format("<td><a href=\"/game?id={0}\">{0}</a></td>", gt.gameID[i]) +
                        string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player1[i]) +
                        string.Format("<td><a href=\"/games?player={0}\">{0}</a></td>", gt.player2[i]) +
                        string.Format("<td>{0}</td>", gt.dateTime[i]) +
                        "</tr>", (ee, pp) => { }, null);
                }
                // Link to all Players and all Games
                ss.BeginSend("</table>" +
                    "<p>" +
                    "<a href=\"/players\">List of all Players</a>" +
                    "</p>", (ee, pp) => { }, null); 
            }
            // If the first line of text sent by the browser to the server is anything else, the server should send back an HTML page 
            // containing an error message. The error message should be meaningful and contain a summary of valid options.
            else
            {
                // The line below this one is a generic placeholder for what needs to be sent
                ss.BeginSend(string.Format("<p>ERROR, you sent: [{0}]</p><p>The only valid commands are /players, /games?player=[player name], and /game?id=[integer]</p>", line), (ee, pp) => { }, null);
            }

            // Close the StringSocket
            ss.Close();
        }
Ejemplo n.º 21
0
        public Answer Get(int id)
        {
            try {
                List<string> columnNames = new List<string> ();
                columnNames.Add ("id");
                columnNames.Add ("gameId");
                columnNames.Add ("playerId");
                columnNames.Add ("questionId");
                columnNames.Add ("answer");
                StatementValue where = new StatementValue ()
            {
                Item1 = "id = @StatementValue0",
                Item2 = new List<string>()
            };
                where.Item2.Add (id.ToString ());
                List<List<string>> result = this.Select (columnNames, where);

                GamesTable gamesTable = new GamesTable (entity);
                PlayersTable playersTable = new PlayersTable (entity);
                QuestionsTable questionsTable = new QuestionsTable (entity);

                List<Answer> answers = new List<Answer> ();
                for (int i = 0; i < result[0].Count; i++) {
                    Game game = gamesTable.GetShallow (int.Parse (result [1] [i]));
                    Player player = null;
                    if (!string.IsNullOrEmpty (result [4] [i]))
                        player = playersTable.Get (int.Parse (result [2] [i]));
                    Question question = questionsTable.Get (int.Parse (result [3] [i]));
                    answers.Add (new Answer (int.Parse (result [0] [i]), question, game, player, result [4] [i]));
                }
                return answers.FirstOrDefault ();
            } catch (MySqlException ex) {
                switch (ex.Number) {
                case 0:
                    throw new DatabaseException ("Cannot connect to server.  Contact administrator", ex);
                case 1045:
                    throw new DatabaseException ("Invalid username/password, please try again", ex);
                default:
                    throw new DatabaseException (ex.Message, ex);
                }
            }
        }