コード例 #1
0
        private void LoadCart()
        {
            if (Session["CartId"] == null)
            {
                Response.Redirect("Default.aspx");
            }

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
            {
                var sql = "SELECT i.CartItemId, p.ProductId, p.Name, p.Price, i.Quantity " +
                          " FROM dbo.CartItem i" +
                          " INNER JOIN dbo.Product p ON p.ProductId = i.ProductId" +
                          " WHERE i.CartId = @CartId" +
                          " ORDER BY p.Name";
                using (var cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddWithValue("@CartId", Session["CartId"]);
                    con.Open();

                    using (var rdr = cmd.ExecuteReader())
                    {
                        CartRepeater.DataSource = rdr;
                        CartRepeater.DataBind();
                    }

                    cmd.CommandText = "SELECT SUM(p.Price * i.Quantity)" +
                                      " FROM dbo.CartItem i " +
                                      " INNER JOIN dbo.Product p ON p.ProductId = i.ProductId" +
                                      " WHERE CartId = @CartId";
                    var total = cmd.ExecuteScalar();
                    CartTotalLabel.Text = total == DBNull.Value ? "" : ((decimal)total).ToString("C");
                }
            }
        }
コード例 #2
0
        private void LoadCart()
        {
            var cartList = Cart.GetCartItems();

            CartRepeater.DataSource = cartList;
            CartRepeater.DataBind();
            UpdatePanel4.Update();
        }
コード例 #3
0
        private void Bind(int page)
        {
            // First get all of the assets in the cart
            CartFinder finder = new CartFinder {
                UserId = CurrentUser.UserId.GetValueOrDefault()
            };

            finder.SortExpressions.Add(new DescendingSort(Cart.Columns.DateAdded.ToString()));
            finder.SortExpressions.Add(new DescendingSort(Cart.Columns.CartId.ToString()));
            List <Cart> items = Cart.FindMany(finder);

            // Filter out those assets that are not accessible by the current user
            var validItems = (from item in items
                              where EntitySecurityManager.CanViewAssetInfo(CurrentUser, item.Asset)
                              select item);

            // Get the asset count
            int total = validItems.Count();

            // Set the page size
            SessionInfo.Current.UserSessionInfo.CartPageSize = PageSize;

            // Bind the asset list to relevant page
            CartRepeater.DataSource = items;
            CartRepeater.DataBind();

            // Setup the top pager
            TopPager.CurrentPage = page;
            TopPager.PageSize    = PageSize;
            TopPager.ItemCount   = total;
            TopPager.CalculatePageCount();

            // Setup the bottom pager
            BottomPager.CurrentPage = TopPager.CurrentPage;
            BottomPager.PageSize    = TopPager.PageSize;
            BottomPager.ItemCount   = TopPager.ItemCount;
            BottomPager.CalculatePageCount();

            // Setup page variables
            CurrentPage = page;
            AssetCount  = total;
            TotalPages  = TopPager.PageCount;

            // Toggle no results panel
            CartResultsPanel.Visible   = (items.Count > 0);
            CartNoResultsPanel.Visible = (items.Count == 0);
        }
コード例 #4
0
        /// <summary>
        /// Creates new order based on current shopping cart
        /// </summary>
        /// <param name="Sender">Control on page</param>
        /// <param name="e">Event args</param>
        protected void CheckoutCommand(Object Sender, EventArgs e)
        {
            if (shoppingCart != null && shoppingCart.Count > 0)
            {
                using (var writeWorkspace = WebShopServicesSingleton.Instance.OpenWorkspace(IsolationLevel.Exclusive))
                {
                    // Creating new order
                    Order newOrder = writeWorkspace.New <Order>();
                    newOrder.ID              = Guid.NewGuid();
                    newOrder.OrderDate       = DateTime.Now;
                    newOrder.ShipDate        = DateTime.Now;
                    newOrder.CustomerName    = "Admin";
                    newOrder.CustomerAddress = "1st street";
                    // Creating collection of order items
                    newOrder.OrderItems = writeWorkspace.New <IIndexedCollection <OrderItem> >();
                    OrderItem newOrderItem = null;
                    foreach (var product in shoppingCart)
                    {
                        newOrderItem          = writeWorkspace.New <OrderItem>();
                        newOrderItem.ID       = Guid.NewGuid();
                        newOrderItem.Product  = product.Key;
                        newOrderItem.Quantity = product.Value;
                        newOrder.OrderItems.Add(newOrderItem);
                    }

                    // Add newly created order to the collection of orders
                    writeWorkspace.Data.Orders.Add(newOrder);

                    // Commit changes in workspace
                    writeWorkspace.Commit();
                }


                // Forward the page workspace for reading new values
                workspace.Update();

                // Clear shopping cart from session
                Session["shoppingCart"] = null;
                shoppingCart            = null;

                // Reload page
                CartRepeater.DataSource = null;
                CartRepeater.DataBind();
                cartPanel.Update();
            }
        }
コード例 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Open workspace on page load
            workspace = WebShopServicesSingleton.Instance.OpenWorkspace(IsolationLevel.ReadOnly);

            // See if there is a shopping cart object on session
            if (Session["shoppingCart"] != null)
            {
                Dictionary <String, int> tempShoppingCart = (Dictionary <String, int>)Session["shoppingCart"];
                if (tempShoppingCart != null)
                {
                    shoppingCart = new Dictionary <Product, int>();
                    Product product;
                    foreach (var cartItem in tempShoppingCart)
                    {
                        product = workspace.Data.Products.Single(p => p.ID.Equals(Guid.Parse(cartItem.Key)));
                        shoppingCart.Add(product, cartItem.Value);
                    }
                    CartRepeater.DataSource = shoppingCart;
                    CartRepeater.DataBind();
                }
            }
        }
コード例 #6
0
    public void BindCart()
    {
        MessageLiteral.Text     = "Your Cart";
        CartRepeater.DataSource = this.Cart.CartItems;
        CartRepeater.DataBind();
        ((Repeater)CartRepeater.Controls[CartRepeater.Controls.Count - 1].FindControl("OffersRepeater")).DataSource = this.Cart.CartCoupons;
        ((Repeater)CartRepeater.Controls[CartRepeater.Controls.Count - 1].FindControl("OffersRepeater")).DataBind();
        CartManager manager = new CartManager(this.Cart);

        this.Cart.Discounts = manager.Discounts;
        this.Cart.Subtotal  = manager.SubTotal;
        this.Cart.Total     = manager.Total;
        if (this.Cart.CartItems.Count == 0)
        {
            MessageLiteral.Text   += " is Empty";
            CheckoutButton.Enabled = false;
            UpdateButton.Enabled   = false;
        }
        else
        {
            CheckoutButton.Enabled = true;
            UpdateButton.Enabled   = true;
        }
    }
コード例 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (OrderToEdit == null || (OrderToEdit.GetAttributeValue <EntityReference>("customerid") != null && !OrderToEdit.GetAttributeValue <EntityReference>("customerid").Equals(Contact.ToEntityReference())))
            {
                PageBreadcrumbs.Visible  = true;
                GenericError.Visible     = true;
                OrderHeader.Visible      = false;
                OrderDetails.Visible     = false;
                OrderInfo.Visible        = false;
                OrderBreadcrumbs.Visible = false;
                OrderHeader.Visible      = false;

                return;
            }

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
            var dataAdapter             = new AnnotationDataAdapter(dataAdapterDependencies);
            var annotations             = dataAdapter.GetAnnotations(OrderToEdit.ToEntityReference(),
                                                                     new List <Order> {
                new Order("createdon")
            });

            NotesList.DataSource = annotations;
            NotesList.DataBind();

            var formViewDataSource = new CrmDataSource {
                ID = "WebFormDataSource", CrmDataContextName = FormView.ContextName
            };

            var fetchXml = string.Format("<fetch mapping='logical'><entity name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></entity></fetch>", "salesorder", "salesorderid", OrderToEdit.GetAttributeValue <Guid>("salesorderid"));

            formViewDataSource.FetchXml = fetchXml;

            OrderForm.Controls.Add(formViewDataSource);

            FormView.DataSourceID = "WebFormDataSource";

            var baseCartReference = OrderToEdit.GetAttributeValue <EntityReference>("adx_shoppingcartid");

            if (baseCartReference == null)
            {
                ShoppingCartSummary.Visible = false;

                Entity invoice;

                if (TryGetInvoice(XrmContext, OrderToEdit, out invoice))
                {
                    ShowInvoice(XrmContext, invoice);

                    return;
                }

                ShowOrder(XrmContext, OrderToEdit);

                Order.Visible   = true;
                Invoice.Visible = false;

                return;
            }

            // legacy code for displaying summary of ordered items.

            var baseCart = XrmContext.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_shoppingcartid") == baseCartReference.Id);

            var cartRecord = baseCart == null ? null : new ShoppingCart(baseCart, XrmContext);

            if (cartRecord == null)
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            var cartItems = cartRecord.GetCartItems().Select(sci => sci.Entity);

            if (!cartItems.Any())
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            CartRepeater.DataSource = cartItems;
            CartRepeater.DataBind();

            Total.Text = cartRecord.GetCartTotal().ToString("C2");
        }
コード例 #8
0
ファイル: QuoteStatus.aspx.cs プロジェクト: weedkiller/dms
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            var quoteToEditEntity = QuoteToEdit != null ? QuoteToEdit.Entity : null;

            if (quoteToEditEntity == null || (quoteToEditEntity.GetAttributeValue <EntityReference>("customerid") != null && !quoteToEditEntity.GetAttributeValue <EntityReference>("customerid").Equals(Contact.ToEntityReference())))
            {
                PageBreadcrumbs.Visible  = true;
                GenericError.Visible     = true;
                QuoteHeader.Visible      = false;
                QuoteDetails.Visible     = false;
                QuoteInfo.Visible        = false;
                QuoteBreadcrumbs.Visible = false;
                QuoteHeader.Visible      = false;

                return;
            }

            var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
            var dataAdapter             = new AnnotationDataAdapter(dataAdapterDependencies);
            var annotations             = dataAdapter.GetAnnotations(QuoteToEdit.Entity.ToEntityReference(),
                                                                     new List <Order> {
                new Order("createdon")
            });

            NotesList.DataSource = annotations;
            NotesList.DataBind();

            var quoteState = quoteToEditEntity.GetAttributeValue <OptionSetValue>("statecode");

            ConvertToOrder.Visible = quoteState != null &&
                                     (quoteState.Value == (int)Enums.QuoteState.Active || quoteState.Value == (int)Enums.QuoteState.Won);

            var formViewDataSource = new CrmDataSource {
                ID = "WebFormDataSource", CrmDataContextName = FormView.ContextName
            };

            var fetchXml = string.Format("<fetch mapping='logical'><entity name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></entity></fetch>", "quote", "quoteid", QuoteToEdit.Id);

            formViewDataSource.FetchXml = fetchXml;

            QuoteForm.Controls.Add(formViewDataSource);

            FormView.DataSourceID = "WebFormDataSource";

            var baseCartReference = quoteToEditEntity.GetAttributeValue <EntityReference>("adx_shoppingcartid");

            var baseCart = (baseCartReference != null) ? ServiceContext.CreateQuery("adx_shoppingcart").FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_shoppingcartid") == baseCartReference.Id)
                                : null;

            var cartRecord = baseCart == null ? null : new ShoppingCart(baseCart, XrmContext);

            if (cartRecord == null)
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            var cartItems = cartRecord.GetCartItems().Select(sci => sci.Entity);

            if (!cartItems.Any())
            {
                ShoppingCartSummary.Visible = false;

                return;
            }

            CartRepeater.DataSource = cartItems;
            CartRepeater.DataBind();

            Total.Text = cartRecord.GetCartTotal().ToString("C2");
        }
コード例 #9
0
        public void Bind()
        {
            var mode  = PersistentLightboxCartInfo.PersistentCartLightboxMode;
            var state = PersistentLightboxCartInfo.PersistentCartLightboxState;

            if (mode == PersistentCartLightboxMode.Cart)
            {
                var items = ContextInfo.CartManager.CartList;
                int count = items.Count;

                CartItemCount1.Text = count.ToString();
                CartItemCount2.Text = count.ToString();

                if (state == PersistentCartLightboxState.Open)
                {
                    int offset = PersistentLightboxCartInfo.CartOffSet;

                    if (count <= NumberOfAssetsToDisplay)
                    {
                        offset = 0;
                    }
                    else if (offset > count - NumberOfAssetsToDisplay)
                    {
                        offset = count - NumberOfAssetsToDisplay;
                    }

                    if (items.Count == 0)
                    {
                        offset = 0;
                        items.Add(Cart.Empty);
                    }

                    items = ContextInfo.CartManager.CartList.Skip(offset).Take(NumberOfAssetsToDisplay).ToList();

                    CartRepeater.DataSource = items;
                    CartRepeater.DataBind();

                    UpdatePagingControls(CartRepeater, offset, count);
                }
            }

            if (mode == PersistentCartLightboxMode.Lightbox)
            {
                var lbaList = ContextInfo.LightboxManager.GetLightboxById(SelectedLightboxId).GetLightboxAssetList();

                var items = (from item in lbaList
                             where (EntitySecurityManager.CanViewAssetInfo(CurrentUser, item.Asset))
                             orderby item.LightboxAssetId ascending
                             select item).ToList();

                int count = items.Count;
                LightboxItemCount1.Text = count.ToString();
                LightboxItemCount2.Text = LightboxItemCount1.Text;

                NewLightboxHyperLink.NavigateUrl  = string.Format("~/MyAccount/ViewLightbox.aspx?lightboxId={0}&action=new", SelectedLightboxId);
                SendLightboxHyperLink.NavigateUrl = string.Format("~/MyAccount/ViewLightbox.aspx?lightboxId={0}&action=send", SelectedLightboxId);
                ViewLightboxHyperLink.NavigateUrl = string.Format("~/MyAccount/ViewLightbox.aspx?lightboxId={0}", SelectedLightboxId);

                if (state == PersistentCartLightboxState.Open)
                {
                    int offset = PersistentLightboxCartInfo.LightboxOffSet;

                    if (count <= NumberOfAssetsToDisplay)
                    {
                        offset = 0;
                    }
                    else if (offset > count - NumberOfAssetsToDisplay)
                    {
                        offset = count - NumberOfAssetsToDisplay;
                    }

                    if (items.Count == 0)
                    {
                        offset = 0;
                        items.Add(LightboxAsset.Empty);
                    }

                    LightboxRepeater.DataSource = items.Skip(offset).Take(NumberOfAssetsToDisplay);
                    LightboxRepeater.DataBind();

                    UpdatePagingControls(LightboxRepeater, offset, count);
                }
            }
        }
コード例 #10
0
        protected void LoadShoppingCart()
        {
            // We create a DataTable (in memory) to store data in and a DataRow so that we can add rows to the
            // DataTable as we iterate through each product in the HttpCookie.
            DataTable tblShoppingCart = new DataTable("CartTable");
            DataRow   rwShoppingCart  = null;

            // We declare "num" to iterate through the HttpCookie and we declare "CartCookie" to be able to check for
            // its existens and to get data from this HttpCookie.
            Int32      num        = default(Int32);
            HttpCookie CartCookie = Request.Cookies.Get("CartCookie");

            // We check to see if the HttpCookie with the name of CartCookie exists so that we not
            // will get any null point exeptions if the HttpCookie does not exist. We also check if
            // the "CartCookie" has any keys, if there are no keys there are no products in the
            // shopping cart and then we will get an exeption if we try to selects products
            // from the "Products" table.
            if (CartCookie != null)
            {
                if (CartCookie.HasKeys)
                {
                    // We add 5 columns to our DataTable, we need to add the columns before we iterate through each
                    // product so that we get only one set of columns :-).
                    tblShoppingCart.Columns.Add("ProductIDC");
                    tblShoppingCart.Columns.Add("ProductName");
                    tblShoppingCart.Columns.Add("SaletaxPercent");
                    tblShoppingCart.Columns.Add("QuantityC");
                    tblShoppingCart.Columns.Add("PriceExSaleTax");

                    // We iterate through each post in the HttpCookie and get the ProductID and Quantity for
                    // each post. We use the ProductID to select data from the Products table.

                    for (num = 0; num <= CartCookie.Values.Count - 1; num++)
                    {
                        string ProductID = CartCookie.Values.AllKeys[num];
                        string Quantity  = CartCookie.Values[num];

                        try
                        {
                            string ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
                            string sql        = "SELECT * FROM Products WHERE ProductID = @ProductID";

                            // Create a SqlConnection. The using block is used to call dispose (close) automatically
                            // even if there are an exception.
                            using (SqlConnection cn = new SqlConnection(ConnString))
                            {
                                // Create a SqlCommand. The using block is used to call dispose (close) automatically
                                // even if there are an exception.
                                using (SqlCommand cmd = new SqlCommand(sql, cn))
                                {
                                    // Add parameters.
                                    cmd.Parameters.AddWithValue("@ProductID", ProductID);

                                    // Open the connection.
                                    cn.Open();

                                    // Create a SqlDatareader and execute the SELECT command. The using block is used
                                    // to call dispose (close) automatically even if there are an exception.
                                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                                    {
                                        while (reader.Read())
                                        {
                                            // We add one row to the DataTable and fill each cell with data.
                                            rwShoppingCart    = tblShoppingCart.NewRow();
                                            rwShoppingCart[0] = ProductID;
                                            rwShoppingCart[1] = reader["ProductName"].ToString();
                                            rwShoppingCart[2] = Convert.ToDecimal(reader["SaletaxPercent"]) * 100;
                                            rwShoppingCart[3] = Quantity;
                                            rwShoppingCart[4] = reader["PriceExSaleTax"].ToString();
                                            tblShoppingCart.Rows.Add(rwShoppingCart);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.Message);
                        }
                    }

                    // We fill our Repeater control with the data from the "tblShoppingCart" DataTable.
                    CartRepeater.DataSource = tblShoppingCart;
                    CartRepeater.DataBind();

                    // Call a subroutine to calculate totals in the shopping cart.
                    CalculateCartSums();
                }
                else
                {
                    // If the HttpCookie does not have any keys we update the shopping cart so that it does not show
                    // any rows.
                    CartRepeater.DataSource = string.Empty;
                    CartRepeater.DataBind();

                    // Call a subroutine to calculate totals in the shopping cart
                    CalculateCartSums();
                }
            }
        }