public void CreateProfile()
        {
            Stopwatch watch = Stopwatch.StartNew();

            var profile = new Profile();
            profile.Username = NAME;
            profile.ApplicationName = "PetShop..Businesss";
            profile.IsAnonymous = false;
            profile.LastActivityDate = DateTime.Now;
            profile.LastUpdatedDate = DateTime.Now;

            try
            {
                using (var context = new PetshopDataContext())
                {
                    context.Profile.InsertOnSubmit(profile);
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            
            Assert.IsTrue(true);

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        /// <summary>
        /// Update profile
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (var context = new PetshopDataContext())
            {
                /*var options = new DataLoadOptions();
                options.LoadWith<Profile>(p => p.AccountList);
                context.LoadOptions = options;*/

                var profile = context.Profile.GetProfile(User.Identity.Name);

                if (!string.IsNullOrEmpty(profile.Username) && AddressForm.IsValid)
                {
                    if (profile.AccountList.Count > 0)
                    {
                        Account account = profile.AccountList[0];
                        UpdateAccount(ref account, AddressForm.Address);
                    }
                    else
                    {
                        var account = new Account();
                        profile.AccountList.Add(account);
                        account.Profile = profile;

                        UpdateAccount(ref account, AddressForm.Address);
                    }

                    context.SubmitChanges();
                }
            }
            lblMessage.Text = "Your profile information has been successfully updated.<br>&nbsp;";
        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string itemId = Request.QueryString["addItem"];
                if (!string.IsNullOrEmpty(itemId))
                {
                    Profile profile = null;
                    using (var context = new PetshopDataContext())
                    {
                        profile = context.Profile.GetProfile(Page.User.Identity.Name);

                        if (profile != null)
                            context.Profile.Detach(profile);
                    }

                    if (profile != null && !string.IsNullOrEmpty(profile.Username))
                    {
                        CartHelper.Add(profile.WishList, itemId, profile.UniqueID, false);
                    }

                    // Redirect to prevent duplictations in the wish list if user hits "Refresh"
                    Response.Redirect("~/WishList.aspx", true);
                }
            }
        }
        /// <summary>
        /// Method to retrieve and cache category name by its ID
        /// </summary>
        /// <param name="categoryId">Category id</param>
        /// <returns>Category name</returns>
        public static string GetCategoryName(string categoryId)
        {
            if (!enableCaching)
            {
                string categoryName = String.Empty;
                using (var context = new PetshopDataContext())
                {
                    categoryName = context.Category.GetByKey(categoryId).Name;
                }
                return categoryName;
            }

            string cacheKey = string.Format(CATEGORY_NAME_KEY, categoryId);

            // Check if the data exists in the data cache
            var data = (string) HttpRuntime.Cache[cacheKey];
            if (data == null)
            {
                // Caching duration from Web.config
                int cacheDuration = int.Parse(ConfigurationManager.AppSettings["CategoryCacheDuration"]);

                // If the data is not in the cache then fetch the data from the business logic tier
                using (var context = new PetshopDataContext())
                {
                    data = context.Category.GetByKey(categoryId).Name;
                }

                // Store the output in the data cache, and Add the necessary AggregateCacheDependency object
                HttpRuntime.Cache.Add(cacheKey, data, null, DateTime.Now.AddHours(cacheDuration),
                                      Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }

            return data;
        }
        /// <summary>
        /// Calculate total
        /// </summary>
        protected void BtnTotal_Click(object sender, ImageClickEventArgs e)
        {
            using (var context = new PetshopDataContext())
            {
                var profile = context.Profile.GetProfile(Page.User.Identity.Name);
                if (!string.IsNullOrEmpty(profile.Username))
                {
                    TextBox txtQuantity;
                    ImageButton btnDelete;
                    int qty = 0;
                    foreach (RepeaterItem row in repShoppingCart.Items)
                    {
                        txtQuantity = (TextBox)row.FindControl("txtQuantity");
                        btnDelete = (ImageButton)row.FindControl("btnDelete");
                        if (int.TryParse(WebUtility.InputText(txtQuantity.Text, 10), out qty))
                        {

                            if (qty > 0)
                                CartHelper.SetQuantity(profile.ShoppingCart, btnDelete.CommandArgument, qty);
                            else if (qty == 0)
                                CartHelper.Remove(profile.ShoppingCart, btnDelete.CommandArgument);
                        }
                    }
                }
            }
            BindCart();
        }
 /// <summary>
 /// Bind repeater to Cart object in Profile
 /// </summary>
 private void BindCart()
 {
     using (var context = new PetshopDataContext())
     {
         var profile = context.Profile.GetProfile(Page.User.Identity.Name);
         if (!string.IsNullOrEmpty(profile.Username))
         {
             List<Cart> items = profile.ShoppingCart;
             context.Cart.DetachAll(items);
             if (items.Count > 0)
             {
                 repShoppingCart.DataSource = items;
                 repShoppingCart.DataBind();
                 PrintTotal();
                 plhTotal.Visible = true;
             }
             else
             {
                 repShoppingCart.Visible = false;
                 plhTotal.Visible = false;
                 lblMsg.Text = "Your cart is empty.";
             }
         }
     }
 }
 public static void ClearCart(List<Cart> items)
 {
     using (var context = new PetshopDataContext())
     {
         context.Cart.AttachAll(items);
         context.Cart.DeleteAllOnSubmit(items);
         context.SubmitChanges();
     }
 }
 protected Inventory GetInventory(string itemId)
 {
     Inventory inventory;
     using( var context = new PetshopDataContext())
     {
         inventory = context.Inventory.GetByKey(itemId);
         context.Inventory.Detach(inventory);
     }
     return inventory;
 }
 // Bind categories
 private void BindCategories()
 {
     
     using (var context = new PetshopDataContext())
     {
         rePCategories.DataSource = context.Category.OrderBy(c => c.Name).FromCache().ToList();
     }
     
     rePCategories.DataBind();
 }
 public static void SetQuantity(List<Cart> items, string itemId, int quantity)
 {
     var item = items.FirstOrDefault(i => i.ItemId == itemId);
     using (var context = new PetshopDataContext())
     {
         context.Cart.Attach(item);
         item.Quantity = quantity;
         context.SubmitChanges();
     }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (billingForm.Address == null)
     {
         using (var context = new PetshopDataContext())
         {
             var profile = context.Profile.GetProfile(User.Identity.Name);
             billingForm.Address = new Address(profile);
         }
     }
 }
 /// <summary>
 /// Recalculate the total
 /// </summary>
 private void PrintTotal()
 {
     using (var context = new PetshopDataContext())
     {
         var profile = context.Profile.GetProfile(Page.User.Identity.Name);
         if (!string.IsNullOrEmpty(profile.Username))
         {
             if (profile.ShoppingCart.Count > 0)
                 ltlTotal.Text = CartHelper.GetTotal(profile.ShoppingCart).ToString("c");
         }
     }
 }
        /// <summary>
        /// Rebind control 
        /// </summary>
        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            //reset index
            productsList.CurrentPageIndex = e.NewPageIndex;

            //get category id
            string categoryId = Request.QueryString["categoryId"];

            //bind data(
            using (var context = new PetshopDataContext())
            {
                productsList.DataSource = context.Product.ByCategory(categoryId).ToList();
            }
            productsList.DataBind();
        }
        public void FetchProfile()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Profile profile = null;
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            Assert.IsTrue(profile.Username == NAME);
            
            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        /// <summary>
        /// Rebind control 
        /// </summary>
        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            //reset index
            searchList.CurrentPageIndex = e.NewPageIndex;

            //get category id
            string keywordKey = Request.QueryString["keywords"];

            var list = new List<Product>();
            using (var context = new PetshopDataContext())
            {
                list = context.Product.Search(keywordKey).ToList();
            }

            //bind data
            searchList.DataSource = list;
            searchList.DataBind();
        }
 protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
 {
     using (var context = new PetshopDataContext())
     {
         string userName = ((System.Web.UI.WebControls.CreateUserWizard)sender).UserName;
         var profile = context.Profile.GetProfile(userName);
         if (null == profile)
         {
             profile = new Profile();
             profile.Username = userName;
             profile.ApplicationName = ".NET Pet Shop 4.0";
             profile.IsAnonymous = false;
             profile.LastActivityDate = DateTime.Now;
             profile.LastUpdatedDate = DateTime.Now;
             context.Profile.InsertOnSubmit(profile);
             context.SubmitChanges();
         }
     }
 }
        public static void Add(List<Cart> items, string itemId, int uniqueId, bool isShoppingCart)
        { 
            int index = 0;
            bool found = false;
            using (var context = new PetshopDataContext())
            {
                /*var options = new DataLoadOptions();
                options.LoadWith<Item>(i => i.Product);*/

                var item = items.FirstOrDefault(i => i.ItemId == itemId);

                if (item != null)
                {
                    context.Cart.Attach(item);
                    item.Quantity++;

                }
                else
                {
                    var cartItem = context.Item
                        .ByItemId(itemId)
                        .Fetch(i => i.Product)
                        .FirstOrDefault();
                    var profile = context.Profile.GetByKey(uniqueId);

                    var cart = new Cart();
                    cart.Profile = profile;
                    cart.ItemId = itemId;
                    cart.Name = cartItem.Name;
                    cart.ProductId = cartItem.Product.ProductId; // HERE
                    cart.IsShoppingCart = isShoppingCart;
                    cart.Price = cartItem.ListPrice ?? cartItem.UnitCost ?? 0;
                    cart.Type = cartItem.Product.Name;
                    cart.CategoryId = cartItem.Product.Category.CategoryId; // HERE
                    cart.Quantity = 1;
                    items.Add(cart);

                    context.Cart.InsertOnSubmit(cart);
                }
                context.SubmitChanges();
            }
        }
        /// <summary>
        /// Bind controls to profile
        /// </summary>
        private void BindUser()
        {
            using (var context = new PetshopDataContext())
            {
                var profile = context.Profile.GetProfile(User.Identity.Name);

                if (string.IsNullOrEmpty(profile.Username))
                {
                    profile = new Profile();
                    profile.Username = User.Identity.Name;
                    profile.ApplicationName = ".NET Pet Shop 4.0";
                    profile.IsAnonymous = !User.Identity.IsAuthenticated;
                    profile.LastActivityDate = DateTime.Now;
                    profile.LastUpdatedDate = DateTime.Now;
                    context.Profile.InsertOnSubmit(profile);
                    context.SubmitChanges();
                }
                AddressForm.Address = new Address(profile);
            }
        }
        /// <summary>
        /// Rebind control 
        /// </summary>
        protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            //reset index
            itemsGrid.CurrentPageIndex = e.NewPageIndex;

            //get category id
            string productId = Request.QueryString["productId"];

            using (var context = new PetshopDataContext())
            {
                /*var options = new DataLoadOptions();
                options.LoadWith<Item>(i => i.Product);
                context.LoadOptions = options;*/

                itemsGrid.DataSource = context.Item
                    .ByProduct(productId)
                    .Fetch(i => i.Product)
                    .ToList();
            }
            itemsGrid.DataBind();
        }
        /// <summary>
        /// Bind repeater to Cart object in Profile
        /// </summary>
        private void BindCart()
        {
            var profile = new Profile();
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(Page.User.Identity.Name);
            }

            if (!string.IsNullOrEmpty(profile.Username))
            {
                List<Cart> wishList = profile.WishList;
                if (wishList.Count > 0)
                {
                    repWishList.DataSource = wishList;
                    repWishList.DataBind();
                }
                else
                {
                    repWishList.Visible = false;
                    lblMsg.Text = "Your wish list is empty.";
                }
            }
        }
        /// <summary>
        /// Handler for Delete/Move buttons
        /// </summary>
        protected void CartItem_Command(object sender, CommandEventArgs e)
        {
            var profile = new Profile();
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(Page.User.Identity.Name);
                context.Profile.Detach(profile);
            }
            if (!string.IsNullOrEmpty(profile.Username))
            {
                switch (e.CommandName)
                {
                    case "Del":
                        CartHelper.Remove(profile.WishList, e.CommandArgument.ToString());
                        break;
                    case "Move":
                        CartHelper.MoveToCart(profile, e.CommandArgument.ToString());
                        break;
                }
            }

            BindCart();
        }
        public void UpdateProfile()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Profile profile = null;
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            using (var context = new PetshopDataContext())
            {
                context.Profile.Attach(profile);
                profile.IsAnonymous = true;
                context.SubmitChanges();
            }

            using (var context = new PetshopDataContext())
            {
                Assert.IsTrue(context.Profile.GetProfile(NAME).IsAnonymous.Value);
            }
            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        public void UpdateItem()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Item item = null;
            using (var context = new PetshopDataContext())
            {
                item = context.Item.GetByKey(ID);
                context.Item.Detach(item);
            }

            using (var context = new PetshopDataContext())
            {
                context.Item.Attach(item);
                item.ListPrice = 111;
                context.SubmitChanges();
            }

            using (var context = new PetshopDataContext())
            {
                Assert.IsTrue(context.Item.GetByKey(ID).ListPrice == 111);
            }

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        public void UpdateSupplier()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Supplier supplier = null;
            using (var context = new PetshopDataContext())
            {
                supplier = context.Supplier.GetByKey(_supplierId);
                context.Supplier.Detach(supplier);
            }

            using (var context = new PetshopDataContext())
            {
                context.Supplier.Attach(supplier);
                supplier.Phone = "111-111-1111";
                context.SubmitChanges();
            }

            using (var context = new PetshopDataContext())
            {
                Assert.IsTrue(context.Supplier.GetByKey(_supplierId).Phone == "111-111-1111");
            }

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        public void FetchItem()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Item item = null;
            using (var context = new PetshopDataContext())
            {
                item = context.Item.GetByKey(ID);
                context.Item.Detach(item);
            }

            Assert.IsTrue(item.ItemId == ID);

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        /// <summary>
        /// Process the order
        /// </summary>
        protected void wzdCheckOut_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            using (var context = new PetshopDataContext())
            {
                var profile = context.Profile.GetProfile(User.Identity.Name);
                if (profile.ShoppingCart.Count > 0)
                {
                    // display ordered items
                    CartListOrdered.Bind(profile.ShoppingCart);

                    // display total and credit card information
                    ltlTotalComplete.Text = ltlTotal.Text;
                    ltlCreditCardComplete.Text = ltlCreditCard.Text;

                    #region Create Order

                    var order = new Order();

                    order.UserId = profile.UniqueID.ToString();
                    order.OrderDate = DateTime.Now;
                    order.CreditCard = GetCreditCard();
                    order.Courier = order.CreditCard.CardType;
                    order.TotalPrice = CartHelper.GetTotal(profile.ShoppingCart);
                    order.AuthorizationNumber = 0;
                    order.Locale = "en-us";

                    #region Shipping Information

                    order.ShipAddr1 = billingForm.Address.Address1;
                    order.ShipAddr2 = billingForm.Address.Address2;
                    order.ShipCity = billingForm.Address.City;
                    order.ShipState = billingForm.Address.State;
                    order.ShipZip = billingForm.Address.Zip;
                    order.ShipCountry = billingForm.Address.Country;
                    order.ShipToFirstName = billingForm.Address.FirstName;
                    order.ShipToLastName = billingForm.Address.LastName;

                    #endregion

                    #region Billing Information

                    order.BillAddr1 = shippingForm.Address.Address1;
                    order.BillAddr2 = shippingForm.Address.Address2;
                    order.BillCity = shippingForm.Address.City;
                    order.BillState = shippingForm.Address.State;
                    order.BillZip = shippingForm.Address.Zip;
                    order.BillCountry = shippingForm.Address.Country;
                    order.BillToFirstName = shippingForm.Address.FirstName;
                    order.BillToLastName = shippingForm.Address.LastName;

                    #endregion
                    context.Order.InsertOnSubmit(order);
                    context.SubmitChanges();

                    #endregion

                    int itemsOnBackOrder = 0;
                    //Decrement and check the Inventory.
                    foreach (Cart cart in profile.ShoppingCart)
                    {
                        var inventory = context.Inventory.GetByKey(cart.ItemId);

                        if (cart.Quantity > inventory.Qty)
                        {
                            itemsOnBackOrder += cart.Quantity - inventory.Qty;
                        }

                        inventory.Qty -= cart.Quantity;
                        context.SubmitChanges();
                    }

                    if (itemsOnBackOrder > 0)
                    {
                        ItemsOnBackOrder.Text = string.Format("<br /><p style=\"color:red;\"><b>Backorder ALERT:</b> {0} items are on backorder.</p>", itemsOnBackOrder);
                    }

                    CartHelper.SaveOrderLineItems(profile.ShoppingCart, order.OrderId);

                    // destroy cart
                    CartHelper.ClearCart(profile.ShoppingCart);
                }
                else
                {
                    lblMsg.Text =
                        "<p><br>Can not process the order. Your cart is empty.</p><p class=SignUpLabel><a class=linkNewUser href=Default.aspx>Continue shopping</a></p>";
                    wzdCheckOut.Visible = false;
                }
            }
        }
        /// <summary>
        /// Changing Wiszard steps
        /// </summary>
        protected void wzdCheckOut_ActiveStePChanged(object sender, EventArgs e)
        {
            if (wzdCheckOut.ActiveStepIndex == 3)
            {
                billingConfirm.Address = billingForm.Address;
                shippingConfirm.Address = shippingForm.Address;

                using (var context = new PetshopDataContext())
                {
                    var profile = context.Profile.GetProfile(User.Identity.Name);
                    ltlTotal.Text = CartHelper.GetTotal(profile.ShoppingCart).ToString("c");
                }

                if (txtCCNumber.Text.Length > 4)
                    ltlCreditCard.Text = txtCCNumber.Text.Substring(txtCCNumber.Text.Length - 4, 4);
            }
        }
        public void RemoveItemFromShoppingCart()
        {
            Stopwatch watch = Stopwatch.StartNew();

            Profile profile = null;
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            using (var context = new PetshopDataContext())
            {
                CartHelper.Remove(profile.ShoppingCart, ID);
            }

            using (var context = new PetshopDataContext())
            {
                Assert.IsTrue(context.Profile.GetProfile(NAME).ShoppingCart.Count == 0);
            }

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        public void UpdateItemQuantityShoppingCart()
        {
            Stopwatch watch = Stopwatch.StartNew();

            //Add new Item to the cart.
            Profile profile = null;
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            CartHelper.Add(profile.ShoppingCart, ID, profile.UniqueID, true);
            CartHelper.Add(profile.ShoppingCart, ID, profile.UniqueID, true);


            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            Assert.IsTrue(profile.ShoppingCart.Count == 1 && profile.ShoppingCart[0].Quantity == 2);

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
        public void ClearShoppingCart()
        {
            Stopwatch watch = Stopwatch.StartNew();

            //Add new Item to the cart.
            Profile profile = null;
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }

            CartHelper.Add(profile.ShoppingCart, ID, profile.UniqueID, true);
            

            //Clear the cart.
            using (var context = new PetshopDataContext())
            {
                profile = context.Profile.GetProfile(NAME);
                context.Profile.Detach(profile);
            }
            
            CartHelper.ClearCart(profile.ShoppingCart);

            using (var context = new PetshopDataContext())
            {
                Assert.IsTrue(context.Profile.GetProfile(NAME).ShoppingCart.Count == 0);
            }

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }