/// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shopping cart item parameters</param>
    protected void AddProducts(ShoppingCartItemParameters itemParams)
    {
        // Get main product info
        int productId = itemParams.SKUID;
        int quantity = itemParams.Quantity;

        if ((productId > 0) && (quantity > 0))
        {
            // Check product/options combination
            if (ShoppingCartInfoProvider.CheckNewShoppingCartItems(ShoppingCart, itemParams))
            {
                // Get requested SKU info object from database
                SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(productId);
                if (skuObj != null)
                {
                    // On the live site
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        bool updateCart = false;

                        // Assign current shopping cart to current user
                        var ui = MembershipContext.AuthenticatedUser;
                        if (!ui.IsPublic())
                        {
                            ShoppingCart.User = ui;
                            updateCart = true;
                        }

                        // Shopping cart is not saved yet
                        if (ShoppingCart.ShoppingCartID == 0)
                        {
                            updateCart = true;
                        }

                        // Update shopping cart when required
                        if (updateCart)
                        {
                            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                        }

                        // Set item in the shopping cart
                        ShoppingCartItemInfo product = ShoppingCart.SetShoppingCartItem(itemParams);

                        // Update shopping cart item in database
                        ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(product);

                        // Update product options in database
                        foreach (ShoppingCartItemInfo option in product.ProductOptions)
                        {
                            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(option);
                        }

                        // Update bundle items in database
                        foreach (ShoppingCartItemInfo bundleItem in product.BundleItems)
                        {
                            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(bundleItem);
                        }

                        // Track add to shopping cart conversion
                        ECommerceHelper.TrackAddToShoppingCartConversion(product);
                    }
                    // In CMSDesk
                    else
                    {
                        // Set item in the shopping cart
                        ShoppingCart.SetShoppingCartItem(itemParams);
                    }
                }
            }

            // Avoid adding the same product after page refresh
            if (lblError.Text == "")
            {
                string url = RequestContext.CurrentURL;

                if (!string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "productid")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "quantity")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "options")))
                {
                    // Remove parameters from URL
                    url = URLHelper.RemoveParameterFromUrl(url, "productid");
                    url = URLHelper.RemoveParameterFromUrl(url, "quantity");
                    url = URLHelper.RemoveParameterFromUrl(url, "options");
                    URLHelper.Redirect(url);
                }
            }
        }
    }
    /// <summary>
    /// Updates shopping cart item units. Called when the "Update itewm units" button is pressed.
    /// Expects the AddProductToShoppingCart methods to be run first.
    /// </summary>
    private bool UpdateShoppingCartItemUnits()
    {
        // Prepare the parameters
        string where = "SKUName LIKE N'MyNewProduct%' AND SKUOptionCategoryID IS NULL";
        SKUInfo product = null;

        // Get the data
        DataSet products = SKUInfoProvider.GetSKUs(where, null);
        if (!DataHelper.DataSourceIsEmpty(products))
        {
            // Create object from DataRow
            product = new SKUInfo(products.Tables[0].Rows[0]);
        }

        if (product != null)
        {
            ShoppingCartItemInfo item = null;

            // Get current shopping cart
            ShoppingCartInfo cart = ECommerceContext.CurrentShoppingCart;

            // Loop through the individual items
            foreach (ShoppingCartItemInfo cartItem in cart.CartItems)
            {
                if (cartItem.SKUID == product.SKUID)
                {
                    // Remember found item
                    item = cartItem;
                    break;
                }
            }

            if (item != null)
            {
                // Update item
                ShoppingCartItemParameters param = new ShoppingCartItemParameters(product.SKUID, 2);
                item = cart.SetShoppingCartItem(param);

                // Ensure cart in database
                ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

                // Update item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(item);

                return true;
            }

            return false;
        }

        return false;
    }
    /// <summary>
    /// Adds product to shopping cart. Called when the "Add product to shopping cart" button is pressed.
    /// Expects the CreateProduct method to be run first.
    /// </summary>
    private bool AddProductToShoppingCart()
    {
        // Prepare the parameters
        string where = "SKUName LIKE N'MyNewProduct%' AND SKUOptionCategoryID IS NULL";
        SKUInfo product = null;

        // Get the data
        DataSet products = SKUInfoProvider.GetSKUs(where, null);
        if (!DataHelper.DataSourceIsEmpty(products))
        {
            // Create object from DataRow
            product = new SKUInfo(products.Tables[0].Rows[0]);
        }

        if (product != null)
        {
            // Get current shopping cart
            ShoppingCartInfo cart = ECommerceContext.CurrentShoppingCart;

            // Ensure cart in database
            ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

            // Add item to cart object
            ShoppingCartItemParameters param = new ShoppingCartItemParameters(product.SKUID, 1);
            ShoppingCartItemInfo cartItem = cart.SetShoppingCartItem(param);

            // Save item to database
            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);

            return true;
        }

        return false;
    }
    /// <summary>
    /// Adds product to shopping cart. Called when the "Add product to shopping cart" button is pressed.
    /// Expects the CreateProduct method to be run first.
    /// </summary>
    private bool AddProductToShoppingCart()
    {
        // Get the data
        var product = SKUInfoProvider.GetSKUs()
                           .WhereStartsWith("SKUName", "MyNewProduct")
                           .WhereNull("SKUOptionCategoryID")
                           .FirstOrDefault();

        if (product != null)
        {
            // Get current shopping cart
            ShoppingCartInfo cart = ECommerceContext.CurrentShoppingCart;

            // Ensure cart in database
            ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

            // Add item to cart object
            ShoppingCartItemParameters param = new ShoppingCartItemParameters(product.SKUID, 1);
            ShoppingCartItemInfo cartItem = cart.SetShoppingCartItem(param);

            // Save item to database
            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);

            return true;
        }

        return false;
    }
        public List<ShoppingCartItemParameters> GetSelectedOptionsParameters()
        {
            List<ShoppingCartItemParameters> options = new List<ShoppingCartItemParameters>();
            ShoppingCartItemParameters param = null;

            if (this.SelectionControl != null)
            {
                // Dropdown list, Radiobutton list - single selection
                if ((this.SelectionControl.GetType() == typeof(LocalizedDropDownList)) ||
                    (this.SelectionControl.GetType() == typeof(LocalizedRadioButtonList)))
                {
                    param = new ShoppingCartItemParameters();
                    param.SKUID = ValidationHelper.GetInteger(((ListControl)this.SelectionControl).SelectedValue, 0);

                    if (param.SKUID > 0)
                    {
                        options.Add(param);
                    }
                }
                // Checkbox list - multiple selection
                else if (this.SelectionControl.GetType() == typeof(LocalizedCheckBoxList))
                {
                    foreach (ListItem item in ((CheckBoxList)this.SelectionControl).Items)
                    {
                        if (item.Selected)
                        {
                            param = new ShoppingCartItemParameters();
                            param.SKUID = ValidationHelper.GetInteger(item.Value, 0);

                            if (param.SKUID > 0)
                            {
                                options.Add(param);
                            }
                        }
                    }
                }
                else if (this.SelectionControl is TextBox)
                {
                    // Bind data
                    if (this.SelectionControl is TextBoxWithLabel)
                    {
                        if (TextOptionSKUID > 0)
                        {
                            param = new ShoppingCartItemParameters();
                            param.SKUID = TextOptionSKUID;
                            param.Text = ((TextBox)(this.SelectionControl)).Text;
                            if (param.SKUID > 0)
                            {
                                options.Add(param);
                            }
                        }
                    }
                }
            }

            return options;
        }
        public List<ShoppingCartItemParameters> GetSelectedOptionsParameters()
        {
            List<ShoppingCartItemParameters> options = new List<ShoppingCartItemParameters>();
            ShoppingCartItemParameters param = null;

            if (SelectionControl != null)
            {
                // Dropdown list, Radiobutton list - single selection
                if ((SelectionControl.GetType() == typeof(LocalizedDropDownList)) ||
                    (SelectionControl.GetType() == typeof(LocalizedRadioButtonList)))
                {
                    param = new ShoppingCartItemParameters();
                    param.SKUID = ValidationHelper.GetInteger(((ListControl)SelectionControl).SelectedValue, 0);

                    if (param.SKUID > 0)
                    {
                        options.Add(param);
                    }
                }
                // Checkbox list - multiple selection
                else if (SelectionControl.GetType() == typeof(LocalizedCheckBoxList))
                {
                    foreach (ListItem item in ((CheckBoxList)SelectionControl).Items)
                    {
                        if (item.Selected)
                        {
                            param = new ShoppingCartItemParameters();
                            param.SKUID = ValidationHelper.GetInteger(item.Value, 0);

                            if (param.SKUID > 0)
                            {
                                options.Add(param);
                            }
                        }
                    }
                }
                else if (SelectionControl is TextBox)
                {
                    // Bind data
                    if (SelectionControl is TextBoxWithLabel)
                    {
                        if (TextOptionSKUID > 0)
                        {
                            param = new ShoppingCartItemParameters();
                            param.SKUID = TextOptionSKUID;
                            param.Text = ((TextBox)(SelectionControl)).Text;
                            if (param.SKUID > 0)
                            {
                                options.Add(param);
                            }
                        }
                    }
                }
                else if (SelectionControl is FormEngineUserControl)
                {
                    FormEngineUserControl fc = SelectionControl as FormEngineUserControl;

                    string val = ValidationHelper.GetString(fc.Value, string.Empty);
                    int[] optionsIds = ValidationHelper.GetIntegers(val.Split(','), 0);

                    // Add selected options to parameters
                    foreach (int id in optionsIds)
                    {
                        if (id > 0)
                        {
                            param = new ShoppingCartItemParameters();
                            param.SKUID = id;
                            options.Add(param);
                        }
                    }

                }
            }

            return options;
        }
    /// <summary>
    /// Updates shopping cart item units. Called when the "Update itewm units" button is pressed.
    /// Expects the AddProductToShoppingCart methods to be run first.
    /// </summary>
    private bool UpdateShoppingCartItemUnits()
    {
        // Get the data
        var product = SKUInfoProvider.GetSKUs()
                           .WhereStartsWith("SKUName", "MyNewProduct")
                           .WhereNull("SKUOptionCategoryID")
                           .FirstOrDefault();

        if (product != null)
        {

            ShoppingCartItemInfo item = null;

            // Get current shopping cart
            ShoppingCartInfo cart = ECommerceContext.CurrentShoppingCart;

            // Loop through the individual items
            foreach (var cartItem in cart.CartItems)
            {
                if (cartItem.SKUID == product.SKUID)
                {
                    // Remember found item
                    item = cartItem;
                    break;
                }
            }

            if (item != null)
            {
                // Update item
                ShoppingCartItemParameters param = new ShoppingCartItemParameters(product.SKUID, 2);
                item = cart.SetShoppingCartItem(param);

                // Ensure cart in database
                ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

                // Update item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(item);

                return true;
            }

            return false;
        }

        return false;
    }
    /// <summary>
    /// Returns selected shopping cart item parameters containig product option parameters.
    /// </summary>
    public ShoppingCartItemParameters GetShoppingCartItemParameters()
    {
        // Get product options
        List<ShoppingCartItemParameters> options = ProductOptionsParameters;

        // Create params
        ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(SKUID, Quantity, options);

        // Ensure minimum allowed number of items is met
        if (SKU.SKUMinItemsInOrder > Quantity)
        {
            cartItemParams.Quantity = SKU.SKUMinItemsInOrder;
        }

        if (donationProperties.Visible || !RedirectToDetailsEnabled)
        {
            // Get exchange rate from cart currency to site main currency
            double rate = (SKU.IsGlobal) ? ShoppingCart.ExchangeRateForGlobalItems : ShoppingCart.ExchangeRate;

            // Set donation specific shopping cart item parameters
            cartItemParams.IsPrivate = donationProperties.DonationIsPrivate;

            // Get donation amount in site main currency
            cartItemParams.Price = ExchangeRateInfoProvider.ApplyExchangeRate(donationProperties.DonationAmount, 1 / rate);
        }

        return cartItemParams;
    }
    public ShoppingCartItemParameters GetShoppingCartItemParameters()
    {
        int Quantity = 1;
        //int SKUID  -> got from drop down
        double price = ValidationHelper.GetDouble(txtDonationAmount.Text, 0.00);

        List<ShoppingCartItemParameters> options = new List<ShoppingCartItemParameters>();

        // Create params
        ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(SKUID, Quantity, options);

        // Ensure minimum allowed number of items is met
        if (SKU.SKUMinItemsInOrder > Quantity)
        {
            cartItemParams.Quantity = SKU.SKUMinItemsInOrder;
        }

        //    // Get exchange rate from cart currency to site main currency
        double rate = (SKU.IsGlobal) ? ShoppingCart.ExchangeRateForGlobalItems : ShoppingCart.ExchangeRate;

        //    // Set donation specific shopping cart item parameters
        //    cartItemParams.IsPrivate = donationProperties.DonationIsPrivate;

        //    // Get donation amount in site main currency
        cartItemParams.Price = ExchangeRateInfoProvider.ApplyExchangeRate(price, 1 / rate);
        return cartItemParams;
    }
    /// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shopping cart item parameters</param>
    protected void AddProducts(ShoppingCartItemParameters itemParams)
    {
        // Get main product info
        int productId = itemParams.SKUID;
        int quantity  = itemParams.Quantity;

        if ((productId > 0) && (quantity > 0))
        {
            // Check product/options combination
            if (ShoppingCartInfoProvider.CheckNewShoppingCartItems(ShoppingCart, itemParams))
            {
                // Get requested SKU info object from database
                SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(productId);
                if (skuObj != null)
                {
                    // On the live site
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        bool updateCart = false;

                        // Assign current shopping cart to current user
                        var ui = MembershipContext.AuthenticatedUser;
                        if (!ui.IsPublic())
                        {
                            ShoppingCart.User = ui;
                            updateCart        = true;
                        }

                        // Shopping cart is not saved yet
                        if (ShoppingCart.ShoppingCartID == 0)
                        {
                            updateCart = true;
                        }

                        // Update shopping cart when required
                        if (updateCart)
                        {
                            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                        }

                        // Set item in the shopping cart
                        ShoppingCartItemInfo product = ShoppingCart.SetShoppingCartItem(itemParams);

                        // Update shopping cart item in database
                        ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(product);

                        // Update product options in database
                        foreach (ShoppingCartItemInfo option in product.ProductOptions)
                        {
                            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(option);
                        }

                        // Update bundle items in database
                        foreach (ShoppingCartItemInfo bundleItem in product.BundleItems)
                        {
                            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(bundleItem);
                        }

                        // Track add to shopping cart conversion
                        ECommerceHelper.TrackAddToShoppingCartConversion(product);
                    }
                    // In CMSDesk
                    else
                    {
                        // Set item in the shopping cart
                        ShoppingCart.SetShoppingCartItem(itemParams);
                    }
                }
            }

            // Avoid adding the same product after page refresh
            if (lblError.Text == "")
            {
                string url = RequestContext.CurrentURL;

                if (!string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "productid")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "quantity")) ||
                    !string.IsNullOrEmpty(URLHelper.GetUrlParameter(url, "options")))
                {
                    // Remove parameters from URL
                    url = URLHelper.RemoveParameterFromUrl(url, "productid");
                    url = URLHelper.RemoveParameterFromUrl(url, "quantity");
                    url = URLHelper.RemoveParameterFromUrl(url, "options");
                    URLHelper.Redirect(url);
                }
            }
        }
    }
    protected override void OnLoad(EventArgs e)
    {
        // Show message when reordering and not all reordered product were added to cart
        if (!RequestHelper.IsPostBack() && QueryHelper.GetBoolean("notallreordered", false))
        {
            lblError.Text = GetString("com.notallreordered");
        }

        if ((ShoppingCart != null) && IsLiveSite)
        {
            // Get order information
            OrderInfo oi = OrderInfoProvider.GetOrderInfo(ShoppingCart.OrderId);
            // If order is paid
            if ((oi != null) && (oi.OrderIsPaid))
            {
                // Clean shopping cart if paid order cart is still in customers current cart on LS
                ShoppingCartControl.CleanUpShoppingCart();
            }
        }

        if (ShoppingCart != null)
        {
            // Set currency selectors site ID
            selectCurrency.SiteID = ShoppingCart.ShoppingCartSiteID;
        }

        lnkNewItem.Text        = GetString("ecommerce.shoppingcartcontent.additem");
        btnUpdate.Text         = GetString("ecommerce.shoppingcartcontent.btnupdate");
        btnEmpty.Text          = GetString("ecommerce.shoppingcartcontent.btnempty");
        btnEmpty.OnClientClick = string.Format("return confirm({0});", ScriptHelper.GetString(GetString("ecommerce.shoppingcartcontent.emptyconfirm")));

        // Add new product dialog
        string addProductUrl = ApplicationUrlHelper.GetElementDialogUrl(ModuleName.ECOMMERCE, "order.addorderitems", 0, GetCMSDeskShoppingCartSessionNameQuery());

        lnkNewItem.OnClientClick = ScriptHelper.GetModalDialogScript(addProductUrl, "addproduct", 1000, 620);

        gridData.Columns[4].HeaderText  = GetString("general.remove");
        gridData.Columns[5].HeaderText  = GetString("ecommerce.shoppingcartcontent.actions");
        gridData.Columns[6].HeaderText  = GetString("ecommerce.shoppingcartcontent.skuname");
        gridData.Columns[7].HeaderText  = GetString("ecommerce.shoppingcartcontent.skuunits");
        gridData.Columns[8].HeaderText  = GetString("ecommerce.shoppingcartcontent.unitprice");
        gridData.Columns[9].HeaderText  = GetString("ecommerce.shoppingcartcontent.itemdiscount");
        gridData.Columns[10].HeaderText = GetString("ecommerce.shoppingcartcontent.subtotal");
        gridData.RowDataBound          += gridData_RowDataBound;

        // Hide "add product" action for live site order
        if (!ShoppingCartControl.IsInternalOrder)
        {
            pnlNewItem.Visible = false;

            ShoppingCartControl.ButtonBack.Text        = GetString("ecommerce.cartcontent.buttonbacktext");
            ShoppingCartControl.ButtonBack.ButtonStyle = ButtonStyle.Default;
            ShoppingCartControl.ButtonNext.Text        = GetString("ecommerce.cartcontent.buttonnexttext");

            if (!ShoppingCartControl.IsCurrentStepPostBack)
            {
                // Get shopping cart item parameters from URL
                ShoppingCartItemParameters itemParams = ShoppingCartItemParameters.GetShoppingCartItemParameters();

                // Set item in the shopping cart
                AddProducts(itemParams);
            }
        }

        // Set sending order notification when editing existing order according to the site settings
        if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
        {
            if (!ShoppingCartControl.IsCurrentStepPostBack)
            {
                if (!string.IsNullOrEmpty(ShoppingCart.SiteName))
                {
                    chkSendEmail.Checked = ECommerceSettings.SendOrderNotification(ShoppingCart.SiteName);
                }
            }
            // Show send email checkbox
            chkSendEmail.Visible = true;
            chkSendEmail.Text    = GetString("shoppingcartcontent.sendemail");

            // Setup buttons
            ShoppingCartControl.ButtonBack.Visible = false;
            ShoppingCartControl.ButtonNext.Text    = GetString("general.next");

            if ((!ExistAnotherStepsExceptPayment) && (ShoppingCartControl.PaymentGatewayProvider == null))
            {
                ShoppingCartControl.ButtonNext.Text = GetString("general.ok");
            }
        }

        // Fill dropdownlist
        if (!ShoppingCartControl.IsCurrentStepPostBack)
        {
            if (!ShoppingCart.IsEmpty || ShoppingCartControl.IsInternalOrder)
            {
                selectCurrency.SelectedID = ShoppingCart.ShoppingCartCurrencyID;
            }

            ReloadData();
        }

        // Ensure order currency in selector
        if ((ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) && (ShoppingCart.Order != null))
        {
            selectCurrency.AdditionalItems += ShoppingCart.Order.OrderCurrencyID + ";";
        }

        HandlePostBack();

        base.OnLoad(e);
    }
    private void btnAddProduct_Click(object sender, EventArgs e)
    {
        // Do not add item if order is paid
        if (OrderIsPaid)
        {
            return;
        }

        // Get strings with productIDs and quantities separated by ';'
        string productIDs = ValidationHelper.GetString(hidProductID.Value, "");
        string quantities = ValidationHelper.GetString(hidQuantity.Value, "");
        string options    = ValidationHelper.GetString(hidOptions.Value, "");
        double price      = ValidationHelper.GetDouble(hdnPrice.Value, -1);
        bool   isPrivate  = ValidationHelper.GetBoolean(hdnIsPrivate.Value, false);

        // Add new products to shopping cart
        if ((productIDs != "") && (quantities != ""))
        {
            int[] arrID      = ValidationHelper.GetIntegers(productIDs.TrimEnd(';').Split(';'), 0);
            int[] arrQuant   = ValidationHelper.GetIntegers(quantities.TrimEnd(';').Split(';'), 0);
            int[] intOptions = ValidationHelper.GetIntegers(options.Split(','), 0);

            // Check site binding
            if (!CheckSiteBinding(arrID) || !CheckSiteBinding(intOptions))
            {
                return;
            }

            lblError.Text = "";

            for (int i = 0; i < arrID.Length; i++)
            {
                int skuId = arrID[i];

                SKUInfo skuInfo = SKUInfoProvider.GetSKUInfo(skuId);
                if ((skuInfo != null) && !skuInfo.IsProductOption)
                {
                    int quantity = arrQuant[i];

                    ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, quantity, intOptions);

                    // If product is donation
                    if (skuInfo.SKUProductType == SKUProductTypeEnum.Donation)
                    {
                        // Get donation properties
                        if (price < 0)
                        {
                            cartItemParams.Price = SKUInfoProvider.GetSKUPrice(skuInfo, ShoppingCart, false, false);
                        }
                        else
                        {
                            cartItemParams.Price = price;
                        }

                        cartItemParams.IsPrivate = isPrivate;
                    }

                    // Add product to the shopping cart
                    ShoppingCart.SetShoppingCartItem(cartItemParams);

                    // Log activity
                    string siteName = SiteContext.CurrentSiteName;
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        ShoppingCartControl.TrackActivityProductAddedToShoppingCart(skuId, ResHelper.LocalizeString(skuInfo.SKUName), ContactID, siteName, RequestContext.CurrentRelativePath, quantity);
                    }

                    // Show empty button
                    btnEmpty.Visible = true;
                }
            }
        }

        // Invalidate values
        hidProductID.Value = "";
        hidOptions.Value   = "";
        hidQuantity.Value  = "";
        hdnPrice.Value     = "";

        // Update values in table
        btnUpdate_Click1(btnAddProduct, e);

        // Hide cart content when empty
        if (DataHelper.DataSourceIsEmpty(ShoppingCart.ContentTable))
        {
            HideCartContent();
        }
        else
        {
            // Inventory should be checked
            checkInventory = true;
        }
    }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        // Validate input data
        if (!IsValid() || (SKU == null))
        {
            // Do not proces
            return;
        }

        if (RedirectToDetailsEnabled)
        {
            if (!ShowProductOptions && !ShowDonationProperties)
            {
                // Does product have some enabled product option categories?
                bool hasOptions = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetSKUOptionCategories(SKUID, true));

                // Is product a customizable donation?
                bool isCustomizableDonation = ((SKU != null) &&
                                               (SKU.SKUProductType == SKUProductTypeEnum.Donation) &&
                                               (!((SKU.SKUPrice == SKU.SKUMinPrice) && (SKU.SKUPrice == SKU.SKUMaxPrice)) || SKU.SKUPrivateDonation));

                if (hasOptions || isCustomizableDonation)
                {
                    // Redirect to product details
                    URLHelper.Redirect("~/CMSPages/GetProduct.aspx?productid=" + SKUID);
                }
            }
        }

        // Get cart item parameters
        ShoppingCartItemParameters cartItemParams = GetShoppingCartItemParameters();

        string error = null;

        // Check if customer is enabled
        if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled))
        {
            error = GetString("ecommerce.cartcontent.customerdisabled");
        }

        // Check if it is possible to add this item to shopping cart
        if ((error == null) && !ShoppingCartInfoProvider.CheckNewShoppingCartItems(ShoppingCart, cartItemParams))
        {
            error = String.Format(GetString("ecommerce.cartcontent.productdisabled"), SKU.SKUName);
        }

        if (!string.IsNullOrEmpty(error))
        {
            // Show error message and cancel adding the product to shopping cart
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

        // If donation properties are used and donation properties form is not valid
        if (donationProperties.Visible && !String.IsNullOrEmpty(donationProperties.Validate()))
        {
            return;
        }

        // Fire on add to shopping cart event
        CancelEventArgs eventArgs = new CancelEventArgs();

        if (OnAddToShoppingCart != null)
        {
            OnAddToShoppingCart(this, eventArgs);
        }

        // If adding to shopping cart was cancelled
        if (eventArgs.Cancel)
        {
            return;
        }

        // Get cart item parameters in case something changed
        cartItemParams = GetShoppingCartItemParameters();

        // Log activity
        LogProductAddedToSCActivity(SKUID, SKU.SKUName, Quantity);

        if (ShoppingCart != null)
        {
            bool updateCart = false;

            // Assign current shopping cart to current user
            CurrentUserInfo ui = CMSContext.CurrentUser;
            if (!ui.IsPublic())
            {
                ShoppingCart.User = ui;
                updateCart        = true;
            }

            // Shopping cart is not saved yet
            if (ShoppingCart.ShoppingCartID == 0)
            {
                updateCart = true;
            }

            // Update shopping cart when required
            if (updateCart)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            // Add item to shopping cart
            ShoppingCartItemInfo addedItem = ShoppingCart.SetShoppingCartItem(cartItemParams);

            if (addedItem != null)
            {
                // Update shopping cart item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(addedItem);

                // Update product options in database
                foreach (ShoppingCartItemInfo option in addedItem.ProductOptions)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(option);
                }

                // Update bundle items in database
                foreach (ShoppingCartItemInfo bundleItem in addedItem.BundleItems)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(bundleItem);
                }

                // Track 'Add to shopping cart' conversion
                ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);

                // If user has to be redirected to shopping cart
                if (RedirectToShoppingCart)
                {
                    // Set shopping cart referrer
                    SessionHelper.SetValue("ShoppingCartUrlReferrer", URLHelper.CurrentURL);

                    // Ensure shopping cart update
                    SessionHelper.SetValue("checkinventory", true);

                    // Redirect to shopping cart
                    URLHelper.Redirect(ShoppingCartUrl);
                }
                else
                {
                    // Localize SKU name
                    string skuName = (addedItem.SKU != null) ? ResHelper.LocalizeString(addedItem.SKU.SKUName) : "";

                    // Check inventory
                    ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);
                    string checkInventoryMessage        = checkResult.GetFormattedMessage();

                    // Get prodcut added message
                    string message = String.Format(GetString("com.productadded"), skuName);

                    // Add inventory check message
                    if (!String.IsNullOrEmpty(checkInventoryMessage))
                    {
                        message += "\n\n" + checkInventoryMessage;
                    }

                    // Count and show total price with options
                    CalculateTotalPrice();

                    // Register the call of JS handler informing about added product
                    ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
                }
            }
        }
    }
    protected override void OnLoad(EventArgs e)
    {
        lblTitle.Text = GetString("shoppingcart.cartcontent");

        if ((ShoppingCart != null) && (ShoppingCart.CountryID == 0) && (SiteContext.CurrentSite != null))
        {
            string      countryName = ECommerceSettings.DefaultCountryName(SiteContext.CurrentSite.SiteName);
            CountryInfo ci          = CountryInfoProvider.GetCountryInfo(countryName);
            ShoppingCart.CountryID = (ci != null) ? ci.CountryID : 0;

            // Set currency selectors site ID
            selectCurrency.SiteID = ShoppingCart.ShoppingCartSiteID;
        }

        imgNewItem.ImageUrl      = GetImageUrl("Objects/Ecommerce_OrderItem/add.png");
        lblCurrency.Text         = GetString("ecommerce.shoppingcartcontent.currency");
        lblCoupon.Text           = GetString("ecommerce.shoppingcartcontent.coupon");
        lnkNewItem.Text          = GetString("ecommerce.shoppingcartcontent.additem");
        imgNewItem.AlternateText = lnkNewItem.Text;
        btnUpdate.Text           = GetString("ecommerce.shoppingcartcontent.btnupdate");
        btnEmpty.Text            = GetString("ecommerce.shoppingcartcontent.btnempty");
        btnEmpty.OnClientClick   = string.Format("return confirm({0});", ScriptHelper.GetString(GetString("ecommerce.shoppingcartcontent.emptyconfirm")));
        lnkNewItem.OnClientClick = string.Format("OpenAddProductDialog('{0}');return false;", GetCMSDeskShoppingCartSessionName());

        gridData.Columns[4].HeaderText  = GetString("general.remove");
        gridData.Columns[5].HeaderText  = GetString("ecommerce.shoppingcartcontent.actions");
        gridData.Columns[6].HeaderText  = GetString("ecommerce.shoppingcartcontent.skuname");
        gridData.Columns[7].HeaderText  = GetString("ecommerce.shoppingcartcontent.skuunits");
        gridData.Columns[8].HeaderText  = GetString("ecommerce.shoppingcartcontent.unitprice");
        gridData.Columns[9].HeaderText  = GetString("ecommerce.shoppingcartcontent.unitdiscount");
        gridData.Columns[10].HeaderText = GetString("ecommerce.shoppingcartcontent.tax");
        gridData.Columns[11].HeaderText = GetString("ecommerce.shoppingcartcontent.subtotal");
        gridData.RowDataBound          += new GridViewRowEventHandler(gridData_RowDataBound);

        // Register product price detail dialog script
        StringBuilder script = new StringBuilder();

        script.Append("function ShowProductPriceDetail(cartItemGuid, sessionName) {");
        script.Append("if (sessionName != \"\"){sessionName =  \"&cart=\" + sessionName;}");
        string detailUrl = (IsLiveSite) ? "~/CMSModules/Ecommerce/CMSPages/ShoppingCartSKUPriceDetail.aspx" : "~/CMSModules/Ecommerce/Controls/ShoppingCart/ShoppingCartSKUPriceDetail.aspx";

        script.Append(string.Format("modalDialog('{0}?itemguid=' + cartItemGuid + sessionName, 'ProductPriceDetail', 750, 500); }}", ResolveUrl(detailUrl)));
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ProductPriceDetail", ScriptHelper.GetScript(script.ToString()));

        // Register add order item dialog script
        script = new StringBuilder();
        script.Append("function OpenOrderItemDialog(cartItemGuid, sessionName) {");
        script.Append("if (sessionName != \"\"){sessionName =  \"&cart=\" + sessionName;}");
        script.Append(string.Format("modalDialog('{0}?itemguid=' + cartItemGuid + sessionName, 'OrderItemEdit', 500, 350); }}", ResolveUrl("~/CMSModules/Ecommerce/Controls/ShoppingCart/OrderItemEdit.aspx")));
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "OrderItemEdit", ScriptHelper.GetScript(script.ToString()));

        script = new StringBuilder();
        string addProductUrl = AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Ecommerce/Pages/Tools/Orders/Order_Edit_AddItems.aspx");

        script.AppendFormat("var addProductDialogURL = '{0}'", URLHelper.GetAbsoluteUrl(addProductUrl));
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "AddProduct", ScriptHelper.GetScript(script.ToString()));


        // Hide "add product" action for live site order
        if (!ShoppingCartControl.IsInternalOrder)
        {
            pnlNewItem.Visible = false;

            ShoppingCartControl.ButtonBack.Text     = GetString("ecommerce.cartcontent.buttonbacktext");
            ShoppingCartControl.ButtonBack.CssClass = "LongButton";
            ShoppingCartControl.ButtonNext.Text     = GetString("ecommerce.cartcontent.buttonnexttext");

            if (!ShoppingCartControl.IsCurrentStepPostBack)
            {
                // Get shopping cart item parameters from URL
                ShoppingCartItemParameters itemParams = ShoppingCartItemParameters.GetShoppingCartItemParameters();

                // Set item in the shopping cart
                AddProducts(itemParams);
            }
        }

        // Set sending order notification when editing existing order according to the site settings
        if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
        {
            if (!ShoppingCartControl.IsCurrentStepPostBack)
            {
                if (!string.IsNullOrEmpty(ShoppingCart.SiteName))
                {
                    chkSendEmail.Checked = ECommerceSettings.SendOrderNotification(ShoppingCart.SiteName);
                }
            }
            // Show send email checkbox
            chkSendEmail.Visible = true;
            chkSendEmail.Text    = GetString("shoppingcartcontent.sendemail");

            // Setup buttons
            ShoppingCartControl.ButtonBack.Visible = false;
            ShoppingCart.CheckAvailableItems       = false;
            ShoppingCartControl.ButtonNext.Text    = GetString("general.next");

            if ((!ExistAnotherStepsExceptPayment) && (ShoppingCartControl.PaymentGatewayProvider == null))
            {
                ShoppingCartControl.ButtonNext.Text = GetString("general.ok");
            }
        }

        // Fill dropdownlist
        if (!ShoppingCartControl.IsCurrentStepPostBack)
        {
            if ((ShoppingCart.CartItems.Count > 0) || ShoppingCartControl.IsInternalOrder)
            {
                if (ShoppingCart.ShoppingCartCurrencyID == 0)
                {
                    // Select customer preferred currency
                    if (ShoppingCart.Customer != null)
                    {
                        CustomerInfo customer = ShoppingCart.Customer;
                        ShoppingCart.ShoppingCartCurrencyID = (customer.CustomerUser != null) ? customer.CustomerUser.GetUserPreferredCurrencyID(SiteContext.CurrentSiteName) : 0;
                    }
                }

                if (ShoppingCart.ShoppingCartCurrencyID == 0)
                {
                    if (SiteContext.CurrentSite != null)
                    {
                        ShoppingCart.ShoppingCartCurrencyID = SiteContext.CurrentSite.SiteDefaultCurrencyID;
                    }
                }

                selectCurrency.CurrencyID = ShoppingCart.ShoppingCartCurrencyID;

                if (ShoppingCart.ShoppingCartDiscountCouponID > 0)
                {
                    // Fill textbox with discount coupon code
                    DiscountCouponInfo dci = DiscountCouponInfoProvider.GetDiscountCouponInfo(ShoppingCart.ShoppingCartDiscountCouponID);
                    if (dci != null)
                    {
                        if (ShoppingCart.IsCreatedFromOrder || dci.IsValid)
                        {
                            txtCoupon.Text = dci.DiscountCouponCode;
                        }
                        else
                        {
                            ShoppingCart.ShoppingCartDiscountCouponID = 0;
                        }
                    }
                }
            }

            ReloadData();
        }

        // Check if customer is enabled
        if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled))
        {
            HideCartContent(GetString("ecommerce.cartcontent.customerdisabled"));
        }

        // Turn on available items checking after content is loaded
        ShoppingCart.CheckAvailableItems = true;

        base.OnLoad(e);
    }
    private void btnAddProduct_Click(object sender, EventArgs e)
    {
        // Do not add item if order is paid
        if (OrderIsPaid)
        {
            return;
        }

        // Get strings with productIDs and quantities separated by ';'
        string productIDs = ValidationHelper.GetString(hidProductID.Value, "");
        string quantities = ValidationHelper.GetString(hidQuantity.Value, "");
        string options = ValidationHelper.GetString(hidOptions.Value, "");
        double price = ValidationHelper.GetDouble(hdnPrice.Value, -1);
        bool isPrivate = ValidationHelper.GetBoolean(hdnIsPrivate.Value, false);

        // Add new products to shopping cart
        if ((productIDs != "") && (quantities != ""))
        {
            int[] arrID = ValidationHelper.GetIntegers(productIDs.TrimEnd(';').Split(';'), 0);
            int[] arrQuant = ValidationHelper.GetIntegers(quantities.TrimEnd(';').Split(';'), 0);
            int[] intOptions = ValidationHelper.GetIntegers(options.Split(','), 0);

            // Check site binding
            if (!CheckSiteBinding(arrID) || !CheckSiteBinding(intOptions))
            {
                return;
            }

            lblError.Text = "";

            for (int i = 0; i < arrID.Length; i++)
            {
                int skuId = arrID[i];

                SKUInfo skuInfo = SKUInfoProvider.GetSKUInfo(skuId);
                if ((skuInfo != null) && !skuInfo.IsProductOption)
                {
                    int quantity = arrQuant[i];

                    ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, quantity, intOptions);

                    // If product is donation
                    if (skuInfo.SKUProductType == SKUProductTypeEnum.Donation)
                    {
                        // Get donation properties
                        if (price < 0)
                        {
                            cartItemParams.Price = SKUInfoProvider.GetSKUPrice(skuInfo, ShoppingCart, false, false);
                        }
                        else
                        {
                            cartItemParams.Price = price;
                        }

                        cartItemParams.IsPrivate = isPrivate;
                    }

                    // Add product to the shopping cart
                    ShoppingCart.SetShoppingCartItem(cartItemParams);

                    // Log activity
                    string siteName = SiteContext.CurrentSiteName;
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        ShoppingCartControl.TrackActivityProductAddedToShoppingCart(skuId, ResHelper.LocalizeString(skuInfo.SKUName), ContactID, siteName, RequestContext.CurrentRelativePath, quantity);
                    }

                    // Show empty button
                    btnEmpty.Visible = true;
                }
            }
        }

        // Invalidate values
        hidProductID.Value = "";
        hidOptions.Value = "";
        hidQuantity.Value = "";
        hdnPrice.Value = "";

        // Update values in table
        btnUpdate_Click1(btnAddProduct, e);

        // Hide cart content when empty
        if (DataHelper.DataSourceIsEmpty(ShoppingCart.ContentTable))
        {
            HideCartContent();
        }
        else
        {
            // Inventory should be checked
            checkInventory = true;
        }
    }
    /// <summary>
    /// Returns selected shopping cart item parameters containig product option parameters.
    /// </summary>
    public ShoppingCartItemParameters GetShoppingCartItemParameters()
    {
        // Get product options
        List<ShoppingCartItemParameters> options = this.ProductOptionsParameters;

        // Create params
        ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(this.SKUID, this.Quantity, options);

        if (this.donationProperties.Visible || !this.RedirectToDetailsEnabled)
        {
            // Get exchange rate from cart currency to site main currency
            double rate = (this.SKU.IsGlobal) ? this.ShoppingCart.ExchangeRateForGlobalItems : this.ShoppingCart.ExchangeRate;

            // Set donation specific shopping cart item parameters
            cartItemParams.IsPrivate = this.donationProperties.DonationIsPrivate;

            // Get donation amount in site main currency
            cartItemParams.Price = ExchangeRateInfoProvider.ApplyExchangeRate(this.donationProperties.DonationAmount, 1 / rate);
        }

        return cartItemParams;
    }
    /// <summary>
    /// Returns selected shopping cart item parameters containing product option parameters.
    /// </summary>
    public ShoppingCartItemParameters GetShoppingCartItemParameters()
    {
        // Get product options
        List<ShoppingCartItemParameters> options;
        int skuId = SKUID;

        if ((SelectedVariant != null) && (Variants.Count != 0))
        {
            skuId = SelectedVariant.Variant.SKUID;
            options = ProductOptionsParametersNonVariant;
        }
        else
        {
            // Get product options
            options = ProductOptionsParameters;
        }
        // Create params
        ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, Quantity, options);

        // Ensure minimum allowed number of items is met
        if (SKU.SKUMinItemsInOrder > Quantity)
        {
            cartItemParams.Quantity = SKU.SKUMinItemsInOrder;
        }

        // Handle Donation custom price
        if (SKU.SKUProductType == SKUProductTypeEnum.Donation)
        {
            // Donation price in case of donating through standard SKU listing/detail
            double donationPrice = SKUInfoProvider.GetSKUPrice(SKU, ShoppingCart);
            // Donation price in case of donating through donationProperties control
            if (donationProperties.Visible || !RedirectToDetailsEnabled)
            {
                // Set donation specific shopping cart item parameters
                cartItemParams.IsPrivate = donationProperties.DonationIsPrivate;
                // Get exchange rate from cart currency to site main currency
                double rate = (SKU.IsGlobal) ? ShoppingCart.ExchangeRateForGlobalItems : ShoppingCart.ExchangeRate;
                donationPrice = ExchangeRateInfoProvider.ApplyExchangeRate(donationProperties.DonationAmount, 1 / rate);
            }
            cartItemParams.Price = donationPrice;
        }

        return cartItemParams;
    }
Esempio n. 18
0
    /// <summary>
    /// Add product event handler.
    /// </summary>
    void btnAddProduct_Click(object sender, EventArgs e)
    {
        // Get strings with productIDs and quantities separated by ';'
        string productIDs = ValidationHelper.GetString(this.hidProductID.Value, "");
        string quantities = ValidationHelper.GetString(this.hidQuantity.Value, "");
        string options = ValidationHelper.GetString(this.hidOptions.Value, "");
        double price = ValidationHelper.GetDouble(this.hdnPrice.Value, -1);
        bool isPrivate = ValidationHelper.GetBoolean(this.hdnIsPrivate.Value, false);

        // Add new products to shopping cart
        if ((productIDs != "") && (quantities != ""))
        {
            string[] arrID = productIDs.TrimEnd(';').Split(';');
            string[] arrQuant = quantities.TrimEnd(';').Split(';');
            int[] intOptions = ValidationHelper.GetIntegers(options.Split(','), 0);

            lblError.Text = "";

            for (int i = 0; i < arrID.Length; i++)
            {
                int skuId = ValidationHelper.GetInteger(arrID[i], 0);

                SKUInfo skuInfo = SKUInfoProvider.GetSKUInfo(skuId);
                if (skuInfo != null)
                {
                    int quant = ValidationHelper.GetInteger(arrQuant[i], 0);

                    ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, quant, intOptions);

                    // If product is donation
                    if (skuInfo.SKUProductType == SKUProductTypeEnum.Donation)
                    {
                        // Get donation properties
                        if (price < 0)
                        {
                            cartItemParams.Price = SKUInfoProvider.GetSKUPrice(skuInfo, ShoppingCartInfoObj, false, false);
                        }
                        else
                        {
                            cartItemParams.Price = price;
                        }

                        cartItemParams.IsPrivate = isPrivate;
                    }

                    // Add product to the shopping cart
                    this.ShoppingCartInfoObj.SetShoppingCartItem(cartItemParams);

                    // Log activity
                    string siteName = CMSContext.CurrentSiteName;
                    if (!this.ShoppingCartControl.IsInternalOrder && (CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)
                        && ActivitySettingsHelper.AddingProductToSCEnabled(siteName))
                    {
                        this.ShoppingCartControl.TrackActivityProductAddedToShoppingCart(skuId, ResHelper.LocalizeString(skuInfo.SKUName), this.ContactID, siteName, URLHelper.CurrentRelativePath, quant);
                    }

                    // Show empty button
                    btnEmpty.Visible = true;
                }
            }
        }

        // Invalidate values
        this.hidProductID.Value = "";
        this.hidOptions.Value = "";
        this.hidQuantity.Value = "";
        this.hdnPrice.Value = "";

        // Update values in table
        btnUpdate_Click1(this.btnAddProduct, e);

        // Hide cart content when empty
        if (DataHelper.DataSourceIsEmpty(ShoppingCartInfoObj.ContentTable))
        {
            HideCartContentWhenEmpty();
        }
        else
        {
            // Inventory shloud be checked
            this.checkInventory = true;
        }
    }