Exemple #1
0
        public void InsertProduct(Product product)
        {
            ctx.Products.Add(product);

            try
            {
                ctx.SaveChanges();
                //validate
                ctx.Configuration.ValidateOnSaveEnabled = true;
            }
            catch (DbEntityValidationException ex)
            {
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                Session["ValidationError"] = fullErrorMessage;

                Response.Redirect("ErrorPage.aspx");

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
            finally
            {
                Response.Redirect("Secure/Staff/ManageProducts.aspx");
            }
        }
        /// <summary>
        /// Behavior for checkbox isProcessed on OrderGridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cboxProcessed_CheckedChanged(object sender, EventArgs e)
        {
            //CheckBox chk = (CheckBox)sender;
            //GridViewRow gr = (GridViewRow)chk.Parent.Parent;
            ////lblmsg.Text = OrderGridView.DataKeys[gr.RowIndex].Value.ToString();

            var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex + 1;

            //Change the status or the order
            var order = (from myorder in ctx.Orders
                         where myorder.OrderId == rowIndex // get the corresponding order
                         select myorder).First();          // this will fetch the record.

            order.Processed   = DateTime.Now.ToString();
            order.IsProcessed = true;

            //Session["Error"] = rowIndex;
            //Response.Redirect("/UserPages/ErrorPage.aspx");

            try
            {
                ctx.SaveChanges();
                //validate
                ctx.Configuration.ValidateOnSaveEnabled = true;
            }

            catch (DbEntityValidationException ex)
            {
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                Session["Error"] = fullErrorMessage;

                Response.Redirect("ErrorPage.aspx");

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
            finally
            {
                Response.Redirect("/Secure/Staff/ProcessOrders.aspx");
            }
        }
Exemple #3
0
        public static void AddEntity()
        {
            //Add Entity values

            var context = new EntityMappingContext();

            IList <Address> AdrrList = new List <Address>();

            AdrrList.Add(new Address()
            {
                AddressID = 1, Street = "YoungSt", City = "Toronto"
            });
            AdrrList.Add(new Address()
            {
                AddressID = 2, Street = "ThomsonSt", City = "Newyork", PostalCode = "506000"
            });
            AdrrList.Add(new Address()
            {
                AddressID = 3, Street = "JohnsonSt", City = "Chicago", PostalCode = "390043"
            });
            AdrrList.Add(new Address()
            {
                AddressID = 4, Street = "JamesSt", City = "Newjersy"
            });

            foreach (Address adr in AdrrList)
            {
                context.Addresses.Add(adr);
            }
            context.SaveChanges();
        }
Exemple #4
0
        public static void DeleteEntity()
        {
            //Delete entity values
            var  context = new EntityMappingContext();
            User user    = context.Users.Where(p => p.UserID == 1).First();

            context.Entry <User>(user).State = System.Data.Entity.EntityState.Deleted;
            context.SaveChanges();
        }
Exemple #5
0
        public static void Add1Entity()
        {
            //Update Entity values
            var context = new EntityMappingContext();

            User usr = context.Users.Where(p => p.FirstName == "John").FirstOrDefault();

            usr.LastName = "A";

            context.SaveChanges();
        }
Exemple #6
0
        /// <summary>
        /// Behavior for remove product button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RemoveProductButton_Click(object sender, EventArgs e)
        {
            using (var ctx = new EntityMappingContext())
            {
                int productId = Convert.ToInt32(DropDownRemoveProduct.SelectedValue);
                var myItem    = (from c in ctx.Products where c.ProductID == productId select c).FirstOrDefault();
                if (myItem != null)
                {
                    ctx.Products.Remove(myItem);
                    ctx.SaveChanges();

                    // Reload the page.
                    string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                    Response.Redirect(pageUrl + "?ProductAction=remove");
                }
                else
                {
                    lblRemoveStatus.Text = "Unable to locate product.";
                }
            }
        }
Exemple #7
0
 /// <summary>
 /// Updates the cart items
 /// </summary>
 /// <param name="updateCartID"></param>
 /// <param name="updateProductID"></param>
 /// <param name="quantity"></param>
 public void UpdateItem(string updateCartID, int updateProductID, int quantity)
 {
     //startup context
     using (var ctx = new EntityMappingContext())
     {
         try
         {
             //get the item
             var myItem = (from myCartItem in ctx.CartItems where myCartItem.CartId == updateCartID && myCartItem.Product.ProductID == updateProductID select myCartItem).FirstOrDefault();
             if (myItem != null)
             {
                 //set the quantity
                 myItem.Quantity = quantity;
                 ctx.SaveChanges();
             }
         }
         catch (Exception exp)
         {
             throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp);
         }
     }
 }
Exemple #8
0
        /// <summary>
        /// Remove the item
        /// </summary>
        /// <param name="removeCartID"></param>
        /// <param name="removeProductID"></param>
        public void RemoveItem(string removeCartID, int removeProductID)
        {
            //get the database
            using (var ctx = new EntityMappingContext())
            {
                try
                {
                    //get item
                    var myItem = (from myCartItem in ctx.CartItems where myCartItem.CartId == removeCartID && myCartItem.Product.ProductID == removeProductID select myCartItem).FirstOrDefault();

                    if (myItem != null)
                    {
                        // Remove Item.
                        ctx.CartItems.Remove(myItem);
                        ctx.SaveChanges();
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Adds items to shoppint cart
        /// </summary>
        /// <param name="id"></param>
        public void AddToCart(int id)
        {
            ProductID = id;

            //HttpContext.Current.Session["Error"] = "CartSessionKey: " + ProductID;
            //HttpContext.Current.Response.Redirect("/UserPages/ErrorPage.aspx");

            // Retrieve the product from the database.
            ShoppingCartId = GetCartId();

            var cartItem = ctx.CartItems.SingleOrDefault(
                cart => cart.CartId == ShoppingCartId &&
                cart.ProductId == id);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists.
                cartItem = new CartItem
                {
                    CartItemId = Guid.NewGuid().ToString(),
                    ProductId  = id,
                    CartId     = ShoppingCartId,
                    Product    = ctx.Products.SingleOrDefault(
                        product => product.ProductID == id),
                    Quantity    = 1,
                    DateCreated = DateTime.Now
                };

                //Change the status or the order
                var pr = (from myproduct in ctx.Products
                          where myproduct.ProductID == ProductID // get the corresponding order
                          select myproduct).FirstOrDefault();    // this will fetch the record.

                MyQuantity = Convert.ToInt32(cartItem.Quantity);
                MyStock    = Convert.ToInt32(pr.Stock);

                //HttpContext.Current.Session["Error"] = MyStock;
                //HttpContext.Current.Response.Redirect("ErrorPage.aspx");

                if ((MyStock) > 0)
                {
                    ctx.CartItems.Add(cartItem);
                }
                else
                {
                    HttpContext.Current.Session["StockError"] = "Not in stock when creating new";
                    HttpContext.Current.Response.Redirect("ErrorPage.aspx");
                }
            }
            else
            {
                //Change the status or the order
                var pr = (from myproduct in ctx.Products
                          where myproduct.ProductID == ProductID // get the corresponding order
                          select myproduct).FirstOrDefault();    // this will fetch the record.

                MyStock = Convert.ToInt32(pr.Stock);

                //HttpContext.Current.Session["Error"] = MyStock;
                //HttpContext.Current.Response.Redirect("ErrorPage.aspx");

                //check stock
                if ((MyStock) > 0)
                {
                    // If the item does exist in the cart,
                    // then add one to the quantity.
                    cartItem.Quantity++;
                }
                else
                {
                    HttpContext.Current.Session["StockError"] = "Not in stock when adding to existing";
                    HttpContext.Current.Response.Redirect("ErrorPage.aspx");
                }
            }
            //remove from inventory
            // DiminishInventory();
            ctx.SaveChanges();
        }
Exemple #10
0
        /// <summary>
        /// Provide behavior for checkout button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCheckOut_Click(object sender, EventArgs e)
        {
            EntityMappingContext ctx = new EntityMappingContext();

            //instantiate store engine to get cart items
            ShoppingCartEngine cartEngine = new ShoppingCartEngine();


            //create an order status object in order to set it to submitted
            OrderStatus orderstatus = ctx.OrderStatuses.Create();

            //get the cart items
            List <CartItem> cartItemList = cartEngine.GetCartItems();

            // Session["CartItems"] = cartItemList;

            orderstatus.Status = "Created " + DateTime.Now.ToString();

            //Session["Error"] = orderstatus.Status;
            //Response.Redirect("/UserPages/ErrorPage.aspx");

            try
            {
                ctx.OrderStatuses.Add(orderstatus);
                ctx.SaveChanges();
                //validate
                ctx.Configuration.ValidateOnSaveEnabled = true;
            }
            catch (DbEntityValidationException ex)
            {
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                Session["Error"] = fullErrorMessage;

                Response.Redirect("ErrorPage.aspx");

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }


            //now deal with registering the user's data. If he / she is not registered
            //He will be prompted to register, otherwise he will proceed to simply checkout

            AdminEngine adminEngine = new AdminEngine();

            //// && System.Web.HttpContext.Current.User.IsInRole("user")
            //&& System.Web.HttpContext.Current.User.IsInRole("Customer")

            string user = System.Web.HttpContext.Current.User.Identity.Name;

            var store = new UserStore <ApplicationUser>(new ApplicationDbContext());

            store.AutoSaveChanges = false;

            var currentUserId = User.Identity.GetUserId();
            var manager       = new UserManager <ApplicationUser>(store);
            var currentUser   = manager.FindById(User.Identity.GetUserId());

            //if the current user is null he is not authenticated
            if (!(currentUser == null))
            {
                //If the object to be checked is null create it
                if (currentUser.MyUserCCardInfo == null)
                {
                    //creating object
                    currentUser.MyUserCCardInfo = new MyUserCCardInfo();
                    //go to enter data
                    Response.Redirect("~/UserPages/EnterUserData.aspx");
                }
                else
                {   //If the credit card number is not null the record exists
                    //and just confirmation is required
                    if (!(currentUser.MyUserCCardInfo.CardNumber == null))
                    {
                        //Create order
                        shoppingCart.CreateOrder(currentUser);

                        //go to confirm
                        Response.Redirect("~/Secure/UserPagesSecured/ConfirmOrder.aspx");
                    }
                    else
                    {
                        //if not then enter user data
                        Response.Redirect("~/UserPages/EnterUserData.aspx");
                    }
                }
            }
            //if the user is not authenticated then make sure he is logged out and send him to login
            else
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.SignOut();
                HttpContext.Current.Response.Redirect("~/Account/Login.aspx");
            }

            //check if the credit card number is null if not then just confirm
            if (!(currentUser.MyUserCCardInfo.CardNumber == null))
            {
                //Create order
                shoppingCart.CreateOrder(currentUser);

                //go to confirm
                Response.Redirect("~/Secure/UserPagesSecured/ConfirmOrder.aspx");
            }

            //if the user name is null then login
            if (user == null)
            {
                HttpContext.Current.Response.Redirect("~/Account/Login.aspx");
            }
        }