Ejemplo n.º 1
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            MvcHandler.DisableMvcResponseHeader = true; //to remove MVC version disclosure

            //getting all the data required for initialization
            string dataRoot    = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
            string rawUpgrades = File.ReadAllText(dataRoot + @"\tofu-universe-upgrades.js");
            string rawItems    = File.ReadAllText(dataRoot + @"\tofu-universe-items.js");
            string iv          = WebConfigurationManager.AppSettings["iv"];
            string key         = WebConfigurationManager.AppSettings["key"];

            //initialize all of our custom classes
            Database.Initialize(System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString());
            Upgrade.Initialize(JsonConvert.DeserializeObject <Dictionary <int, dynamic> >(rawUpgrades));
            Item.Initialize(JsonConvert.DeserializeObject <Dictionary <int, dynamic> >(rawItems));
            AESCryptoStuff.Initialize(iv, key);
            Hmac.Initialize(key);
            ValidityMap.Initialize();

            //transfer storage objects to .js files served to the client
            string scriptsRoot  = Server.MapPath("~") + @"\Scripts\TofuUniverse\";
            string itemsFile    = "let _tofuUniverse = {}; _tofuUniverse.ITEMS = " + rawItems;
            string upgradesFile = "_tofuUniverse.UPGRADES = " + rawUpgrades;

            File.WriteAllText(scriptsRoot + "tofu-universe-items.js", itemsFile);
            File.WriteAllText(scriptsRoot + "tofu-universe-upgrades.js", upgradesFile);
        }
Ejemplo n.º 2
0
        public ActionResult TransactionHistory()
        {
            #region role and is logged in
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }

            if (Session["role"].ToString() != "Admin")
            {
                return(RedirectToAction("Index", "Unauthorised"));
            }


            #endregion

            Database d = Database.CurrentInstance;
            try
            {
                if (d.OpenConnection())
                {
                    List <TransactionHistory> transactions = new List <TransactionHistory>();
                    string SearchQuery = "SELECT * FROM dububase.beantransaction Order by dateOfTransaction Desc";

                    MySqlCommand   c   = new MySqlCommand(SearchQuery, d.conn);
                    AESCryptoStuff AES = AESCryptoStuff.CurrentInstance;
                    using (MySqlDataReader r = c.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            transactions.Add(new TransactionHistory
                            {
                                TransactionNo     = AES.AesDecrypt(r["transactionNo"].ToString()),
                                TransactionDesc   = AES.AesDecrypt(r["transactionDesc"].ToString()),
                                Price             = Convert.ToDouble(r["priceOfBeans"]),
                                Status            = r["status"].ToString(),
                                BeansBefore       = Convert.ToInt32(r["userBeansBefore"]),
                                BeansAfter        = Convert.ToInt32(r["userBeansAfter"]),
                                DateOfTransaction = (Convert.ToDateTime(r["dateOfTransaction"])).ToString(),
                                UserID            = AES.AesDecrypt(r["UserID"].ToString())
                            });
                        }
                    }
                    ViewBag.Transactions = transactions;
                    return(View());
                }
            }
            catch (MySqlException e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                d.CloseConnection();
            }

            return(View());
        }
Ejemplo n.º 3
0
        //Retreive msg from db
        public List <string> ChatGetMessage()
        {
            //Set connection string
            String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ConnectionString;

            conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
            try
            {
                //Storing list
                List <string> chatList     = new List <string>();
                List <string> decodedList  = new List <string>();
                List <string> censoredList = new List <string>();
                //Open connection
                conn.Open();
                MySqlCommand   cmd           = new MySqlCommand(queryString, conn);
                AESCryptoStuff aes_obj       = AESCryptoStuff.CurrentInstance;
                Censors        censorMessage = new Censors();
                //QueryString set
                queryString     = "SELECT * FROM dububase.chat";
                cmd.CommandText = queryString;
                cmd             = new MySql.Data.MySqlClient.MySqlCommand(queryString, conn);
                reader          = cmd.ExecuteReader();
                while (reader.HasRows && reader.Read())
                {
                    //While rows are present read and add each row from chatmessage column to chatList
                    chatList.Add(aes_obj.AesDecrypt(reader["chatMessage"].ToString()));
                }
                //Loop through list and decode
                foreach (string i in chatList)
                {
                    decodedList.Add(encInit.DecodeStuff(i));
                }
                foreach (string b in decodedList)
                {
                    censoredList.Add(censorMessage.CrapCensor(b));
                }
                return(censoredList);
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string errorMsg = "Error";
                errorMsg += ex.Message;
                throw new Exception(errorMsg);
            }
            finally
            {
                reader.Close();
                conn.Close();
            }
        }
Ejemplo n.º 4
0
        public ActionResult UserProfile(string username)
        {
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }

            if (Session["role"].ToString() != "Admin")
            {
                return(RedirectToAction("Index", "Unauthorised"));
            }
            Database            d      = Database.CurrentInstance;
            List <DummyProfile> Dummys = new List <DummyProfile>();

            try
            {
                if (d.OpenConnection())
                {
                    string SearchQuery = "SELECT * FROM dububase.users Where username = @username;";

                    MySqlCommand c = new MySqlCommand(SearchQuery, d.conn);
                    c.Parameters.AddWithValue("@username", username);
                    AESCryptoStuff AES   = AESCryptoStuff.CurrentInstance;
                    user           users = new user();
                    using (MySqlDataReader r = c.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            user user = new user
                            {
                                userName = (r["userName"].ToString()),
                                email    = (r["email"]).ToString(),
                                role     = (r["role"].ToString())
                            };
                            ViewBag.Dummy = user;
                        }
                    }
                }
            }
            catch (MySqlException e)
            {
                Debug.WriteLine("MySQL Error!");
            }
            finally
            {
                d.CloseConnection();
            }
            return(View());
        }
Ejemplo n.º 5
0
        public ActionResult RoleChange(ChangeRoleModel model)
        {
            #region role and is logged in
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }

            if (Session["role"].ToString() != "Admin")
            {
                return(RedirectToAction("Index", "Unauthorised"));
            }


            #endregion

            Database d = Database.CurrentInstance;

            AESCryptoStuff aes_obj = AESCryptoStuff.CurrentInstance;
            try
            {
                if (d.OpenConnection())
                {
                    string       queryString = "UPDATE dububase.users SET role = @role Where username=@username;";
                    MySqlCommand cmd         = new MySqlCommand(queryString, d.conn);
                    cmd.CommandText = queryString;
                    cmd.Parameters.AddWithValue("@role", model.NewRole);
                    cmd.Parameters.AddWithValue("@username", model.Username);
                    cmd.ExecuteNonQuery();
                    return(RedirectToAction("UserProfile", "Admin", new { username = model.Username }));
                }
            }catch (System.Data.SqlClient.SqlException ex)
            {
                string errorMsg = "Error";
                errorMsg += ex.Message;
                throw new Exception(errorMsg);
            }
            finally
            {
                d.CloseConnection();
            }

            //change to somewhere
            return(View());
        }
Ejemplo n.º 6
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }

            var    response  = Request["g-recaptcha-response"];
            string secretKey = "6LenbkIUAAAAAJGZh-mw37g7pIC-vLXNXAbxnsXd";
            var    client    = new WebClient();
            var    result    = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
            var    obj       = JObject.Parse(result);
            var    status    = (bool)obj.SelectToken("success");

            ViewBag.Message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";

            if (status == true)
            {
                Database       d   = Database.CurrentInstance;
                AESCryptoStuff AES = AESCryptoStuff.CurrentInstance;
                try
                {
                    if (d.OpenConnection())
                    {
                        var    username    = Session["uName"];
                        string SearchQuery = "SELECT * FROM dububase.users Where @username";


                        MySqlCommand c = new MySqlCommand(SearchQuery, d.conn);
                        c.Parameters.AddWithValue("@username", username);
                        string password = "";
                        using (MySqlDataReader r = c.ExecuteReader())
                        {
                            while (r.Read())
                            {
                                password = AES.AesDecrypt(r["password"].ToString());
                            }
                        }
                        var OldPassword = Crypto.Hash(model.OldPassword);
                        var NewPassword = Crypto.Hash(model.NewPassword);
                        if (OldPassword == password)
                        {
                            string query = "Update dububase.users set password = @newPassword where username =@username;";
                            c = new MySqlCommand(query, d.conn);
                            c.Parameters.AddWithValue("@newPassword", AES.AesEncrypt(NewPassword));
                            c.Parameters.AddWithValue("@username", username);
                            c.BeginExecuteNonQuery();
                            return(RedirectToAction("UserProfile", "Profile"));
                        }
                        else
                        {
                            ViewBag.Message = "Wrong Password";
                            return(View());
                        };
                    }
                }
                catch (MySqlException e)
                {
                    Debug.WriteLine("MySQL Error!");
                }
                finally
                {
                    d.CloseConnection();
                }
            }
            return(View());
        }
Ejemplo n.º 7
0
        public ActionResult TransactionHistory()
        {
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }
            var Username = Session["uname"];

            //if(Session["u"].ToString() != Username)
            //{
            //    return RedirectToAction("TransactionHistory", "Profile", new { Username = Username });
            //}

            Database d = Database.CurrentInstance;

            try
            {
                if (d.OpenConnection())
                {
                    string SearchQuery = "SELECT * FROM dububase.beantransaction Where userID = @userID Order by dateOfTransaction Desc";
                    //string SearchQuery = "Select userID From dububase.users where username = @username;";
                    MySqlCommand c = new MySqlCommand(SearchQuery, d.conn);
                    //c.Parameters.AddWithValue("@username", Username);
                    //int userID = 0;
                    //using (MySqlDataReader r = c.ExecuteReader())
                    //{
                    //    while (r.Read())
                    //    {
                    //        userID = Convert.ToInt32(r["userID"].ToString());
                    //    }
                    //}
                    var uid = Session["userID"].ToString();

                    c = new MySqlCommand(SearchQuery, d.conn);
                    AESCryptoStuff AES = AESCryptoStuff.CurrentInstance;
                    c.Parameters.AddWithValue("@userID", AES.AesEncrypt(uid.ToString()));
                    List <TransactionHistory> transactions = new List <TransactionHistory>();

                    using (MySqlDataReader r = c.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            transactions.Add(new TransactionHistory
                            {
                                TransactionNo     = AES.AesDecrypt(r["transactionNo"].ToString()),
                                TransactionDesc   = AES.AesDecrypt(r["transactionDesc"].ToString()),
                                Price             = Convert.ToDouble(r["priceOfBeans"]),
                                Status            = r["status"].ToString(),
                                BeansBefore       = Convert.ToInt32(r["userBeansBefore"]),
                                BeansAfter        = Convert.ToInt32(r["userBeansAfter"]),
                                DateOfTransaction = (Convert.ToDateTime(r["dateOfTransaction"])).ToString(),
                                UserID            = AES.AesDecrypt(r["UserID"].ToString())
                            });
                        }
                    }
                    ViewBag.Transactions = transactions;
                    return(View());
                }
            }
            catch (MySqlException e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                d.CloseConnection();
            }
            return(View());
        }
Ejemplo n.º 8
0
        public ActionResult BanUser(BanUserModel model)
        {
            #region role and is logged in
            if (Session["uname"] == null || Session["uname"].ToString() == "")
            {
                return(RedirectToAction("Login", "User"));
            }
            if (Session["role"].ToString() != "Admin")
            {
                return(RedirectToAction("Index", "Unauthorised"));
            }


            #endregion
            string username = model.Username;
            //db stuff
            Database       d       = Database.CurrentInstance;
            AESCryptoStuff aes_obj = AESCryptoStuff.CurrentInstance;
            //EncodeDecode encInit = new EncodeDecode();

            try
            {
                if (d.OpenConnection())
                {
                    string queryString = "UPDATE dububase.users SET isBan = 'true', banTill=@date Where username=@username;";

                    List <user> users = new List <user>();



                    MySqlCommand cmd = new MySqlCommand(queryString, d.conn);

                    String BanPeriod = model.BanPeriod;
                    int    time      = 0;
                    if (BanPeriod == "1 Week")
                    {
                        time = 7;
                    }
                    else if (BanPeriod == "2 Weeks")
                    {
                        time = 14;
                    }
                    else if (BanPeriod == "1 Month")
                    {
                        time = 30;
                    }
                    else if (BanPeriod == "3 Months")
                    {
                        time = 90;
                    }
                    else if (BanPeriod == "1 Year")
                    {
                        time = 365;
                    }
                    DateTime mehgofu = DateTime.Now.AddDays(time);
                    cmd.Parameters.AddWithValue("@date", mehgofu);
                    cmd.Parameters.AddWithValue("@username", model.Username);
                    cmd.ExecuteNonQuery();

                    //add ban table into sql
                    queryString = "INSERT INTO dububase.banhistory(username, banReason,banPeriod) VALUES(@username, @banReason,@banPeriod); ";
                    cmd         = new MySqlCommand(queryString, d.conn);
                    cmd.Parameters.AddWithValue("@username", model.Username);
                    cmd.Parameters.AddWithValue("@banReason", model.BanReason);
                    cmd.Parameters.AddWithValue("@banPeriod", model.BanPeriod);
                    cmd.ExecuteNonQuery();

                    return(RedirectToAction("UserProfile", "Admin", new { username = model.Username }));
                }
            }
            catch (MySqlException e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                d.CloseConnection();
            }
            return(RedirectToAction("UserProfile", "Admin", new { username = model.Username }));
        }
Ejemplo n.º 9
0
        public ActionResult PaymentWithPaypal(Models.CreditCard currentCard)
        {
            Database       d      = Database.CurrentInstance;
            AESCryptoStuff AES    = AESCryptoStuff.CurrentInstance;
            int            userID = Convert.ToInt32(Session["UserID"]);
            string         price  = string.Empty;

            price = Convert.ToString(Session["price"]);
            string beansName = string.Empty;

            beansName = Convert.ToString(Session["beansName"]);
            string beansAmount = string.Empty;

            beansAmount = Convert.ToString(Session["beansAmount"]);

            //getting the apiContext as earlier
            APIContext apiContext = Models.Configuration.GetAPIContext();

            //generating sessionID
            Session["ShopSessionID1"] = KeyGenerator.GetUniqueKey(20);

            string sessionID1 = Session["ShopSessionID1"].ToString();

            Session["ShopSessionID2"] = BCrypt.HashSession(sessionID1, BCrypt.GenerateSalt());

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist
                    //it is returned by the create function call of the payment class

                    // Creating a payment
                    // baseURL is the url on which paypal sendsback the data.
                    // So we have provided URL of this controller only
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
                                     "/Shop/PaymentWithPayPal?";

                    //guid we are generating for storing the paymentID received in session
                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    //CreatePayment function gives us the payment approval url
                    //on which payer is redirected for paypal account payment

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        string       addItemTransQuery = "INSERT INTO beantransaction(transactionNo, transactionDesc, priceOfBeans, status, dateOfTransaction, userID) VALUES (@transactionNo, @transactionDesc, @price, @status, @dateOfTransaction, @userID)";
                        string       transDesc         = "Failed Purchase of " + beansName + " (" + beansAmount + " Beans) for $" + price;
                        MySqlCommand c3 = new MySqlCommand(addItemTransQuery, d.conn);

                        c3.Parameters.AddWithValue("@transactionNo", AES.AesEncrypt(KeyGenerator.GetUniqueKey(20)));
                        c3.Parameters.AddWithValue("@transactionDesc", AES.AesEncrypt(transDesc));
                        c3.Parameters.AddWithValue("@price", Convert.ToDouble(price));
                        c3.Parameters.AddWithValue("@status", "Failure");
                        c3.Parameters.AddWithValue("@dateOfTransaction", DateTime.Now);
                        c3.Parameters.AddWithValue("@userID", AES.AesEncrypt(userID.ToString()));
                        return(RedirectToAction("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                string       addItemTransQuery = "INSERT INTO beantransaction(transactionNo, transactionDesc, priceOfBeans, status, dateOfTransaction, userID) VALUES (@transactionNo, @transactionDesc, @price, @status, @dateOfTransaction, @userID)";
                string       transDesc         = "Failed Purchase of " + beansName + " (" + beansAmount + " Beans) for $" + price;
                MySqlCommand c3 = new MySqlCommand(addItemTransQuery, d.conn);

                c3.Parameters.AddWithValue("@transactionNo", AES.AesEncrypt(KeyGenerator.GetUniqueKey(20)));
                c3.Parameters.AddWithValue("@transactionDesc", AES.AesEncrypt(transDesc));
                c3.Parameters.AddWithValue("@price", Convert.ToDouble(price));
                c3.Parameters.AddWithValue("@status", "Failure");
                c3.Parameters.AddWithValue("@dateOfTransaction", DateTime.Now);
                c3.Parameters.AddWithValue("@userID", AES.AesEncrypt(userID.ToString()));
                return(View("FailureView"));
            }

            try
            {
                if (d.OpenConnection())
                {
                    string       userQuery = "SELECT * FROM users WHERE userID = @userID";
                    MySqlCommand c         = new MySqlCommand(userQuery, d.conn);
                    c.Parameters.AddWithValue("@userID", userID);
                    int beansBefore = 0;
                    int beansAfter  = 0;

                    Debug.WriteLine("SCARY");
                    using (MySqlDataReader r = c.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            if (Convert.ToInt32(r["userID"]) == userID)
                            {
                                beansBefore = Convert.ToInt32(r["beansAmount"].ToString());
                                beansAfter  = beansBefore + Convert.ToInt32(beansAmount);
                            }
                        }
                        r.Close();

                        string       updateQuery = "UPDATE users SET beansAmount = @beansAfter WHERE userID = @userID";
                        MySqlCommand c2          = new MySqlCommand(updateQuery, d.conn);

                        c2.Parameters.AddWithValue("@beansAfter", beansAfter);
                        c2.Parameters.AddWithValue("@userID", userID);
                        c2.ExecuteNonQuery();
                        Debug.WriteLine(beansBefore + " " + beansAfter);

                        string       addItemTransQuery = "INSERT INTO beantransaction VALUES (@transactionNo, @transactionDesc, @price, @beansBefore, @beansAfter, @status, @dateOfTransaction, @userID)";
                        string       transDesc         = "Purchase " + beansName + " (" + beansAmount + " Beans) for $" + price;
                        MySqlCommand c3 = new MySqlCommand(addItemTransQuery, d.conn);

                        c3.Parameters.AddWithValue("@transactionNo", AES.AesEncrypt(KeyGenerator.GetUniqueKey(20)));
                        c3.Parameters.AddWithValue("@transactionDesc", AES.AesEncrypt(transDesc));
                        c3.Parameters.AddWithValue("@price", Convert.ToDouble(price));
                        c3.Parameters.AddWithValue("@beansBefore", beansBefore);
                        c3.Parameters.AddWithValue("@beansAfter", beansAfter);
                        c3.Parameters.AddWithValue("@status", "Successful");
                        c3.Parameters.AddWithValue("@dateOfTransaction", DateTime.Now);
                        c3.Parameters.AddWithValue("@userID", AES.AesEncrypt(userID.ToString()));

                        c3.ExecuteNonQuery();
                    }
                }
            }
            catch (MySqlException e)
            {
                Debug.WriteLine(e);

                string       addItemTransQuery = "INSERT INTO beantransaction(transactionNo, transactionDesc, priceOfBeans, status, dateOfTransaction, userID) VALUES (@transactionNo, @transactionDesc, @price, @status, @dateOfTransaction, @userID)";
                string       transDesc         = "Failed Purchase of " + beansName + " (" + beansAmount + " Beans) for $" + price;
                MySqlCommand c3 = new MySqlCommand(addItemTransQuery, d.conn);

                c3.Parameters.AddWithValue("@transactionNo", AES.AesEncrypt(KeyGenerator.GetUniqueKey(20)));
                c3.Parameters.AddWithValue("@transactionDesc", AES.AesEncrypt(transDesc));
                c3.Parameters.AddWithValue("@price", Convert.ToDouble(price));
                c3.Parameters.AddWithValue("@status", "Failure");
                c3.Parameters.AddWithValue("@dateOfTransaction", DateTime.Now);
                c3.Parameters.AddWithValue("@userID", AES.AesEncrypt(userID.ToString()));

                return(RedirectToAction("FailureView"));
            }
            finally
            {
                d.CloseConnection();
            }
            return(RedirectToAction("SuccessView"));
        }
Ejemplo n.º 10
0
        public ActionResult ItemPurchase(string beansPrice, string premiumItemName, string premiumItemID)
        {
            Database d      = Database.CurrentInstance;
            int      userID = Convert.ToInt32(Session["UserID"]);
            int      itemID = Convert.ToInt32(premiumItemID);

            try
            {
                if (d.OpenConnection())
                {
                    string       userQuery = "SELECT * FROM users WHERE userID = @userID";
                    MySqlCommand c         = new MySqlCommand(userQuery, d.conn);
                    c.Parameters.AddWithValue("@userID", userID);
                    int  beansBefore        = 0;
                    int  beansAfter         = 0;
                    bool successfulPurchase = false;

                    using (MySqlDataReader r = c.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            if (Convert.ToInt32(r["userID"]) == userID)
                            {
                                beansBefore = Convert.ToInt32(r["beansAmount"].ToString());
                                beansAfter  = beansBefore - Convert.ToInt32(beansPrice);
                                if (beansAfter < 0)
                                {
                                    successfulPurchase = false;
                                }

                                else if (beansAfter > 0)
                                {
                                    successfulPurchase = true;
                                }
                            }
                        }
                        r.Close();

                        if (successfulPurchase == true)
                        {
                            AESCryptoStuff AES         = AESCryptoStuff.CurrentInstance;
                            string         updateQuery = "UPDATE users SET beansAmount = @beansAfter WHERE userID = @userID";
                            MySqlCommand   c2          = new MySqlCommand(updateQuery, d.conn);
                            c2.Parameters.AddWithValue("@beansAfter", beansAfter);
                            c2.Parameters.AddWithValue("@userID", userID);
                            c2.ExecuteNonQuery();

                            string       addItemTransQuery = "INSERT INTO itemtransaction VALUES (@transactionNo, @transactionDesc, @price, @beansBefore, @beansAfter, @userID, @dateOfTransaction)";
                            string       transDesc         = "Purchase of " + premiumItemName + " for " + beansPrice + " beans.";
                            MySqlCommand c3 = new MySqlCommand(addItemTransQuery, d.conn);
                            c3.Parameters.AddWithValue("@transactionNo", AES.AesEncrypt(KeyGenerator.GetUniqueKey(20)));
                            c3.Parameters.AddWithValue("@transactionDesc", AES.AesEncrypt(transDesc));
                            c3.Parameters.AddWithValue("@price", beansPrice);
                            c3.Parameters.AddWithValue("@beansBefore", beansBefore);
                            c3.Parameters.AddWithValue("@beansAfter", beansAfter);
                            c3.Parameters.AddWithValue("@userID", AES.AesEncrypt(userID.ToString()));
                            c3.Parameters.AddWithValue("@dateOfTransaction", DateTime.Now);

                            c3.ExecuteNonQuery();

                            string       addInventoryQuery = "INSERT INTO inventory VALUES (@userID, @itemID)";
                            MySqlCommand c4 = new MySqlCommand(addInventoryQuery, d.conn);
                            c4.Parameters.AddWithValue("@userID", userID);
                            c4.Parameters.AddWithValue("@itemID", itemID);
                            c4.ExecuteNonQuery();
                        }

                        else
                        {
                            return(RedirectToAction("FailureView"));
                        }
                    }
                }
            }

            catch (MySqlException e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                d.CloseConnection();
            }

            return(RedirectToAction("Shop"));
        }