public string UpdateQTY()
        {
            using (ProductsEntities database = new ProductsEntities())
            {
                // Updates the QTY of product in cart from the "cart" session variable.
                // Occurs on page load.

                // Get the POSTED value of the product ID.
                var id = Convert.ToInt32(Request["qtyID"]);

                // Find the matching product.
                Product product = database.Products.Find(id);

                // Check if the Cart exists.
                if (Session["cart"] != null)
                {
                    // Check if the cart contains the requested product.
                    if (((Dictionary <Product, int>)Session["cart"]).ContainsKey(product))
                    {
                        // Return a string representation of the product to the view
                        // so the quantity of the product in the cart can be set.
                        return(((Dictionary <Product, int>)Session["cart"])[product].ToString());
                    }
                }

                // If there was no product found in the cart (zero quantity), return string value of zero.
                return("0");
            }
        }
Exemple #2
0
        public ActionResult LoginPost([Bind(Include = "Username, Password")]  User user)
        {
            // Open the database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // Get user that matches the username and password details.
                User login = database.Users.FirstOrDefault(u => u.Username == user.Username &&
                                                           u.Password == user.Password);

                // If there is a user that matches.
                if (login != null)
                {
                    // Set the session details for username and password.
                    Session["Username"] = login.Username;
                    Session["UserId"]   = login.UserId;

                    // If coming from the checkout page, redirect back to the checkout.
                    if (Session["checkout"] != null)
                    {
                        return(RedirectToAction("../Checkout"));
                    }

                    // If not coming from the checkout page, redirect to the shop.
                    else
                    {
                        return(RedirectToAction("../Shop"));
                    }
                }
            }

            return(View(user));
        }
Exemple #3
0
 public async Task <HttpResponseMessage> GetAllProducts()
 {
     using (var products = new ProductsEntities())
     {
         return(Request.CreateResponse(HttpStatusCode.OK, await products.Products.ToListAsync()));
     }
 }
        public string AddToCart()
        {
            using (ProductsEntities database = new ProductsEntities())
            {
                // Get ID of product from Ajax POST.
                var id = Convert.ToInt32(Request["id"]);

                // Plus or minus button will aways be a 1, set quantity to reflect this.
                var quantity = 1;

                // Find the product in the database and assign it to the product variable.
                Product product = database.Products.Find(id);

                // Check if Cart exists.
                if (Session["cart"] == null)
                {
                    // Cart does not exist - Instantiate the Cart.
                    Session["cart"] = new Dictionary <Product, int>();
                }

                // Check whether Product is already in the Cart.
                if (((Dictionary <Product, int>)Session["cart"]).ContainsKey(product))
                {
                    // Product is already in Cart - Increase the Quantity.
                    ((Dictionary <Product, int>)Session["cart"])[product] += quantity;
                }
                else
                {
                    // Add Product to the Cart.
                    ((Dictionary <Product, int>)Session["cart"]).Add(product, quantity);
                }

                return(((Dictionary <Product, int>)Session["cart"])[product].ToString());
            }
        }
Exemple #5
0
        public int GetCurrentAvailability(int?cur_order)
        {
            ProductsEntities entities = new ProductsEntities();
            var cur_Availability      = (from p in entities.Products where p.ProductId == cur_order select p).FirstOrDefault();

            return((int)cur_Availability.Quantity);
        }
Exemple #6
0
        public string UpdateOrder(Order _order)
        {
            string           result   = string.Empty;
            ProductsEntities entities = new ProductsEntities();
            int   availability        = GetCurrentAvailability(_order.ProductId);
            Order updatedOrder        = (from o in entities.Orders
                                         where o.ProductId == _order.ProductId
                                         select o).FirstOrDefault();

            if (availability - (_order.Quantity - updatedOrder.Quantity) >= 0)
            {
                Product updatedProduct = (from p in entities.Products
                                          where p.ProductId == _order.ProductId
                                          select p).FirstOrDefault();
                updatedProduct.Quantity = availability - (_order.Quantity - updatedOrder.Quantity);
                updatedOrder.Quantity   = _order.Quantity;
                entities.SaveChanges();
                result = "Order Updated";
            }
            else
            {
                result = "Unavailability of the product";
            }
            return(result);
        }
        //This function deletes from the shopping cart
        public static List <Product> DeleteItemFromCartList(int id)
        {
            ProductsEntities db = new ProductsEntities();

            //check if cart alreay exists
            if (HttpContext.Current.Session["Cart"] == null)
            {
                //make a new list
                List <Product> cart = new List <Product>();
                //add this product to it
                cart.Remove((from p in db.Products
                             where p.ID == id
                             select p).Single());
                //add the list to the session
                HttpContext.Current.Session.Add("Cart", cart);
                return(cart);
            }
            else
            {
                //if the cart isn't empty
                List <Product> cart = (List <Product>)(HttpContext.Current.Session["Cart"]);
                //add book to cart
                cart.Remove((from p in db.Products
                             where p.ID == id
                             select p).Single());
                return(cart);
            }
        }
Exemple #8
0
 public Product Get(int id)
 {
     using (ProductsEntities productsEntities = new ProductsEntities())
     {
         return(productsEntities.Products.FirstOrDefault(e => e.ProductID == id));
     }
 }
Exemple #9
0
 public IEnumerable <Product> Get()
 {
     using (ProductsEntities productsEntities = new ProductsEntities())
     {
         return(productsEntities.Products.ToList());
     }
 }
        // GET: Index
        public ActionResult Index(int?page)
        {
            using (ProductsEntities database = new ProductsEntities())
            {
                // Set PagedList size.
                int pageSize  = 4;
                int pageIndex = 1;

                // Default to Page 1 if no value is provided.
                pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

                // Check whether the Shopping Cart is empty or not.
                if (Session["cart"] != null && ((Dictionary <Product, int>)Session["cart"]).Count() != 0)
                {
                    // Retrieve current contents of the Cart and save to the PagedList container.
                    IPagedList <Product> cartList = null;
                    cartList = ((Dictionary <Product, int>)Session["cart"]).Keys.ToPagedList(pageIndex, pageSize);

                    // Show Shopping Cart.
                    return(View(cartList));
                }
                else
                {
                    // Show Shopping Cart Empty message.
                    return(View("Empty"));
                }
            }
        }
        //This function adds the information to a user object and adds it to the DB


        //This function puts product items into a list
        public static List <Product> GenerateProductList()
        {
            ProductsEntities db       = new ProductsEntities();
            List <Product>   products = db.Products.ToList();

            return(products);
        }
Exemple #12
0
        public async Task <HttpResponseMessage> DeleteProduct(int id)
        {
            try
            {
                using (var product = new ProductsEntities())
                {
                    var entity = await product.Products.FindAsync(id);

                    if (entity == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Product with {id} is not found on the database."));
                    }
                    else
                    {
                        product.Products.Remove(entity);
                        await product.SaveChangesAsync();

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
        //This function searches the description of product listings
        public static List <Product> SearchProductList(string term)
        {
            ProductsEntities db      = new ProductsEntities();
            List <Product>   results = (from r in db.Products
                                        where r.Description.Contains(term)
                                        select r).ToList();

            return(results);
        }
Exemple #14
0
        // Controller method for confirmation of the purchase.
        public ActionResult Summary()
        {
            // Open the database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // Retrieve UserID and OrderID.
                var intUser = Convert.ToInt32(Session["UserId"]);
                var intOrd  = Convert.ToInt32(Session["OrderId"]);

                // Retrieve Customer details from database.
                var cust = from c in database.Customers
                           where c.UserId == intUser
                           select c;

                // Retrieve Order details.
                var ord = from o in database.Orders
                          where o.OrderId == intOrd
                          select o;

                // Update Order status.
                Order order = ord.FirstOrDefault();
                try
                {
                    order.OrderStatus = "COMPLETE";
                    database.SaveChanges();
                }
                catch (System.NullReferenceException)
                {
                    return(RedirectToAction("../Shop/Index"));
                }

                // Retrieve list of Order Products.
                var prodOrd = from po in database.Order_Products
                              where po.OrderID == intOrd
                              select po;

                var modelCust    = cust.Include("User").ToList();
                var modelOrd     = ord.Include("Customer").ToList();
                var modelProdOrd = prodOrd.Include("Order").ToList();

                // Reset Session Variables for the Cart and Order.
                Session["OrderId"] = null;
                Session["cart"]    = null;

                foreach (var ct in cust)
                {
                    Debug.WriteLine(ct.Address);
                }

                ViewBag.ModelCust = modelCust;
                ViewBag.ModelOrd  = modelOrd;

                // Order Completed - Display Order Summary.
                return(View(modelProdOrd));
            }
        }
        // Default Shop page controller method.
        public ActionResult Index(string productCategory, string searchString)
        {
            // Open the database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // Create the category list for the dropdown list and send it to the view.
                var catList = new List <string>();
                var catQry  = from d in database.Categories
                              orderby d.Title
                              select d.Title;

                // Select only distinct categories, so there will only be one of each category in the list.
                catList.AddRange(catQry.Distinct());

                // Send the category list to the view.
                ViewBag.productCategory = new SelectList(catList);

                // Select all the products.
                var products = from p in database.Products
                               select p;

                // Select products that match the search string.
                if (!String.IsNullOrEmpty(searchString))
                {
                    products = products.Where(p => p.Title.Contains(searchString));
                }

                // Convert the selected category string to an int usable in the category match query.
                int intCat = 0;

                var catsToInt = from c in database.Categories
                                select c;

                // Loop through all the categories and set the integer eauivalent of the category name.
                foreach (var catToInt in catsToInt)
                {
                    if (productCategory == catToInt.Title)
                    {
                        intCat = catToInt.CategoryID;
                    }
                }


                // Select the matched category integer.
                if (intCat != 0)
                {
                    products = products.Where(x => x.CategoryID == intCat);
                }

                // Convert the query to an IEnumerable object for eager loading.
                var converted = products.Include("Category").ToList();

                return(View(converted));
            }
        }
        public string RemoveFromCart()
        {
            using (ProductsEntities database = new ProductsEntities())
            {
                // Get ID of product from ajax POST
                var id = Convert.ToInt32(Request["id"]);

                // Plus or minus button will aways be a 1, set quantity to reflect this
                var quantity = 1;

                // Find the product in the database and assign it to the product variable
                Product product = database.Products.Find(id);

                // Check if Cart exists.
                if (Session["cart"] != null)
                {
                    // Check Product is in the Cart.
                    if (((Dictionary <Product, int>)Session["cart"]).ContainsKey(product))
                    {
                        // Product is in Cart - Deduct Quantity.
                        ((Dictionary <Product, int>)Session["cart"])[product] -= quantity;

                        // If Quantity of Product is 0, Remove from Cart completely.
                        if (((Dictionary <Product, int>)Session["cart"])[product] == 0)
                        {
                            ((Dictionary <Product, int>)Session["cart"]).Remove(product);
                        }
                    }

                    // Check if Cart is now Empty.
                    if (((Dictionary <Product, int>)Session["cart"]).Count == 0)
                    {
                        // Cart is now empty after Product removal - Reset the cart.
                        Session["cart"] = null;
                    }
                }

                // If Cart is now Empty or Product is no longer in the Cart, return 0.
                if (Session["cart"] == null ||
                    ((Dictionary <Product, int>)Session["cart"]).Count == 0 ||
                    !((Dictionary <Product, int>)Session["cart"]).ContainsKey(product))
                {
                    return("0");
                }
                else
                {
                    return(((Dictionary <Product, int>)Session["cart"])[product].ToString());
                }
            }
        }
        public JsonResult UpdateQTY()
        {
            using (ProductsEntities database = new ProductsEntities())
            {
                // Updates the QTY of product in cart from the "cart" session variable.
                // Occurs on page load.
                var     quantity  = 0;
                decimal subTotal  = 0;
                decimal totalCost = 0;

                // Get the POSTED value of the product ID.
                var id = Convert.ToInt32(Request["qtyID"]);

                // Find the matching product.
                Product product = database.Products.Find(id);

                // If Cart is now Empty or Product is no longer in the Cart, return 0.
                if (Session["cart"] == null ||
                    ((Dictionary <Product, int>)Session["cart"]).Count == 0)
                {
                    quantity  = 0;
                    subTotal  = 0;
                    totalCost = 0;
                }
                else if (product != null)
                {
                    // Check if Product is currently in Cart.
                    if (((Dictionary <Product, int>)Session["cart"]).ContainsKey(product))
                    {
                        // Product is in Cart.
                        quantity  = ((Dictionary <Product, int>)Session["cart"])[product];
                        subTotal  = (product.Price) * (quantity);
                        totalCost = TotalCost();
                    }
                    else
                    {
                        // Product has been removed from Cart - Quantity and SubTotal are 0.
                        quantity = 0;
                        subTotal = 0;
                    }

                    // Calculate Total Cost of the Cart.
                    totalCost = TotalCost();
                }

                return(Json(new { prodid = id.ToString(), quantity = quantity.ToString(), subtotal = subTotal.ToString(), totalcost = totalCost.ToString() }, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #18
0
        public string DeleteOrder(Order _order)
        {
            ProductsEntities entities = new ProductsEntities();
            int     availability      = GetCurrentAvailability(_order.ProductId);
            Product updatedProduct    = (from p in entities.Products
                                         where p.ProductId == _order.ProductId
                                         select p).FirstOrDefault();
            Order updatedOrder = (from o in entities.Orders
                                  where o.ProductId == _order.ProductId
                                  select o).FirstOrDefault();

            updatedProduct.Quantity = availability + updatedOrder.Quantity;
            entities.Orders.Remove(updatedOrder);
            entities.SaveChanges();
            return("Order Removed");
        }
Exemple #19
0
        // Add a user to the database controller method.
        public ActionResult AddUser(string Username)
        {
            // Reset the session variables used in this method.
            Session["exists"] = "";
            Session["match"]  = "";

            // Open the database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // See if the requested username already exists.
                if (Request["username"] != null)
                {
                    // Convert the POST username to a string for use in Linq query.
                    var strItem = Request["username"].ToString();

                    // Find the requested username in the database.
                    var match = from user in database.Users
                                where user.Username == strItem
                                select user;

                    // Loop through the matched usernames to see if one does exist.
                    foreach (User u in match)
                    {
                        // Set the session variable for username already exists to true.
                        Session["exists"] = "true";

                        // Redirect back to the RegisterUser page.
                        return(RedirectToAction("RegisterUser"));
                    }
                }

                // If the username is available, continue.
                // Create a new user to add to the database.
                User newUser = new User();

                newUser.Username        = Request["Username"];
                newUser.Password        = Request["Password"];
                newUser.ConfirmPassword = Request["ConfirmPassword"];

                // Add the new user to the database and save the changes.
                database.Users.Add(newUser);
                database.SaveChanges();

                // Redirect to the Thank you for registering page.
                return(RedirectToAction("ThankYou"));
            }
        }
Exemple #20
0
        // GET: Index
        public ActionResult Index()
        {
            if (Session["Username"] == null)
            {
                // User is not logged in - Redirect to Login page.
                return(RedirectToAction("../Home/Login", new { checkout = true }));
            }
            else if (Session["Username"] != null)
            {
                // User is logged in.
                using (ProductsEntities database = new ProductsEntities())
                {
                    // Find the member's details in the registration (Customers database).
                    var strItem = Convert.ToInt32(Session["UserId"]);
                    var match   = from customer in database.Customers
                                  where customer.UserId.Equals(strItem)
                                  select customer;

                    // If the customer is in the 'Customers' database (Registered for postage).
                    foreach (Customer c in match)
                    {
                        if (c.UserId == strItem)
                        {
                            if (Session["cart"] != null && ((Dictionary <Product, int>)Session["cart"]).Count() > 0)
                            {
                                return(View("Index"));
                            }
                            else
                            {
                                return(View("../Cart/Empty"));
                            }
                        }
                    }

                    // Redirect to Registration page if a valid login is not found.
                    return(View("RegisterCustomer"));
                }
            }
            else if (Session["cart"] == null || ((Dictionary <Product, int>)Session["cart"]).Count() == 0)
            {
                // Shopping Cart is empty - Redirect to Cart Empty message.
                return(RedirectToAction("../Cart"));
            }

            return(View());
        }
Exemple #21
0
 public ActionResult Login(Users u)
 {
     // this action is for handle post (login)
     if (ModelState.IsValid) // this is check validity
     {
         using (ProductsEntities dc = new ProductsEntities())
         {
             var v = dc.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault();
             if (v != null)
             {
                 Session["LogedUserID"]       = v.UserID.ToString();
                 Session["LogedUserFullname"] = v.FullName.ToString();
                 return(RedirectToAction("Index", "Products"));
             }
         }
     }
     return(View(u));
 }
Exemple #22
0
        public async Task <HttpResponseMessage> AddProduct([FromBody] Product product)
        {
            try
            {
                using (var products = new ProductsEntities())
                {
                    products.Products.Add(product);
                    await products.SaveChangesAsync();

                    var message = Request.CreateResponse(HttpStatusCode.Created, product);
                    message.Headers.Location = new Uri(Request.RequestUri + product.Id.ToString());
                    return(message);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemple #23
0
        public ActionResult RegisterCustomer()
        {
            // Open the database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // If the current state of the view model is valid.
                if (ModelState.IsValid)
                {
                    // Create a new customer and assign the details from the POST data.
                    Customer customer = new Customer();

                    customer.FirstName = Request["firstname"];
                    customer.LastName  = Request["lastname"];
                    customer.Email     = Request["email"];
                    customer.Address   = Request["address"];
                    customer.Suburb    = Request["suburb"];
                    customer.State     = Request["state"];
                    customer.Postcode  = Convert.ToInt32(Request["postcode"]);
                    customer.UserId    = Convert.ToInt32(Session["UserId"]);

                    // Add the new customer details to the database and save the changes.
                    db.Customers.Add(customer);
                    db.SaveChanges();

                    // If the cart exists and has products in it return to the cart view.
                    if (Session["cart"] != null && ((Dictionary <Product, int>)Session["cart"]).Count() > 0)
                    {
                        return(View("Index"));
                    }

                    // Otherwise return to the cart is empty view.
                    else
                    {
                        return(View("../Cart/Empty"));
                    }
                }

                // If the view model state is not valid, return to the registration page.
                return(View("RegisterCustomer"));
            }
        }
Exemple #24
0
 public async Task <HttpResponseMessage> ProductDetails([FromUri] int?id)
 {
     try
     {
         if (id == null)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Product with {id} is not found on the database."));
         }
         else
         {
             using (var product = new ProductsEntities())
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, await product.Products.FirstOrDefaultAsync(products => products.Id == id)));
             }
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Exemple #25
0
        public string AddOrder(Order _order)
        {
            string           empty    = string.Empty;
            string           result   = empty;
            ProductsEntities entities = new ProductsEntities();
            int availability          = GetCurrentAvailability(_order.ProductId);

            if (availability - _order.Quantity >= 0)
            {
                Product updatedProduct = (from p in entities.Products
                                          where p.ProductId == _order.ProductId
                                          select p).FirstOrDefault();
                updatedProduct.Quantity = availability - _order.Quantity;
                entities.Orders.Add(_order);
                entities.SaveChanges();
                result = "Order placed";
            }
            else
            {
                result = "Unavailability of the product";
            }
            return(result);
        }
Exemple #26
0
        public List <Product> GetProducts()
        {
            ProductsEntities entities = new ProductsEntities();

            return(entities.Products.ToList());
        }
Exemple #27
0
        // GET: Checkout
        public ActionResult Checkout()
        {
            // Open and automatically dispose of database.
            using (ProductsEntities database = new ProductsEntities())
            {
                // Convert session object to int for use with database.
                var convertInt = Convert.ToInt32(Session["UserId"]);

                // Get the cart dictionary from the session variable.
                Dictionary <Product, int> cart = (Dictionary <Product, int>)Session["cart"];

                // If no order for the session exists.
                if (Session["OrderId"] == null)
                {
                    // Get customers that match the session UserId.
                    var cust = from c in database.Customers
                               where c.UserId == convertInt
                               select c;

                    // Create a new Order for adding to the database.
                    Order order = new Order();

                    // Get the customer found in the above linq query.
                    Customer customer = cust.FirstOrDefault();

                    // Assign the order details.
                    order.CustId      = customer.CustId;
                    order.OrderDate   = DateTime.Now;
                    order.OrderStatus = "OPEN";

                    // Add the order to the database and save.
                    database.Orders.Add(order);
                    database.SaveChanges();



                    // Loop through the cart.
                    foreach (KeyValuePair <Product, int> entry in cart)
                    {
                        // Order the products, recording OrderId, ProductId, quantity and current price.
                        Order_Products ordProd = new Order_Products();
                        ordProd.OrderID   = order.OrderId;
                        ordProd.ProductID = entry.Key.ProductID;
                        ordProd.Quantity  = entry.Value;
                        ordProd.Price     = entry.Key.Price;

                        // Add the product orders to the database and save the changes.
                        database.Order_Products.Add(ordProd);
                        database.SaveChanges();
                    }

                    // Set the session variable OrderId to indicate the order has been created and products added.
                    Session["OrderId"] = order.OrderId;
                }

                // If the order already exists.
                else
                {
                    // Convert the session order id to an int for use with the database.
                    var convertIntOrder = Convert.ToInt32(Session["OrderId"]);

                    // Find all the product orders for the session Order ID.
                    var orderProd = from o in database.Order_Products
                                    where o.OrderID == convertIntOrder
                                    select o;

                    // Remove the product orders from the database.
                    foreach (var op in orderProd)
                    {
                        database.Order_Products.Remove(op);
                    }


                    // Re-add the product orders from the cart to the database to reflect any new changes.
                    // Loop through the cart.
                    foreach (KeyValuePair <Product, int> entry in cart)
                    {
                        // Order the products, recording OrderId, ProductId, quantity and current price.
                        Order_Products ordProd = new Order_Products();
                        ordProd.OrderID   = convertIntOrder;
                        ordProd.ProductID = entry.Key.ProductID;
                        ordProd.Quantity  = entry.Value;
                        ordProd.Price     = entry.Key.Price;

                        // Add the product orders to the database.
                        database.Order_Products.Add(ordProd);
                    }

                    // Save the database changes.
                    database.SaveChanges();
                }

                return(View());
            }
        }
Exemple #28
0
 public Repository()
 {
     this.db = new ProductsEntities();
     this.db.Database.CommandTimeout = 216000;//Set command time out to 60 min.
     table = db.Set <TEntity>();
 }
Exemple #29
0
 public Repository(ProductsEntities db)
 {
     this.db = db;
     table   = db.Set <TEntity>();
 }