/// <summary>
        /// Creates the HTML string that will be used to get the tables for all games
        /// </summary>
        /// <returns></returns>
        public string allGamesTableCreator()
        {
            // Connect to the DB
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    // Open a connection
                    conn.Open();

                    MySqlCommand command = conn.CreateCommand();
                    command.CommandText = "Select GameID, Duration From Games";

                    //Dictionary used to hold all games that have been played
                    Dictionary <uint, GameModel> games = new Dictionary <uint, GameModel>();

                    // Execute the command and cycle through the DataReader object
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        //Create a gameModel out of the current game and add it to the games dictionary
                        while (reader.Read())
                        {
                            uint      currGameID  = uint.Parse(reader["GameID"].ToString());
                            GameModel currentGame = new GameModel(currGameID, uint.Parse(reader["Duration"].ToString()));
                            games.Add(currGameID, currentGame);
                        }
                    }

                    command.CommandText = "Select PlayerID, Game, Score, Accuracy From Players";

                    // Execute the command and cycle through the DataReader object
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        //Add every player to the game that they played
                        while (reader.Read())
                        {
                            String playerID = reader["PlayerID"].ToString();
                            uint   score    = uint.Parse(reader["Score"].ToString());
                            uint   accuracy = uint.Parse(reader["Accuracy"].ToString());

                            PlayerModel newPlayer = new PlayerModel(playerID, score, accuracy);
                            games[uint.Parse(reader["Game"].ToString())].AddPlayer(playerID, score, accuracy);
                        }
                    }

                    return(WebViews.GetAllGames(games));
                }
                catch (Exception e)
                {
                    return("Error: " + e.Message);
                }
            }
        }
Example #2
0
        /// <summary>
        /// This handles the HTTP request and makes the web page depending on the request
        /// </summary>
        /// <param name="ss">Socket state for the connection</param>
        public static void ServeHttpRequest(SocketState ss)
        {
            if (ss.ErrorOccured == true)
            {
                Console.WriteLine("Error occured while accepting: \"" + ss.ErrorMessage + "\"");
                return;
            }

            string request = ss.GetData();

            Console.WriteLine(request);

            //Player request
            if (request.Contains("GET /games?player="))
            {
                //Finds the player name with substring
                int    start  = request.IndexOf("=") + 1;
                int    length = request.IndexOf(" HTTP/1.1") - start;
                string name   = request.Substring(start, length);

                //Gets all of the players in the form of a dictionary
                Dictionary <uint, PlayerModel> playersDictionary = DatabaseController.GetAllPlayerGames(name);

                //Creates list of sessions that the player has been in by getting the game durations from the database
                List <SessionModel> SessionList = new List <SessionModel>();
                foreach (KeyValuePair <uint, PlayerModel> player in playersDictionary)
                {
                    SessionList.Add(new SessionModel(player.Key, DatabaseController.GetGameDuration(player.Key), player.Value.Score, player.Value.Accuracy));
                }

                //Sends the list so it can be formatted into a table
                Networking.SendAndClose(ss.TheSocket, WebViews.GetPlayerGames(name, SessionList));
            }
            //Games request
            else if (request.Contains("GET /games HTTP/1.1"))
            {
                //Creates a table with each of the games and all of their data
                Networking.SendAndClose(ss.TheSocket, WebViews.GetAllGames(DatabaseController.GetAllGames()));
            }
            //If there aren't any slashes it goes to the home page
            else if (request.Contains("GET / HTTP/1.1"))
            {
                Networking.SendAndClose(ss.TheSocket, WebViews.GetHomePage(0));
            }
            //Otherwise it throws a 404 error
            else
            {
                Networking.SendAndClose(ss.TheSocket, WebViews.Get404());
            }
        }
        /// <summary>
        /// Creates the HTML string that will be used to get the table for any individual
        /// player
        /// </summary>
        /// <param name="name">The name of the player</param>
        /// <returns></returns>
        public string individualTableCreator(String name)
        {
            // Connect to the DB
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    // Open a connection
                    conn.Open();

                    MySqlCommand command = conn.CreateCommand();
                    command.CommandText = "Select PlayerID, Game, Score, Accuracy From Players";

                    //Lists used to hold information about the players
                    List <SessionModel> games            = new List <SessionModel>();
                    List <uint>         currGameIDs      = new List <uint>();
                    List <uint>         currGameDurs     = new List <uint>();
                    List <uint>         currGameScore    = new List <uint>();
                    List <uint>         currGameAccuracy = new List <uint>();


                    // Execute the command and cycle through the DataReader object
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            //Add all the player data to its aplicable table
                            if (reader["PlayerID"].Equals(name))
                            {
                                currGameIDs.Add(uint.Parse(reader["Game"].ToString()));
                                currGameScore.Add(uint.Parse(reader["Score"].ToString()));
                                currGameAccuracy.Add(uint.Parse(reader["Accuracy"].ToString()));
                            }
                        }
                    }
                    //If the player hasn't played any games, the url is invalid
                    if (currGameIDs.Count == 0)
                    {
                        return(errorMessage());
                    }
                    //Get the duration for each game the player has played
                    foreach (uint i in currGameIDs)
                    {
                        command.CommandText = "Select Duration From Games Where GameID=" + "'" + i + "'" + "";
                        currGameDurs.Add(uint.Parse(command.ExecuteScalar().ToString()));
                    }
                    //Turn each game the player has played into a session model
                    //Add those to the games list
                    for (int i = 0; i < currGameIDs.Count; i++)
                    {
                        SessionModel newGame = new SessionModel(currGameIDs[i], currGameDurs[i], currGameScore[i], currGameAccuracy[i]);
                        games.Add(newGame);
                    }

                    return(WebViews.GetPlayerGames(name, games));
                }
                catch (Exception e)
                {
                    return("Error: " + e.Message);
                }
            }
        }
 /// <summary>
 /// Used to send home page html string
 /// </summary>
 /// <returns></returns>
 public string sendToHomePage()
 {
     return(WebViews.GetHomePage());
 }
 /// <summary>
 /// Method used when an Invalid URL is used
 /// </summary>
 /// <returns></returns>
 public string errorMessage()
 {
     return(WebViews.Get404());
 }
        /// <summary>
        /// Gets the view.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="convertView">The convert view.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="position">The position.</param>
        /// <returns>Android.Views.View.</returns>
        protected virtual Android.Views.View GetView(string item, Android.Views.View convertView, Android.Views.ViewGroup parent, int position)
        {
            if (item.Contains("youtu"))
            {
                var inflatorservice = (LayoutInflater)Android.App.Application.Context.GetSystemService(Android.App.Application.LayoutInflaterService);
                var convertview     = inflatorservice.Inflate(Resource.Layout.Video, parent, false);
                // convertview ^
                var control = ((LinearLayout)convertview);
                customViewContainer = convertview.FindViewById <FrameLayout>(Resource.Id.customViewContainer);
                //string youTubeVideoHTML = "<body style='padding: 0; margin: 0; background: #000000;'><iframe width='100%' height='{1}' src='{0}' allowfullscreen = 'allowfullscreen' mozallowfullscreen = 'mozallowfullscreen' msallowfullscreen ='msallowfullscreen' oallowfullscreen = 'oallowfullscreen' webkitallowfullscreen = 'webkitallowfullscreen'></iframe></body>";

                string youTubeVideoHTML = "<body style='padding: 0; margin: 0; background: #000000;'><iframe width='100%' height={0} src='{0}' allowfullscreen></iframe></body>";
                string html             = string.Format(youTubeVideoHTML, "https://www.youtube.com/embed/" + item.Split('=').LastOrDefault() + "?start=0&amp;wmode=transparent&amp;fs=1", 160);



                var webView = convertview.FindViewById <Android.Webkit.WebView>(Resource.Id.webView);
                webView.Settings.JavaScriptEnabled = true;
                webView.Settings.SetPluginState(WebSettings.PluginState.On);
                webView.Settings.PluginsEnabled = true;

                webView.SetWebChromeClient(new CustomWebChromeClient(webView));

                webView.Focusable = true;
                webView.Clickable = true;
                webView.Click    += (s, e) =>
                {
                };


                var mime     = "text/html";
                var encoding = "utf-8";

                webView.LoadData(html, mime, encoding);

                WebViews.Add(webView);

                return(control);
            }
            else
            {
                var imageView = convertView as ImageView ?? new ImageView(parent.Context);

                if (IsValidUrl(item))
                {
                    Task.Run(async() =>
                    {
                        Bitmap imageBitmap = null;

                        using (var webClient = new WebClient())
                        {
                            var imageBytes = await webClient.DownloadDataTaskAsync(new Uri(item));
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                try
                                {
                                    double newHeight = 142;
                                    imageBitmap      = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);

                                    //var width = (320 * imageBitmap.Width) / (imageBitmap.Height);
                                    decimal ratio = (App.MobileDevice.CurrentDevice.Display.Width / 160);

                                    if ((imageBitmap.Width / imageBitmap.Height) > ratio)
                                    {
                                        //var height = (App.MobileDevice.CurrentDevice.Display.Width * imageBitmap.Height) / imageBitmap.Width;
                                        //Bitmap bitmap = Bitmap.CreateScaledBitmap(imageBitmap, App.MobileDevice.CurrentDevice.Display.Width, height, false);
                                        //imageView.SetImageBitmap(bitmap);
                                        var width = 0.0;
                                        if (imageBitmap.Height > 160)
                                        {
                                            width = Convert.ToDouble(imageBitmap.Width) / (Convert.ToDouble(imageBitmap.Height) / 160);
                                        }
                                        else
                                        {
                                            width = (160 / Convert.ToDouble(imageBitmap.Height)) * Convert.ToDouble(App.MobileDevice.CurrentDevice.Display.Width);
                                        }

                                        var newWidth  = Convert.ToInt32(Math.Round(width, 0));
                                        Bitmap bitmap = Bitmap.CreateScaledBitmap(imageBitmap, newWidth, 160, false);
                                        imageView.SetImageBitmap(bitmap);
                                    }
                                    else
                                    {
                                        //var width = (App.MobileDevice.CurrentDevice.Display.Height * imageBitmap.Width) / imageBitmap.Height;
                                        //Bitmap bitmap = Bitmap.CreateScaledBitmap(imageBitmap, width, App.MobileDevice.CurrentDevice.Display.Height, false);
                                        //imageView.SetImageBitmap(bitmap);

                                        var height = 0.0;

                                        if (imageBitmap.Width > App.MobileDevice.CurrentDevice.Display.Width)
                                        {
                                            height = imageBitmap.Height / (Convert.ToDouble(imageBitmap.Width) / Convert.ToDouble(App.MobileDevice.CurrentDevice.Display.Width));
                                        }
                                        else
                                        {
                                            height = (Convert.ToDouble(App.MobileDevice.CurrentDevice.Display.Width) / Convert.ToDouble(imageBitmap.Width)) * imageBitmap.Height;
                                        }

                                        newHeight     = Convert.ToInt32(Math.Round(height, 0));
                                        Bitmap bitmap = Bitmap.CreateScaledBitmap(imageBitmap, App.MobileDevice.CurrentDevice.Display.Width, (int)newHeight, false);
                                        imageView.SetImageBitmap(bitmap);
                                    }

                                    imageView.SetBackgroundColor(Android.Graphics.Color.Black);
                                    //imageView.sethei
                                }
                                catch (Exception ex) { }
                            });
                        }
                        //await GetBitmapFromUrl(imageView, item);
                    });
                }
                else
                {
                    imageView.SetImageResource(Resources.GetIdentifier(System.IO.Path.GetFileNameWithoutExtension(item), "drawable", Context.PackageName));
                }

                //imageView.SetMinimumWidth(App.MobileDevice.CurrentDevice.Display.Width);
                imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
                imageView.SetAdjustViewBounds(true);
                //imageView.SetBackgroundColor(Android.Graphics.Color.Yellow);

                return(imageView);
            }
        }