Beispiel #1
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();
        }
Beispiel #2
0
        /// <summary>
        /// Get categories
        /// </summary>
        /// <returns></returns>
        public IQueryable GetCategories()
        {
            var        ctx   = new EntityMappingContext();
            IQueryable query = ctx.Categories;

            return(query);
        }
Beispiel #3
0
        public IQueryable <Category> GetCategories()
        {
            var _db = new EntityMappingContext();
            IQueryable <Category> query = _db.Categories;

            return(query);
        }
Beispiel #4
0
        public static void AddCount()
        {
            EntityMappingContext db = new EntityMappingContext();
            var query = db.Users.Count();

            Console.WriteLine(query);
        }
Beispiel #5
0
        /// <summary>
        /// Get products
        /// </summary>
        /// <returns></returns>
        public IQueryable GetProducts()
        {
            var        ctx   = new EntityMappingContext();
            IQueryable query = ctx.Products;

            return(query);
        }
Beispiel #6
0
        /// <summary>
        /// Bind customer row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gridUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DropDownList ddl = null;

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                ddl = e.Row.FindControl("ddlCategoryNew") as DropDownList;
            }
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    ddl = e.Row.FindControl("ddlCategory") as DropDownList;
            //}
            if (ddl != null)
            {
                using (EntityMappingContext context = new EntityMappingContext())
                {
                    ddl.DataSource    = context.Categories;
                    ddl.DataTextField = "Name";
                    //ddl.DataValueField = "CategoryID";
                    ddl.DataBind();
                    ddl.Items.Insert(0, new ListItem(""));
                }
                //if (e.Row.RowType == DataControlRowType.DataRow)
                //{
                //    ddl.SelectedValue = ((Customer)(e.Row.DataItem)).CategoryID.ToString();
                //}
            }
        }
Beispiel #7
0
 /// <summary>
 /// Disposes the context
 /// </summary>
 public void Dispose()
 {
     if (ctx != null)
     {
         ctx.Dispose();
         ctx = null;
     }
 }
Beispiel #8
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();
        }
Beispiel #9
0
        public static void AddUserValue()
        {
            Database.SetInitializer <EntityMappingContext>(new UserContext());
            EntityMappingContext db = new EntityMappingContext();

            var query = db.Users.Where(d => d.FirstName.StartsWith("D")).Count();

            Console.WriteLine(query);
        }
Beispiel #10
0
        ///     Section MyUserShippingAddress
        /// ----------------------------------------------------------------------------------------
        ///

        /// <summary>
        /// Bind Shipping Address info data to grid
        /// </summary>
        void BindShippingAddressInfo()
        {
            using (EntityMappingContext context = new EntityMappingContext())
            {
                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 (currentUser == null)
                {
                    var obj = new List <MyUserInfo>();
                    obj.Add(new MyUserInfo());

                    //gridShippingAddress.DataSource = currentUser.ShippingAddress;
                    //gridShippingAddress.DataSource = obj.ToList();
                    //gridShippingAddress.DataBind();

                    List <MyUserShippingAddress> myUserShippingAddress = new List <MyUserShippingAddress>();
                    myUserShippingAddress.Add(currentUser.ShippingAddress);

                    gridShippingAddress.DataSource = myUserShippingAddress.ToList().Where(elem => elem != null);;
                    gridShippingAddress.DataBind();

                    int columnsCount = gridCreditCard.Columns.Count;
                    gridShippingAddress.Rows[0].Cells.Clear();                      // clear all the cells in the row
                    gridShippingAddress.Rows[0].Cells.Add(new TableCell());         //add a new blank cell
                    gridShippingAddress.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

                    //You can set the styles here
                    gridShippingAddress.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    gridShippingAddress.Rows[0].Cells[0].ForeColor       = System.Drawing.Color.Red;
                    gridShippingAddress.Rows[0].Cells[0].Font.Bold       = true;
                    //set No Results found to the new added cell
                    gridShippingAddress.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
                }
                else
                {
                    //List<MyUserInfo> myUserInfoList = new List<MyUserInfo>();
                    //myUserInfoList.Add(currentUser.MyUserInfo);

                    //gridUser.DataSource = myUserInfoList.ToList();
                    //gridUser.DataBind();

                    List <MyUserShippingAddress> myUserShippingAddress = new List <MyUserShippingAddress>();
                    myUserShippingAddress.Add(currentUser.ShippingAddress);

                    gridShippingAddress.DataSource = myUserShippingAddress.ToList().Where(elem => elem != null);;
                    gridShippingAddress.DataBind();
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Method to bind employee records to repeater control.
        /// </summary>
        void bindOrderConfirmationToRepeater()
        {
            using (EntityMappingContext context = new EntityMappingContext())
            {
                rptConfirmOrder.DataSource = (from oc in context.OrderConfirmations.ToList()

                                              where  oc.OrderConfirmationId == m_lastOrderConfId select oc);
                rptConfirmOrder.DataBind();
            }
        }
Beispiel #12
0
        public IQueryable <Product> GetProducts([QueryString("id")] int?categoryId)
        {
            var _db = new EntityMappingContext();
            IQueryable <Product> query = _db.Products;

            if (categoryId.HasValue && categoryId > 0)
            {
                query = query.Where(p => p.CategoryId == categoryId);
            }
            return(query);
        }
Beispiel #13
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();
        }
Beispiel #14
0
        public IQueryable <Department> GetDepartments([QueryString("id")] int?departmentId)
        {
            var ctx = new EntityMappingContext();
            IQueryable <Department> query = ctx.Departments;

            if (departmentId.HasValue && departmentId > 0)
            {
                query = query.Where(dep => dep.DepartmentId == departmentId);
            }
            return(query);
        }
Beispiel #15
0
        public static void UserOrderby()
        {
            EntityMappingContext db = new EntityMappingContext();
            var query = from c in db.Users
                        orderby c.FirstName descending
                        select c;

            foreach (User e in query)
            {
                Console.WriteLine("{0},{1}", e.FirstName, e.UserID);
            }
        }
Beispiel #16
0
        public IQueryable <Product> GetProduct([QueryString("productID")] int?productId)
        {
            var _db = new EntityMappingContext();
            IQueryable <Product> query = _db.Products;

            if (productId.HasValue && productId > 0)
            {
                query = query.Where(product => product.ProductID == productId);
            }
            else
            {
                query = null;
            }
            return(query);
        }
Beispiel #17
0
        public static void StoredProcedure()
        {
            using (var ctx = new EntityMappingContext())
            {
                var parmv = new SqlParameter {
                    ParameterName = "@ContactId", Value = 1, DbType = System.Data.DbType.String
                };
                var Cnt = ctx.Database.SqlQuery <Contact>("EXEC GetContactId @ContactId", parmv).ToList <Contact>();


                foreach (Contact e in Cnt)
                {
                    Console.WriteLine("{0},{1},{2}", e.FirstName, e.LastName, e.Title);
                }
            }
        }
Beispiel #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gridShippingAddress_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            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());

            ApplicationUser appuserContext = new ApplicationUser();

            GridViewRow row = gridBillingAddress.Rows[e.RowIndex];
            TextBox     txtShippingAddressName   = row.FindControl("txtShippingAddressName") as TextBox;
            TextBox     txtShippingAddressNumber = row.FindControl("txtShippingAddressNumber") as TextBox;
            TextBox     txtShippingStair         = row.FindControl("txtShippingStair") as TextBox;
            TextBox     txtShippingApartment     = row.FindControl("txtShippingApartment") as TextBox;
            TextBox     txtShippingCity          = row.FindControl("txtShippingCity") as TextBox;
            TextBox     txtShippingCountry       = row.FindControl("txtShippingCountry") as TextBox;
            TextBox     txtShippingZipcode       = row.FindControl("txtShippingZipcode") as TextBox;

            //DropDownList ddlCategory = row.FindControl("ddlCategory") as DropDownList;
            if (txtShippingAddressName != null && txtShippingAddressNumber != null && txtShippingStair != null && txtShippingApartment != null && txtShippingCity != null && txtShippingCountry != null && txtShippingZipcode != null)
            {
                using (EntityMappingContext context = new EntityMappingContext())
                {
                    int      customerID = Convert.ToInt32(gridUser.DataKeys[e.RowIndex].Value);
                    Customer obj        = context.Customers.First(x => x.CustomerId == customerID);
                    currentUser.BillingAddress.AddressName   = txtShippingAddressName.Text;
                    currentUser.BillingAddress.AddressNumber = txtShippingAddressNumber.Text;
                    currentUser.BillingAddress.Stair         = txtShippingStair.Text;
                    currentUser.BillingAddress.Apartment     = txtShippingApartment.Text;
                    currentUser.BillingAddress.Country       = txtShippingCountry.Text;
                    currentUser.BillingAddress.City          = txtShippingCity.Text;
                    currentUser.BillingAddress.Zipcode       = txtShippingZipcode.Text;
                    //obj.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue);
                    store.Context.SaveChanges();
                    lblMessage.Text = "Saved successfully.";
                    gridShippingAddress.EditIndex = -1;
                    BindShippingAddressInfo();
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// Update customer row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gridUser_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            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());

            ApplicationUser appuserContext = new ApplicationUser();


            GridViewRow row           = gridUser.Rows[e.RowIndex];
            TextBox     txtFirstName  = row.FindControl("txtFirstName") as TextBox;
            TextBox     txtMiddleName = row.FindControl("txtMiddleName") as TextBox;
            TextBox     txtLastName   = row.FindControl("txtLastName") as TextBox;
            TextBox     txtEmail      = row.FindControl("txtEmail") as TextBox;
            TextBox     txtTelephone  = row.FindControl("txtTelephone") as TextBox;
            TextBox     txtCellphone  = row.FindControl("txtCellphone") as TextBox;

            //DropDownList ddlCategory = row.FindControl("ddlCategory") as DropDownList;
            if (txtFirstName != null && txtLastName != null && txtEmail != null && txtTelephone != null && txtCellphone != null && txtMiddleName != null)
            {
                using (EntityMappingContext context = new EntityMappingContext())
                {
                    int      customerID = Convert.ToInt32(gridUser.DataKeys[e.RowIndex].Value);
                    Customer obj        = context.Customers.First(x => x.CustomerId == customerID);
                    currentUser.MyUserInfo.FirstName  = txtFirstName.Text;
                    currentUser.MyUserInfo.LastName   = txtLastName.Text;
                    currentUser.MyUserInfo.Email      = txtEmail.Text;
                    currentUser.MyUserInfo.MiddleName = txtMiddleName.Text;
                    currentUser.MyUserInfo.Cellphone  = txtCellphone.Text;
                    currentUser.MyUserInfo.Telephone  = txtTelephone.Text;
                    //obj.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue);
                    store.Context.SaveChanges();
                    lblMessage.Text    = "Saved successfully.";
                    gridUser.EditIndex = -1;
                    BindGridUserInfo();
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Iterate through all the rows within the shopping cart list and  remove it if marked for removal
        /// </summary>
        /// <param name="cartId"></param>
        /// <param name="CartItemUpdates"></param>
        public void UpdateShoppingCartDatabase(String cartId, List <ShoppingCartUpdates> CartItemUpdates)
        {
            using (var db = new EntityMappingContext())
            {
                try
                {
                    //count
                    int CartItemCount = CartItemUpdates.Count();

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


                    //traversse the cart items in the cart item list
                    foreach (var cartItem in cartItemList)
                    {
                        // Iterate through all rows within shopping cart list
                        for (int i = 0; i < cartItemList.Count; i++)
                        {
                            //check if the product id matches the cart's update product id
                            if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId)
                            {
                                //if the quantity is less than 1 or if it is marked for removal
                                if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true)
                                {
                                    RemoveItem(cartId, cartItem.ProductId);
                                }
                                else
                                {
                                    //update the items's purhcase quantity
                                    UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
                                }
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp);
                }
            }
        }
Beispiel #21
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.";
                }
            }
        }
Beispiel #22
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);
         }
     }
 }
Beispiel #23
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);
                }
            }
        }
Beispiel #24
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");
            }
        }
Beispiel #25
0
        /// <summary>
        /// Create the order
        /// </summary>
        /// <param name="currentUser"></param>
        public void CreateOrder(ApplicationUser currentUser)
        {
            //start by getting the current user
            AdminEngine adminEngine = new AdminEngine();

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

            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());

            //currentUser.MyUserInfo = new MyUserInfo();

            //extractCartItems();
            using (var context = new EntityMappingContext())
            {
                //Session["Error"] = m_items;
                //Response.Redirect("/UserPages/ErrorPage.aspx");

                m_items = GetCartItems();

                //lists to store ids and quantity respectively
                m_listIds      = new List <int>();
                m_listQuantity = new List <int>();

                //fill order items - from the cart
                //get just the product id and the quantity. The rest I search for
                for (int i = 0; i < m_items.Count; i++)
                {
                    m_orderItem = new OrderItem()
                    {
                        // OrderId = order.OrderId,
                        ProductId = m_items[i].ProductId,
                        Quantity  = m_items[i].Quantity,
                        Price     = m_items[i].Product.UnitPrice,
                        ItemName  = m_items[i].Product.ProductName,
                        Specs     = m_items[i].Product.Specifications,
                    };

                    //add items and their corresponding id
                    m_listIds.Add(m_items[i].ProductId);
                    m_listQuantity.Add(m_items[i].ProductId);


                    //Product Data
                    m_ProductName   += Environment.NewLine + m_items[i].Product.ProductName + ","; // drop lines
                    m_orderQuantity += m_items[i].Quantity;
                    m_ProductPrice   = Convert.ToDouble(m_items[i].Product.UnitPrice);
                    m_Subtotal      += m_items[i].Quantity * Convert.ToDouble(m_items[i].Product.UnitPrice);
                    m_Total          = m_Subtotal * 1.25;


                    try
                    {
                        // Add OrderDetail to DB.
                        ctx.OrderItems.Add(m_orderItem);
                        ctx.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        HttpContext.Current.Session["Error"] = ex;
                        HttpContext.Current.Response.Redirect("ErrorPage.aspx");
                    }
                }


                HttpContext.Current.Session["m_listIds"]      = m_listIds;
                HttpContext.Current.Session["m_listQuantity"] = m_listQuantity;



                //Generate Order Confirmation
                OrderConfirmation orderConfirmation = new OrderConfirmation()
                {
                    CustomerName   = currentUser.MyUserInfo.FirstName,
                    CustomerMiddle = currentUser.MyUserInfo.MiddleName,
                    CustomerLast   = currentUser.MyUserInfo.LastName,
                    CustomerPhone  = currentUser.MyUserInfo.Telephone,
                    CustomerCell   = currentUser.MyUserInfo.Cellphone,
                    CustomerEmail  = currentUser.MyUserInfo.Email,

                    BillingAddressName = currentUser.BillingAddress.AddressName,
                    BillingAddressNo   = currentUser.BillingAddress.AddressNumber,
                    BillingApartment   = currentUser.BillingAddress.Apartment,
                    BillingStair       = currentUser.BillingAddress.Stair,
                    BillingZipCode     = currentUser.BillingAddress.Zipcode,
                    BillingCity        = currentUser.BillingAddress.City,
                    BillingCountry     = currentUser.BillingAddress.Country,

                    ShippingAddressName = currentUser.ShippingAddress.AddressName,
                    ShippingAddressNo   = currentUser.ShippingAddress.AddressNumber,
                    ShippingApartment   = currentUser.ShippingAddress.Apartment,
                    ShippingStair       = currentUser.ShippingAddress.Stair,
                    ShippingZipCode     = currentUser.ShippingAddress.Zipcode,
                    ShippingCity        = currentUser.ShippingAddress.City,
                    ShippingCountry     = currentUser.ShippingAddress.Country,


                    ////Product Data
                    ProductName = m_ProductName,
                    Quantity    = m_orderQuantity,
                    ProductSpec = m_orderItem.Specs,
                    Subtotal    = m_Subtotal,
                    Total       = m_Total,


                    //Payment Data - Credit Card
                    CCardName         = currentUser.MyUserCCardInfo.CardName,
                    CCardNo           = currentUser.MyUserCCardInfo.CardNumber,
                    CCArdExpiryDate   = currentUser.MyUserCCardInfo.CardExpiryDate,
                    CCardSecurityCode = currentUser.MyUserCCardInfo.CardSecurityCode,
                };


                //for (int i = 0; i < m_items.Count; i++)
                //{

                //    //instantiate orderEngine to access GetLineItem method
                //    OrderEngine orderEngine = new OrderEngine();

                //get the item list
                //List<LineItem> itemList = orderEngine.GetLineItems();

                //create order
                m_order = new Order()
                {
                    Created         = DateTime.Now.ToString(),
                    BillingAddress  = orderConfirmation.BillingAddress,
                    ShippingAddress = orderConfirmation.ShippingAddress,
                    CustomerName    = currentUser.UserName,
                    Total           = orderConfirmation.Total,
                };

                //}



                //Generate invoice
                Invoice invoice = new Invoice()
                {
                    SubTotal = m_orderItem.Price,
                    Tax      = 0.25,
                    Total    = (m_orderItem.Price * (0.25)) + m_orderItem.Quantity,
                    //       BillingAddress = billingAddress,
                };



                //initialize type to avoid nulle refference

                //CreateAddress
                Address billingAddress = new Address()
                {
                    //Address part
                    StreetName = currentUser.BillingAddress.AddressName,
                    StreetNo   = currentUser.BillingAddress.AddressNumber,
                    City       = currentUser.BillingAddress.City,
                    Country    = currentUser.BillingAddress.Country,
                    ZipCode    = currentUser.BillingAddress.Zipcode,
                };


                //Create customer
                Customer customer = new Customer()
                {
                    FirstName  = currentUser.MyUserInfo.FirstName,
                    MiddleName = currentUser.MyUserInfo.MiddleName,
                    LastName   = currentUser.MyUserInfo.LastName,
                    Phone      = currentUser.MyUserInfo.Telephone,
                    CellPhone  = currentUser.MyUserInfo.Cellphone,
                    Email      = currentUser.MyUserInfo.Email

                                 //BillingAddress = billingAddress
                };


                //add delivery address
                Address deliveryAddress = new Address()
                {
                    //Address part
                    StreetName = currentUser.ShippingAddress.AddressName,
                    StreetNo   = currentUser.ShippingAddress.AddressNumber,
                    City       = currentUser.ShippingAddress.City,
                    Country    = currentUser.ShippingAddress.Country,
                    ZipCode    = currentUser.ShippingAddress.Zipcode,
                };



                //Shippment
                Shippment shipment = new Shippment()
                {
                    State = "Not shipped",

                    AddresName  = currentUser.ShippingAddress.AddressName,
                    AddressNo   = currentUser.ShippingAddress.AddressNumber,
                    AddresApt   = currentUser.ShippingAddress.Apartment,
                    AddresStair = currentUser.ShippingAddress.Stair,
                    Country     = currentUser.ShippingAddress.Country,
                    City        = currentUser.ShippingAddress.City,
                    ZipCode     = currentUser.ShippingAddress.Zipcode,
                };



                try
                {
                    ctx.OrderConfirmations.Add(orderConfirmation);
                    ctx.Orders.Add(m_order);
                    // ctx.LineItems.Add(m_lineItem); // Add OrderDetail to DB.
                    ctx.Invoices.Add(invoice);
                    ctx.Customers.Add(customer);
                    ctx.Addresses.Add(billingAddress);
                    ctx.Shipments.Add(shipment);
                    ctx.SaveChanges();



                    // Prepare for the items to be saved. this is used to display the line items
                    List <CartItem> orderDetailList = GetCartItems();

                    // Add OrderDetail information to the DB for each product purchased.
                    for (int i = 0; i < orderDetailList.Count; i++)
                    {
                        // Create a new OrderDetail object.
                        m_lineItem = new LineItem();

                        m_lineItem.OrderId     = m_order.OrderId;
                        m_lineItem.UserName    = currentUser.UserName;
                        m_lineItem.ProductID   = orderDetailList[i].ProductId;
                        m_lineItem.ProductName = orderDetailList[i].Product.ProductName;
                        m_lineItem.Quantity    = orderDetailList[i].Quantity;
                        m_lineItem.UnitPrice   = orderDetailList[i].Product.UnitPrice;

                        ctx.LineItems.Add(m_lineItem);
                        ctx.SaveChanges();
                    }


                    m_lastOrderId = m_order.OrderId;
                    HttpContext.Current.Session["lastId"] = m_lastOrderId;

                    m_lastOrderConfirmationId = orderConfirmation.OrderConfirmationId;
                    HttpContext.Current.Session["lastOrderConfId"] = m_lastOrderConfirmationId;


                    //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);

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

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

                finally
                {
                    //orderId
                    var orderId = ctx.Orders.OrderByDescending(myorder => myorder.OrderId).FirstOrDefault();

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

                    anorder.Submitted = DateTime.Now.ToString();
                    ctx.SaveChanges();
                }

                ////reset the cart for next order
                //// cartEngine.ZeroCart();
                // EmptyCart();
                //HttpContext.Current.Response.Redirect("/UserPages/Products.aspx");
            }//end EntityMappingContext
        }