public ActionResult New(string name)
        {
            // Check for null input
            //
            if (name == null || name == "")
            {
                AddErrorMessage(TempData, "Can't have an empty measure!");
                return(RedirectToAction("Index", "Home"));
            }

            //
            // User is logged in
            //

            // Check if measure exists
            //
            if (DbContext.Measures.Where(c => c.Name.ToLower() == name.ToLower()).FirstOrDefault() != null)
            {
                AddErrorMessage(TempData, "The measure you tried to add already exists!");
                return(RedirectToAction("Index", "Home"));
            }

            // Attempt to create new measure
            //
            Measure newMeasure = new Measure()
            {
                Name = name
            };

            // If model not valid
            //
            if (TryValidateModel(newMeasure) == false)
            {
                AddErrorMessage(TempData, "Make sure the measure name is between 3 and 25 characters long.", "Invalid Data!");
                return(RedirectToAction("Index", "Home"));
            }

            // Model is valid
            // Attempt to save it to the database
            //
            try
            {
                DbContext.Measures.Add(newMeasure);
                DbContext.SaveChanges();

                // Saved successfully
                //
                AddOkMessage(TempData, "You have successfully added a new measure!");
            }
            catch
            {
                AddErrorMessage(TempData, "An error was encountered while saving the new measure to the database!");
            }

            return(RedirectToAction("Index", "Home"));
        }
Example #2
0
        public ActionResult New(string name, string description, int category, int measure)
        {
            bool HasError = false;
            Item newItem  = null;

            // Check for null name
            //
            if (name == "" || name == null || name.Length > 25)
            {
                AddErrorMessage(TempData, "Please make sure that the name is not empty or longer than 25 characters!");
                HasError = true;
            }

            // Check for null category/measure
            //
            if (category == 0 || measure == 0)
            {
                AddErrorMessage(TempData, "Please specify the category and measure before submitting!");
                HasError = true;
            }

            // Check if item exists
            //
            Models.Item oldItem = DbContext.Items.Where(i => i.Name == name).FirstOrDefault();
            if (oldItem != null &&
                oldItem.Name == name &&
                oldItem.CategoryID == category &&
                oldItem.MeasureID == measure &&
                oldItem.Description == description)
            {
                AddErrorMessage(TempData, "The item you're trying to add already exists!");
                HasError = true;
            }

            // If no error has been encountered so far
            // Attempt to create model and validate
            //
            if (!HasError)
            {
                // Create new model
                //
                newItem = new Item()
                {
                    Name        = name,
                    Description = description,
                    Bought      = 0,
                    CategoryID  = category,
                    MeasureID   = measure
                };

                // Try to validate model
                // if it fails return to form with errors
                //
                if (TryValidateModel(newItem) == false)
                {
                    AddErrorMessage(TempData, "Your entry is not valid!");
                    HasError = true;
                }
            }

            // If still no error
            // Attempt to save to database
            //
            if (!HasError)
            {
                try
                {
                    DbContext.Items.Add(newItem);
                    DbContext.SaveChanges();

                    // Saved successfully
                    //
                    AddOkMessage(TempData, "The new item was saved successfully!");
                }
                catch (DbUpdateException ex)
                {
                    AddErrorMessage(TempData, "An error was encountered while trying to add the new item.");
                    AddErrorMessage(TempData, ex.ToString(), "DEBUG DbContext Exception");
                    HasError = true;
                }
            }

            // If there was an error
            // Load all categories and measures
            // pass them to ViewData and redirect to New
            //
            if (HasError)
            {
                ViewData["Categories"] = DbContext.Categories.ToList();
                ViewData["Measures"]   = DbContext.Measures.ToList();
                return(View());
            }

            // If no error was encountered
            // return to 'browse' section
            //
            return(RedirectToAction("Browse", "Item"));
        }
Example #3
0
        public IActionResult NewPurchase(int userId, int groupId, int itemId, int currency, string quantity, string price, string date, string provider)
        {
            // Check for null input
            if (quantity == "" || price == "" || date == "")
            {
                AddErrorMessage(TempData, "Invalid input!");
                return(RedirectToAction("Browse", "Item"));
            }

            // Check for existing user, group, item

            var user  = DbContext.Users.Find(userId);
            var item  = DbContext.Items.Find(itemId);
            var group = DbContext.Groups.Find(groupId);

            if (user == null || item == null || group == null || group.UserID != userId)
            {
                AddErrorMessage(TempData, "Invalied user or item data!");
                return(RedirectToAction("Browse", "Item"));
            }

            // Convert date

            IFormatProvider culture = new System.Globalization.CultureInfo("bg-BG", true);
            DateTime        dateR   = DateTime.Parse(date, culture);

            // Convert strings to be ready to turn into type decimal

            if (quantity.Contains("."))
            {
                quantity = quantity.Replace(".", ",");
            }
            if (price.Contains("."))
            {
                price = price.Replace(".", ",");
            }

            // Convert to decimal

            decimal quantityR = Decimal.Parse(quantity, culture);
            decimal priceR    = Decimal.Parse(price, culture);

            // Attempt to create new purchase model

            Purchase newPurchase = new Purchase()
            {
                UserID     = userId,
                GroupID    = groupId,
                ItemID     = itemId,
                CurrencyID = currency,
                Date       = dateR,
                Price      = priceR,
                Quantity   = quantityR,
                Provider   = provider
            };

            // Attempt to validate new model

            if (TryValidateModel(newPurchase) == false)
            {
                AddErrorMessage(TempData, "Something went wrong! Please try again!");
                return(RedirectToAction("New", "Purchase"));
            }

            // Attempt to create new DB record

            try
            {
                DbContext.Purchases.Add(newPurchase);
                DbContext.SaveChanges();

                // Added successfully
                // Increase numbers of bough of item

                DbContext.Items.Find(itemId).Bought += 1;
                DbContext.SaveChanges();

                AddOkMessage(TempData, "Purchase successfully added!");
                return(RedirectToAction("Browse", "Item"));
            }
            catch (Exception ex)
            {
                AddErrorMessage(TempData, ex.ToString());
                AddErrorMessage(TempData, "An error occurred!");
                return(RedirectToAction("Index", "Home"));
            }
        }
        public ActionResult New(int userId, int item, int group, string quantity, string price, int currency, string date, string provider)
        {
            // Convert date
            IFormatProvider culture = new System.Globalization.CultureInfo("bg-BG", true);
            DateTime        dateR   = DateTime.Parse(date, culture);

            // Convert strings to be ready to turn into type decimal
            if (quantity.Contains("."))
            {
                quantity = quantity.Replace(".", ",");
            }
            if (price.Contains("."))
            {
                price = price.Replace(".", ",");
            }

            // Convert to decimal
            decimal quantityR = Decimal.Parse(quantity, culture);
            decimal priceR    = Decimal.Parse(price, culture);

            // Check if item valid
            var checkItem = DbContext.Items.Find(item);

            if (checkItem == null)
            {
                AddErrorMessage(TempData, "Search your item, add it to your purchase and try again!");
                return(RedirectToAction("New"));
            }

            // Check if group is valid
            if (DbContext.Groups.Find(group) == null || DbContext.Groups.Find(group).UserID != userId)
            {
                AddErrorMessage(TempData, "Check the group you have selected and try again!");
                return(RedirectToAction("New"));
            }

            // Check if currency is valid
            if (DbContext.Currencies.Find(currency) == null)
            {
                AddErrorMessage(TempData, "Check the currency you picked!");
                return(RedirectToAction("New"));
            }

            //
            // Everything seems okay
            //

            // Attempt to create new purchase model
            // and validate
            //
            Purchase newPurchase = new Purchase()
            {
                UserID     = userId,
                GroupID    = group,
                ItemID     = item,
                CurrencyID = currency,
                Date       = dateR,
                Price      = priceR,
                Quantity   = quantityR,
                Provider   = provider
            };

            if (TryValidateModel(newPurchase) == false)
            {
                AddErrorMessage(TempData, "Something went wrong! Please try again!");
                return(RedirectToAction("New"));
            }

            // Attempt to create new DB record
            //
            try
            {
                DbContext.Purchases.Add(newPurchase);
                DbContext.SaveChanges();

                // Added successfully
                // Increase numbers of bough of item
                DbContext.Items.Find(item).Bought += 1;
                DbContext.SaveChanges();

                AddOkMessage(TempData, "Purchase successfully added!");
                return(RedirectToAction("New"));
            }
            catch (Exception ex)
            {
                AddErrorMessage(TempData, ex.ToString());
                AddErrorMessage(TempData, "An error occurred!");
                return(RedirectToAction("Index", "Home"));
            }
        }
        public IActionResult New(string name, int prefcurr)
        {
            // If the group exists for this user then return error
            //
            Security.Authorization DbRetriever = new Security.Authorization(DbContext, HttpContext);
            Models.User            currUser    = DbRetriever.GetUserFrom(HttpContext);

            // If the UserID in session doesn't reflects an actual user
            // Redirect to the sign up page
            //
            if (currUser == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            // If a group with the same name, bound to this user exists
            // Redirect to user's home page with errors set
            //
            if (currUser.Groups.Where(g => g.Name == name).FirstOrDefault() != null)
            {
                AddErrorMessage(TempData, "A group with the same name already exists");
                return(RedirectToAction("Home", "Account"));
            }

            // Make new group model with the given name
            //
            Models.Group newGroup = new Models.Group()
            {
                Name       = name,
                UserID     = currUser.UserID,
                PrefCurrID = prefcurr
            };

            // Try to validate new model
            // If it fails redirect to user home page passing the newGroup model to display errors
            //
            if (TryValidateModel(newGroup) == false)
            {
                AddErrorMessage(TempData, "Model is not valid");
                return(RedirectToAction("Home", "Account"));
            }

            // Try to make new database record
            //
            try
            {
                DbContext.Groups.Add(newGroup);
                DbContext.SaveChanges();

                // If everything is okay go to user's home page
                //
                AddOkMessage(TempData, "New group created successfully!");
            }
            catch
            {
                // If it fails to add new record to db
                // Redirect to users home page
                //
                AddErrorMessage(TempData, "Error while creating your group!");
            }

            return(RedirectToAction("Home", "Account"));
        }
Example #6
0
        public ActionResult New(string username, string password)
        {
            // If the user is already authenticated no need to show the sign up page
            //
            if (IsLogged(HttpContext))
            {
                return(RedirectToAction("Index", "Home"));
            }

            //
            // User is not logged in
            //

            // Check if username already exists
            //
            if (DbContext.Users.Where(u => u.Username == username).FirstOrDefault() != null)
            {
                AddErrorMessage(TempData, "This username already exists!");
                return(View()); // Username exists
            }

            //
            // Username does note exist in the database
            //

            // Make new model for the new user
            // Pass the username and password provided by the user
            //
            Models.User newUser = new Models.User()
            {
                Username = username,
                Password = password
            };

            // Try to validate the new model
            //
            if (TryValidateModel(newUser) == false)
            {
                return(View(newUser));
            }                                                                 // Model not valid

            //
            // Model is valid
            //

            // Secure the password through hashing
            //
            newUser.SecurePassword();

            // Try to make new database record from new model
            //
            try
            {
                DbContext.Users.Add(newUser);
                DbContext.SaveChanges();

                //
                // New record added successfully
                //

                // Add the default Group to the new User
                //
                Models.Group defGroup = new Models.Group()
                {
                    Name = "MyGroup"
                };
                defGroup.UserID = DbContext.Users.Last().UserID;
                DbContext.Groups.Add(defGroup);
                DbContext.SaveChanges();

                // Set a welcoming/helping message
                //
                AddOkMessage(TempData, "You successfully signed up for the best expenses tracker! You can now login and start tracking!", "Welcome to ShopTracker!");

                // Redirect to the login page
                //
                return(RedirectToAction("Login"));
            }
            catch (Exception ex)
            {
                // Something went wrong
                // Redirect user to a new sign up form
                //
                AddErrorMessage(TempData, ex.ToString());
                AddErrorMessage(TempData, "Error while making a new record!");
                return(RedirectToAction("New"));
            }
        }
        public ActionResult New(string name, string fullName)
        {
            // If user not logged in redirect to the home page
            //
            if (!IsLogged(HttpContext, "You must be logged in to do this!", TempData))
            {
                return(RedirectToAction("Login", "Account"));
            }

            // Check for null input
            //
            if (name == null || name == "" || fullName == null || fullName == "")
            {
                AddErrorMessage(TempData, "Can't have an empty currency!");
                return(RedirectToAction("Index", "Home"));
            }

            //
            // User is logged in
            //

            // Format currency name
            //
            name.ToUpper();
            fullName = char.ToUpper(fullName[0]) + fullName.Substring(1);

            // Check if currency exists
            //
            if (DbContext.Currencies.Where(c => c.Name == name).FirstOrDefault() != null)
            {
                AddErrorMessage(TempData, "The currency you tried to add already exists!");
                return(RedirectToAction("Index", "Home"));
            }

            // Attempt to create new currency
            //
            Currency newCurrency = new Currency()
            {
                Name     = name,
                FullName = fullName
            };

            // If model not valid
            //
            if (TryValidateModel(newCurrency) == false)
            {
                AddErrorMessage(TempData, "Make sure the currency name is 3 characters long and the full name doesn't exceed 20 characters.");
                return(RedirectToAction("Index", "Home"));
            }

            // Model is valid
            // Attempt to save it to the database
            //
            try
            {
                DbContext.Currencies.Add(newCurrency);
                DbContext.SaveChanges();

                // Saved successfully
                //
                AddOkMessage(TempData, "You have successfully added a new currency!");
            }
            catch
            {
                AddErrorMessage(TempData, "An error was encountered while saving the new currency to the database!");
            }

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult New(string name)
        {
            // Check for null input
            //
            if (name == null || name == "")
            {
                AddErrorMessage(TempData, "Can't have an empty category!");
                return(RedirectToAction("Index", "Home"));
            }

            //
            // User is logged in
            //

            // Format category name
            //
            name.ToLower();
            name = char.ToUpper(name[0]) + name.Substring(1);

            // Check if category exists
            //
            if (DbContext.Categories.Where(c => c.Name == name).FirstOrDefault() != null)
            {
                AddErrorMessage(TempData, "The category you tried to add already exists!");
                return(RedirectToAction("Index", "Home"));
            }

            // Attempt to create new category
            //
            Category newCategory = new Category()
            {
                Name = name
            };

            // If model not valid
            //
            if (TryValidateModel(newCategory) == false)
            {
                AddErrorMessage(TempData, "Make sure the category name is between 3 and 25 characters long.");
                return(RedirectToAction("Index", "Home"));
            }

            // Model is valid
            // Attempt to save it to the database
            //
            try
            {
                DbContext.Categories.Add(newCategory);
                DbContext.SaveChanges();

                // Saved successfully
                //
                AddOkMessage(TempData, "You have successfully added a new category!");
            }
            catch
            {
                AddErrorMessage(TempData, "An error was encountered while saving the new category!");
            }

            return(RedirectToAction("Index", "Home"));
        }