Exemple #1
0
 /// <summary>
 /// Create Shopping cart with item by customer
 /// </summary>
 /// <param name="customerAddressID"></param>
 /// <param name="txtQty"></param>
 private void CreateShoppingCartByCustomer(SKUInfo product, int customerAddressID, int productQty, double skuPrice)
 {
     try
     {
         var customerAddress = AddressInfoProvider.GetAddressInfo(customerAddressID);
         if (!DataHelper.DataSourceIsEmpty(product))
         {
             ShoppingCartInfo cart = new ShoppingCartInfo();
             cart.ShoppingCartSiteID     = CurrentSite.SiteID;
             cart.ShoppingCartCustomerID = customerAddressID;
             cart.ShoppingCartCurrencyID = CurrencyInfoProvider.GetMainCurrency(CurrentSite.SiteID).CurrencyID;
             cart.SetValue("ShoppingCartCampaignID", ProductCampaignID);
             cart.SetValue("ShoppingCartProgramID", ProductProgramID);
             cart.SetValue("ShoppingCartDistributorID", customerAddressID);
             cart.SetValue("ShoppingCartInventoryType", ProductType);
             cart.User = CurrentUser;
             cart.ShoppingCartShippingAddress  = customerAddress;
             cart.ShoppingCartShippingOptionID = ProductShippingID;
             ShoppingCartInfoProvider.SetShoppingCartInfo(cart);
             ShoppingCartItemParameters parameters = new ShoppingCartItemParameters(product.SKUID, productQty);
             parameters.CustomParameters.Add("CartItemCustomerID", customerAddressID);
             ShoppingCartItemInfo cartItem = cart.SetShoppingCartItem(parameters);
             cartItem.SetValue("CartItemPrice", skuPrice);
             cartItem.SetValue("CartItemDistributorID", customerAddressID);
             cartItem.SetValue("CartItemCampaignID", ProductCampaignID);
             cartItem.SetValue("CartItemProgramID", ProductProgramID);
             ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);
             cart.InvalidateCalculations();
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("CustomerCartOperations.ascx.cs", "CreateShoppingCartByCustomer()", ex);
     }
 }
Exemple #2
0
    public override bool ProcessStep()
    {
        try
        {
            //int paymentID = ValidationHelper.GetInteger(SessionHelper.GetValue("PaymentID"), 0);
            int paymentID = ShippingExtendedInfoProvider.GetCustomFieldValue(ShoppingCart, "ShoppingCartPaymentID");

            // Cleanup the ShoppingCart ViewState
            ShoppingCartControl.SetTempValue(SHIPPING_OPTION_ID, null);

            ShoppingCartControl.SetTempValue(PAYMENT_OPTION_ID, null);

            //ShoppingCart.ShoppingCartShippingOptionID = selectShipping.ShippingID;
            //ShoppingCart.ShoppingCartPaymentOptionID = selectPayment.PaymentID;
            ShoppingCart.ShoppingCartShippingOptionID = IsShippingNeeded ? GetShippingID() : selectShipping.ShippingID;
            ShoppingCart.ShoppingCartPaymentOptionID  = paymentID;

            // Update changes in database only when on the live site
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }
            return(true);
        }
        catch (Exception ex)
        {
            lblError.Visible = true;
            lblError.Text    = ex.Message + " /step " + IsShippingNeeded.ToString();
            return(false);
        }
    }
Exemple #3
0
    /// <summary>
    /// Saves data
    /// </summary>
    protected override void SaveStepData(object sender, StepEventArgs e)
    {
        base.SaveStepData(sender, e);

        if (!StopProcessing)
        {
            // Set current address
            AddressInfo ai = addressForm.EditedObject as AddressInfo;
            if (ai != null)
            {
                CurrentCartAddress = ai;

                if (string.IsNullOrEmpty(ai.AddressPersonalName) && (ShoppingCart.Customer != null))
                {
                    ai.AddressPersonalName = TextHelper.LimitLength(string.Format("{0} {1}", ShoppingCart.Customer.CustomerFirstName, ShoppingCart.Customer.CustomerLastName), 200);
                }
            }
        }

        // Clear shipping address if shipping checkbox is unchecked
        if ((AddressType == SHIPPING) && (!chkShowAddress.Checked))
        {
            ShoppingCart.ShoppingCartShippingAddress = null;
        }

        // Set shopping cart with current address change
        ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
    }
Exemple #4
0
    public override bool ProcessStep()
    {
        try
        {
            // Cleanup the ShoppingCart ViewState
            this.ShoppingCartControl.SetTempValue(SHIPPING_OPTION_ID, null);
            this.ShoppingCartControl.SetTempValue(PAYMENT_OPTION_ID, null);

            ShoppingCartInfoObj.ShoppingCartShippingOptionID = this.selectShipping.ShippingID;
            ShoppingCartInfoObj.ShoppingCartPaymentOptionID  = this.selectPayment.PaymentID;

            // Update changes in database only when on the live site
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCartInfoObj);
            }
            return(true);
        }
        catch (Exception ex)
        {
            lblError.Visible = true;
            lblError.Text    = ex.Message;
            return(false);
        }
    }
        public ShoppingCart CreateEmptyShoppingCart()
        {
            var originalCart = ShoppingCartFactory.CreateCart(SiteID);

            ShoppingCartInfoProvider.SetShoppingCartInfo(originalCart);

            return(new ShoppingCart(originalCart, new EcommerceActivitiesLoggerFake(), null, null));
        }
    private void SaveCartItem(ShoppingCartItemInfo scii)
    {
        // Set new cart
        if (ShoppingCart.ShoppingCartID == 0)
        {
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
        }

        ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(scii);
    }
        public void SetShoppingCartAddress(int addressId)
        {
            var cart = ECommerceContext.CurrentShoppingCart;

            if (cart.ShoppingCartShippingAddress == null || cart.ShoppingCartShippingAddress.AddressID != addressId)
            {
                var address = AddressInfoProvider.GetAddressInfo(addressId);
                cart.ShoppingCartShippingAddress = address;
                ShoppingCartInfoProvider.SetShoppingCartInfo(cart);
            }
        }
    protected override void SaveStepData(object sender, StepEventArgs e)
    {
        base.SaveStepData(sender, e);

        // Just set current filed values into EditableObject, saving was canceled in OnBeforeSave
        customerForm.SaveData(null, false);

        var customer = customerForm.EditedObject as CustomerInfo;

        if (customer == null)
        {
            throw new InvalidOperationException("Customer cannot be null while saving step data.");
        }

        var typeSelector = TypeSelector;

        // Clear company fields for non-company type
        if ((typeSelector != null) && !typeSelector.Value.Equals(COMPANY_TYPE))
        {
            customer.CustomerCompany           = "";
            customer.CustomerOrganizationID    = "";
            customer.CustomerTaxRegistrationID = "";
        }

        if (customer.CustomerID < 1 && ShoppingCart.ShoppingCartUserID > 0)
        {
            // Connect newly created customer with registered user -> if user returns to the site, customer`s data will be filled
            customer.CustomerUserID = ShoppingCart.ShoppingCartUserID;
        }
        customer.CustomerSiteID = ShoppingCart.ShoppingCartSiteID;

        var shoppingService = Service.Resolve <IShoppingService>();

        shoppingService.SetCustomer(customer);

        // Address cannot be inserted before customer is saved (otherwise it would be an orphan address)
        // In case of address update - AddressName and AddressPersonalName should be re-generated according current customer info (if not present on the address form)
        if (((shoppingService.GetBillingAddress() == null) ||
             (shoppingService.GetShippingAddress() == null) ||
             (ShoppingCart.ShoppingCartCompanyAddress != null)) &&
            (customer.CustomerID > 0))
        {
            SaveCustomerAddresses(ShoppingCart);
        }

        ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);

        // Update contact with customer details
        var dci     = DataClassInfoProvider.GetDataClassInfo(customer.TypeInfo.ObjectClassName);
        var mapper  = new ContactDataMapper(dci.ClassName, dci.ClassContactOverwriteEnabled);
        var checker = new CustomerContactDataPropagationChecker();

        Service.Resolve <IContactDataInjector>().Inject(customer, ContactID, mapper, checker);
    }
Exemple #9
0
        public ShoppingCart CreateCartWithCustomerInfo(CustomerInfo customer, AddressInfo address = null, ICurrentContactProvider currentContactProvider = null)
        {
            var cartInfo = ShoppingCartFactory.CreateCart(SiteID);

            cartInfo.ShoppingCartCurrencyID = Factory.MainCurrency.CurrencyID;
            cartInfo.Customer = customer;
            cartInfo.ShoppingCartBillingAddress = address;

            ShoppingCartInfoProvider.SetShoppingCartInfo(cartInfo);

            return(new ShoppingCart(cartInfo, new EcommerceActivitiesLoggerFake(), currentContactProvider));
        }
    /// <summary>
    /// Handles the payment option change and rises the <see cref="CMSCheckoutWebPart.SHOPPING_CART_CHANGED"/>.
    /// </summary>
    protected void PaymentSelected(object sender, EventArgs e)
    {
        // Only if selection is different
        if (ShoppingCart.ShoppingCartPaymentOptionID != drpPayment.SelectedID)
        {
            ShoppingCart.ShoppingCartPaymentOptionID = drpPayment.SelectedID;
            ShoppingCart.Evaluate();
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);

            // Make sure that in-memory changes persist (unsaved address, etc.)
            ECommerceContext.CurrentShoppingCart = ShoppingCart;

            // Raise the change event for all subscribed web parts
            ComponentEvents.RequestEvents.RaiseEvent(this, e, SHOPPING_CART_CHANGED);
        }
    }
Exemple #11
0
    protected override void SaveStepData(object sender, StepEventArgs e)
    {
        base.SaveStepData(sender, e);

        // Just set current filed values into EditableObject, saving was canceled in OnBeforeSave
        customerForm.SaveData(null, false);

        var customer     = customerForm.EditedObject as CustomerInfo;
        var typeSelector = TypeSelector;

        // Clear company fields for non-company type
        if ((customer != null) && (typeSelector != null) && !typeSelector.Value.Equals(COMPANY_TYPE))
        {
            customer.CustomerCompany           = "";
            customer.CustomerOrganizationID    = "";
            customer.CustomerTaxRegistrationID = "";
        }

        var cart = ShoppingCart;

        // Assign save customer to the shopping cart -> will be needed for addresses
        cart.Customer = SaveCustomer(customer, cart.ShoppingCartUserID, cart.ShoppingCartSiteID);

        // Address cannot be inserted before customer is saved (otherwise it would be an orphan address)
        // In case of address update - AddressName and AddressPersonalName should be re-generated according current customer info (if not present on the address form)
        if (((cart.ShoppingCartBillingAddress != null) ||
             (cart.ShoppingCartShippingAddress != null) ||
             (cart.ShoppingCartCompanyAddress != null)) &&
            (customer != null) && (customer.CustomerID > 0))
        {
            SaveCustomerAddresses(cart);
        }

        ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

        // Update contact with customer details
        if (customer != null)
        {
            var dci     = DataClassInfoProvider.GetDataClassInfo(customer.TypeInfo.ObjectClassName);
            var mapper  = new ContactDataMapper(dci.ClassName, dci.ClassContactOverwriteEnabled);
            var checker = new CustomerContactDataPropagationChecker();
            Service.Resolve <IContactDataInjector>().Inject(customer, ContactID, mapper, checker);
        }
    }
    private void LoadControlData()
    {
        // Initialize selector if needed
        if (!RequestHelper.IsPostBack() && drpShipping.HasData)
        {
            drpShipping.Reload();
            drpShipping.SelectedID = ShoppingService.GetShippingOption();
        }

        // Evaluate cart if shipping was pre-selected
        if (ShoppingCart.ItemChanged("ShoppingCartShippingOptionID"))
        {
            ShoppingCart.Evaluate();
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);

            // Make sure that in-memory changes persist (unsaved address, etc.)
            Service.Resolve <ICurrentShoppingCartService>().SetCurrentShoppingCart(ShoppingCart);
        }
    }
Exemple #13
0
    /// <summary>
    /// Adds content of order to current shopping cart.
    /// </summary>
    private void AddToCart(int orderId)
    {
        if (!ShowOrderToShoppingCart)
        {
            return;
        }

        // Get order
        OrderInfo order = OrderInfoProvider.GetOrderInfo(orderId);

        if (order != null)
        {
            CustomerInfo customer = CustomerInfoProvider.GetCustomerInfo(order.OrderCustomerID);

            if (customer.CustomerUserID == CurrentUser.UserID)
            {
                // Get current shopping cart
                ShoppingCartInfo cart = ECommerceContext.CurrentShoppingCart;
                // Set new cart
                if (cart.ShoppingCartID == 0)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(cart);
                }

                string cartUrl = ECommerceSettings.ShoppingCartURL(CurrentSite.SiteName);

                // Update shopping cart by items from order
                if (!ShoppingCartInfoProvider.UpdateShoppingCartFromOrder(cart, orderId))
                {
                    cartUrl = URLHelper.AddParameterToUrl(cartUrl, "notallreordered", "1");
                }

                // Update shopping cart items in database
                foreach (ShoppingCartItemInfo item in cart.CartItems)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(item);
                }

                // Redirect to shopping cart page
                URLHelper.ResponseRedirect(cartUrl);
            }
        }
    }
Exemple #14
0
    /// <summary>
    /// Creates a new shopping cart record and corresponding shopping cart items records in the database
    /// as a copy of given shopping cart info.
    /// Currency is set according to the currency of the given cart.
    /// If a configuration of cart item is no longer available it is not cloned to new shopping cart.
    /// <see cref="AbstractUserControl.CurrentUser"/> is set as the new cart owner (only non-public user is set).
    /// </summary>
    /// <param name="originalCart">Original cart to clone.</param>
    /// <returns>Created shopping cart info.</returns>
    private ShoppingCartInfo CloneShoppingCartInfo(ShoppingCartInfo originalCart)
    {
        using (new CMSActionContext {
            UpdateTimeStamp = false
        })
        {
            var cartClone = ShoppingCartFactory.CreateCart(CurrentSite.SiteID, CurrentUser.IsPublic() ? null : CurrentUser);

            cartClone.ShoppingCartCurrencyID = originalCart.ShoppingCartCurrencyID;
            cartClone.ShoppingCartLastUpdate = originalCart.ShoppingCartLastUpdate;
            ShoppingCartInfoProvider.SetShoppingCartInfo(cartClone);

            ShoppingCartInfoProvider.CopyShoppingCartItems(originalCart, cartClone);

            // Set the shopping cart items into the database
            cartClone.CartItems.ForEach(i => i.Generalized.SetObject());

            return(cartClone);
        }
    }
    /// <summary>
    /// Handles the currency change event. Saving of the selected value into the shopping cart object.
    /// </summary>
    private void DropDownSingleSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ShoppingCart.ShoppingCartCurrencyID != selectCurrency.SelectedID)
        {
            // Set currency for the shopping cart according to the selected value
            ShoppingCart.ShoppingCartCurrencyID = selectCurrency.SelectedID;
            ShoppingCart.Evaluate();
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);

            // Make sure that in-memory changes persist (unsaved address, etc.)
            Service.Resolve <ICurrentShoppingCartService>().SetCurrentShoppingCart(ShoppingCart);

            // Raise the change event for all subscribed web parts
            ComponentEvents.RequestEvents.RaiseEvent(this, e, SHOPPING_CART_CHANGED);
        }

        if (ReloadPage)
        {
            URLHelper.Redirect(RequestContext.CurrentURL);
        }
    }
    /// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shopping cart item parameters</param>
    protected void AddProducts(ShoppingCartItemParameters itemParams)
    {
        IShoppingService shoppingService = Service.Resolve <IShoppingService>();

        var ui = MembershipContext.AuthenticatedUser;

        if (!ui.IsPublic())
        {
            ShoppingCart.User = ui;
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
        }
        if (!ShoppingCartControl.IsInternalOrder)
        {
            var addedItem = shoppingService.AddItemToCart(itemParams);

            // Track add to shopping cart conversion
            ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);
        }
        else if (Service.Resolve <ICartItemChecker>().CheckNewItem(itemParams, ShoppingCart))
        {
            ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, 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);
            }
        }
    }
        private ShoppingCartItemInfo CreateCartItem(TreeNode document, Guid templateId)
        {
            if (document == null)
            {
                return(null);
            }

            var sku = SKUInfoProvider.GetSKUInfo(document.NodeSKUID);

            var cart = ECommerceContext.CurrentShoppingCart;

            ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

            var parameters = new ShoppingCartItemParameters(sku.SKUID, 1);

            if (Guid.Empty != templateId)
            {
                var optionSku = GetOrCreateTemplateOptionSKU();
                var option    = new ShoppingCartItemParameters(optionSku.SKUID, 1)
                {
                    Text = templateId.ToString()
                };

                parameters.ProductOptions.Add(option);
            }

            var cartItem = cart.SetShoppingCartItem(parameters);

            cartItem.CartItemText = sku.SKUName;
            cartItem.SetValue("ChilliEditorTemplateID", templateId);
            cartItem.SetValue("ChiliTemplateID", document.GetGuidValue("ProductChiliTemplateID", Guid.Empty));
            cartItem.SetValue("ProductType", document.GetStringValue("ProductType", string.Empty));
            cartItem.SetValue("ProductPageID", document.NodeID);
            cartItem.SetValue("ProductChiliPdfGeneratorSettingsId", document.GetGuidValue("ProductChiliPdfGeneratorSettingsId", Guid.Empty));
            cartItem.SetValue("ProductChiliWorkspaceId", document.GetGuidValue("ProductChiliWorkgroupID", Guid.Empty));
            cartItem.SetValue("ProductProductionTime", document.GetStringValue("ProductProductionTime", string.Empty));
            cartItem.SetValue("ProductShipTime", document.GetStringValue("ProductShipTime", string.Empty));

            return(cartItem);
        }
Exemple #18
0
        /// <summary>
        /// Saves the shopping cart into the database.
        /// </summary>
        /// <param name="validate">Specifies whether the validation should be performed.</param>
        public void Save(bool validate = true)
        {
            if (validate)
            {
                var result = Validate();
                if (result.CheckFailed)
                {
                    throw new InvalidOperationException();
                }
            }

            SaveCustomer();
            SaveAddresses();

            ShoppingCartInfoProvider.SetShoppingCartInfo(OriginalCart);
            foreach (var item in OriginalCart.CartItems)
            {
                item.ShoppingCart   = OriginalCart;
                item.ShoppingCartID = OriginalCart.ShoppingCartID;
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(item);
            }
        }
    private void LoadControlData(bool forceReload = false)
    {
        var paymentOptions = PaymentOptionInfoProvider.GetPaymentOptions(ShoppingCart.ShoppingCartSiteID, true)
                             .Column("PaymentOptionID")
                             .OrderBy("PaymentOptionDisplayName");

        if (ShoppingCart.ShippingOption == null || !ShoppingCart.IsShippingNeeded)
        {
            paymentOptions.WhereTrue("PaymentOptionAllowIfNoShipping");
        }

        var paymentIds = paymentOptions.GetListResult <int>();

        // If there is only one payment method set it
        if (paymentIds.Count == 1)
        {
            ShoppingCart.ShoppingCartPaymentOptionID = paymentIds.First();
            drpPayment.SelectedID = ShoppingCart.ShoppingCartPaymentOptionID;
        }

        drpPayment.DisplayOnlyAllowedIfNoShipping = (ShoppingCart.ShoppingCartShippingOptionID <= 0) || !ShoppingCart.IsShippingNeeded;

        if (!RequestHelper.IsPostBack() || forceReload || ((ShoppingCart.ShoppingCartPaymentOptionID != 0) && !PaymentOptionInfoProvider.IsPaymentOptionApplicable(ShoppingCart, ShoppingCart.PaymentOption)))
        {
            // Reset selector on shipping changed event if selected payment is not allowed for current shipping (zero shipping id is Please select state).
            drpPayment.Reload();
            drpPayment.SelectedID = ShoppingCart.ShoppingCartPaymentOptionID;
        }

        // Evaluate cart if payment was pre-selected
        if (ShoppingCart.ItemChanged("ShoppingCartPaymentOptionID"))
        {
            ShoppingCart.Evaluate();
            ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);

            // Make sure that in-memory changes persist (unsaved address, etc.)
            ECommerceContext.CurrentShoppingCart = ShoppingCart;
        }
    }
    protected override void SaveStepData(object sender, StepEventArgs e)
    {
        base.SaveStepData(sender, e);

        // Just set current filed values into EditableObject, saving was canceled in OnBeforeSave
        customerForm.SaveData(null, false);

        var customer     = customerForm.EditedObject as CustomerInfo;
        var typeSelector = TypeSelector;

        // Clear company fields for non-company type
        if ((customer != null) && (typeSelector != null) && !typeSelector.Value.Equals(COMPANY_TYPE))
        {
            customer.CustomerCompany           = "";
            customer.CustomerOrganizationID    = "";
            customer.CustomerTaxRegistrationID = "";
        }

        var cart = ShoppingCart;

        // Assign save customer to the shopping cart -> will be needed for addresses
        cart.Customer = SaveCustomer(customer, cart.ShoppingCartUserID, cart.ShoppingCartSiteID);

        // Address cannot be inserted before customer is saved (otherwise it would be an orphan address)
        // In case of address update - AddressName and AddressPersonalName should be re-generated according current customer info (if not present on the address form)
        if (((cart.ShoppingCartBillingAddress != null) ||
             (cart.ShoppingCartShippingAddress != null) ||
             (cart.ShoppingCartCompanyAddress != null)) &&
            (customer != null) && (customer.CustomerID > 0))
        {
            SaveCustomerAddresses(cart);
        }

        ShoppingCartInfoProvider.SetShoppingCartInfo(cart);

        // Update contact with customer details
        ModuleCommands.OnlineMarketingUpdateContactFromExternalData(customer, ContactID);
    }
    /// <summary>
    /// Creates a new shopping cart record and corresponding shopping cart items records in the database
    /// as a copy of given shopping cart info.
    /// Currency is set according to the currency of given cart.
    /// If a configuration of cart item is no longer available it is not cloned to new shopping cart.
    /// Correct user id for logged user is _not_ handled in this method, because it does not depend on
    /// abandoned cart's user id. It should be handled according to user's status (logged in/anonymous)
    /// in the browser where the cart is loaded:
    ///  - anonymous cart or user's cart opened in the browser where user is logged in - new cart userId should be set to logged user's id
    ///  - anonymous cart or user's cart opened in the browser where user is _not_ logged in - new cart userId should be empty (anonymous cart)
    /// </summary>
    /// <param name="originalCart">Original cart to clone.</param>
    /// <returns>Created shopping cart info.</returns>
    private ShoppingCartInfo CloneShoppingCartInfo(ShoppingCartInfo originalCart)
    {
        using (new CMSActionContext {
            UpdateTimeStamp = false
        })
        {
            ShoppingCartInfo cartClone = ShoppingCartFactory.CreateCart(CurrentSite.SiteID, originalCart.User);

            cartClone.ShoppingCartCurrencyID = originalCart.ShoppingCartCurrencyID;
            cartClone.ShoppingCartLastUpdate = originalCart.ShoppingCartLastUpdate;
            ShoppingCartInfoProvider.SetShoppingCartInfo(cartClone);

            ShoppingCartInfoProvider.CopyShoppingCartItems(originalCart, cartClone);

            // Set the shopping cart items into the database
            foreach (ShoppingCartItemInfo item in cartClone.CartItems)
            {
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(item);
            }

            return(cartClone);
        }
    }
    public override bool ProcessStep()
    {
        string siteName = SiteContext.CurrentSiteName;

        if (IsExistingAccount())
        {
            // Sign in customer with existing account

            // Authenticate user
            //UserInfo ui = UserInfoProvider.GetUserInfo(txtLogin.Text);

            UserInfo ui = AuthenticationHelper.AuthenticateUser(txtLogin.Text.Trim(), txtMotDePasse.Text, SiteContext.CurrentSiteName);

            if (ui == null)
            {
                // ShowError(ResHelper.GetString("ShoppingCartCheckRegistration.LoginFailed"));
                return(false);
            }

            // Set current user
            MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true);
            UserInfoProvider.SetPreferredCultures(ui);

            // Sign in
            FormsAuthentication.SetAuthCookie(ui.UserName, false);

            // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
            ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

            // Assign current user to the current shopping cart
            ShoppingCart.User = ui;

            // Save changes to database // Already done in the end of this method
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCartInfObj);
            }

            //Create a customer for the user if do not yet exist
            CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(this.ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID  = this.ShoppingCartControl.UserInfo.UserID;
                ci.CustomerEnabled = true;
            }

            // Old email address
            //string oldEmail = ci.CustomerEmail.ToLower(); ;

            ci.CustomerFirstName = ui.FirstName;
            ci.CustomerLastName  = ui.LastName;
            ci.CustomerEmail     = ui.Email;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Set the shopping cart customer ID
            this.ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }
        else if (IsNewAccount())
        {
            txtEmail2.Text             = txtEmail2.Text.Trim();
            pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

            // Check if user exists
            UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
            if (ui != null)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                return(false);
            }

            // Check all sites where user will be assigned
            string checkSites = (String.IsNullOrEmpty(ShoppingCartControl.AssignToSites)) ? SiteContext.CurrentSiteName : ShoppingCartControl.AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return(false);
            }

            // Create new customer and user account and sign in
            // User



            ui = new UserInfo();


            ui.UserName  = txtEmailRegistration.Text.Trim();
            ui.Email     = txtEmailRegistration.Text.Trim();
            ui.FirstName = txtFirstName.Text.Trim();
            ui.FullName  = UserInfoProvider.GetFullName(txtFirstName.Text.Trim(), String.Empty, txtLastName.Text.Trim());
            ui.LastName  = txtLastName.Text.Trim();
            ui.Enabled   = true;
            ui.UserIsGlobalAdministrator = false;
            ui.UserURLReferrer           = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign = AnalyticsHelper.Campaign;
            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            try
            {
                UserInfoProvider.SetPassword(ui, txtMotDePasseRegistration.Text);

                string[] siteList;

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }
                else // If not set user current site
                {
                    siteList = new string[] { siteName };
                }

                foreach (string site in siteList)
                {
                    UserInfoProvider.AddUserToSite(ui.UserName, site);

                    // Add user to roles
                    if (ShoppingCartControl.AssignToRoles != "")
                    {
                        AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                    }
                }

                // Log registered user
                AnalyticsHelper.LogRegisteredUser(siteName, ui);

                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                return(false);
            }

            // Customer
            CustomerInfo ci = new CustomerInfo();
            ci.CustomerFirstName = txtFirstName.Text.Trim();
            ci.CustomerLastName  = txtLastName.Text.Trim();
            ci.CustomerEmail     = txtEmailRegistration.Text.Trim();

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkCorporateBody.Checked)
            {
                ci.CustomerCompany = txtCompany1.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                }
            }

            ci.CustomerUserID  = ui.UserID;
            ci.CustomerSiteID  = 0;
            ci.CustomerEnabled = true;
            ci.CustomerCreated = DateTime.Now;
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Track successful registration conversion
            string name = ShoppingCartControl.RegistrationTrackConversionName;
            ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

            // Log "customer registration" activity and update profile
            var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
            if (activityCustomerRegistration.Data != null)
            {
                if (ContactID <= 0)
                {
                    activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }
                activityCustomerRegistration.Log();
            }

            // Sign in
            if (ui.UserEnabled)
            {
                CMSContext.AuthenticateUser(ui.UserName, false);
                ShoppingCart.User = ui;

                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

            // Send new registration notification email
            if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
            {
                SendRegistrationNotification(ui);
            }
            /**aadrresse*/
            // Process billing address
            //------------------------
            int         CountryID  = ValidationHelper.GetInteger(ddlShippingCountry.SelectedValue, 0);
            AddressInfo ai         = null;
            bool        newAddress = true;
            ai = new AddressInfo();
            string mCustomerName = ci.CustomerFirstName + " " + ci.CustomerLastName;
            // newAddress.AddressName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;


            ai.AddressPersonalName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;
            ai.AddressLine1        = txtAdresse.Text.Trim();
            ai.AddressLine2        = txtAdresse.Text.Trim();
            ai.AddressCity         = txtVille.Text.Trim();
            ai.AddressZip          = txtCodePostale.Text.Trim();
            ai.AddressCountryID    = CountryID;


            if (newAddress)
            {
                ai.AddressIsBilling  = true;
                ai.AddressIsShipping = !chkShippingAddr.Checked;
                ai.AddressEnabled    = true;
            }
            ai.AddressCustomerID = ci.CustomerID;
            ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

            // Save address and set it's ID to ShoppingCartInfoObj
            AddressInfoProvider.SetAddressInfo(ai);

            // Update current contact's address
            ModuleCommands.OnlineMarketingMapAddress(ai, ContactID);

            ShoppingCart.ShoppingCartBillingAddressID = ai.AddressID;

            // If shopping cart does not need shipping
            if (!ShippingOptionInfoProvider.IsShippingNeeded(ShoppingCart))
            {
                ShoppingCart.ShoppingCartShippingAddressID = 0;
            }
            // If shipping address is different from billing address
            else if (chkShippingAddr.Checked)
            {
                //// Check country presence
                //if (CountrySelector2.CountryID <= 0)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedcountryerr");
                //    return false;
                //}

                //if (!CountrySelector2.StateSelectionIsValid)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedstateerr");
                //    return false;
                //}

                //newAddress = false;
                //// Process shipping address
                ////-------------------------
                //ai = AddressInfoProvider.GetAddressInfo(Convert.ToInt32(drpShippingAddr.SelectedValue));
                //if (ai == null)
                //{
                //    ai = new AddressInfo();
                //    newAddress = true;
                //}

                ai.AddressPersonalName = txtadresseshipping.Text.Trim();
                ai.AddressLine1        = txtadresseshipping.Text.Trim();
                ai.AddressLine2        = txtadresseshipping.Text.Trim();
                ai.AddressCity         = txtvilleshipping.Text.Trim();
                ai.AddressZip          = txtcpshipping.Text.Trim();
                ai.AddressCountryID    = CountryID;

                if (newAddress)
                {
                    ai.AddressIsShipping = true;
                    ai.AddressEnabled    = true;
                    ai.AddressIsBilling  = false;
                    ai.AddressIsCompany  = false;
                    ai.AddressEnabled    = true;
                }
                ai.AddressCustomerID = ci.CustomerID;
                ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

                // Save address and set it's ID to ShoppingCartInfoObj
                AddressInfoProvider.SetAddressInfo(ai);
                ShoppingCart.ShoppingCartShippingAddressID = ai.AddressID;
            }
            // Shipping address is the same as billing address
            else
            {
                ShoppingCart.ShoppingCartShippingAddressID = ShoppingCart.ShoppingCartBillingAddressID;
            }
            /**finadrress*/
            this.ShoppingCartControl.ButtonNextClickAction();
        }

        try
        {
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCart);
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, SiteContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text    = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return(false);
                }

                // Sign in customer with existing account
                AuthenticationHelper.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                // Log "login" activity
                MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                LoadStep(true);

                // Return false to get to Edit customer page
                return(false);
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text             = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                string[] siteList = { siteName };

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return(false);
                }

                // Check all sites where user will be assigned
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return(false);
                }

                // Create new customer and user account and sign in
                // User
                ui           = new UserInfo();
                ui.UserName  = txtEmail2.Text.Trim();
                ui.Email     = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName  = txtLastName1.Text.Trim();
                ui.FullName  = ui.FirstName + " " + ui.LastName;
                ui.Enabled   = true;
                ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;
                ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
                ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text    = ex.Message;
                    return(false);
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName  = txtLastName1.Text.Trim();
                ci.CustomerEmail     = txtEmail2.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID  = ui.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                CreateContactRelation(ci);

                // Sign in
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName  = txtLastName2.Text.Trim();
                ci.CustomerEmail     = txtEmail3.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID  = SiteContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                CreateContactRelation(ci);

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return(false);
            }
        }
        else
        {
            // Save the customer data
            bool         newCustomer = false;
            CustomerInfo ci          = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID = 0;
                newCustomer       = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName  = txtEditLast.Text.Trim();
            ci.CustomerEmail     = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            if (newCustomer)
            {
                CreateContactRelation(ci);
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            ShoppingCart.InvalidateCalculations();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
    /// <summary>
    /// Process this step.
    /// </summary>
    public override bool ProcessStep()
    {
        // Shopping cart units are already saved in database (on "Update" or on "btnAddProduct_Click" actions)
        bool isOK = false;

        if (ShoppingCartInfoObj != null)
        {
            // Reload data
            ReloadData();

            // Check available items before "Check out"
            string error = ShoppingCartInfoProvider.CheckShoppingCart(this.ShoppingCartInfoObj);
            if (!string.IsNullOrEmpty(error))
            {
                lblError.Text = error.Replace(";", "<br />");
            }
            else if (this.ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
            {
                // Indicates wheter order saving process is successful
                isOK = true;

                try
                {
                    ShoppingCartInfoProvider.SetOrder(this.ShoppingCartInfoObj);
                }
                catch
                {
                    isOK = false;
                }

                if (isOK)
                {
                    lblInfo.Text = GetString("General.ChangesSaved");

                    // Send order notification when editing existing order
                    if (this.ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
                    {
                        if (chkSendEmail.Checked)
                        {
                            OrderInfoProvider.SendOrderNotificationToAdministrator(this.ShoppingCartInfoObj);
                            OrderInfoProvider.SendOrderNotificationToCustomer(this.ShoppingCartInfoObj);
                        }
                    }
                    // Send order notification emails when on the live site
                    else if (ECommerceSettings.SendOrderNotification(CMSContext.CurrentSite.SiteName))
                    {
                        OrderInfoProvider.SendOrderNotificationToAdministrator(this.ShoppingCartInfoObj);
                        OrderInfoProvider.SendOrderNotificationToCustomer(this.ShoppingCartInfoObj);
                    }
                }
                else
                {
                    lblError.Text = GetString("Ecommerce.OrderPreview.ErrorOrderSave");
                }
            }
            // Go to the next step
            else
            {
                // Save other options
                if (!this.ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCartInfoObj);
                }
                isOK = true;
            }
        }

        return(isOK);
    }
    /// <summary>
    /// Sets product in the shopping cart.
    /// </summary>
    /// <param name="itemParams">Shoppping 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(ShoppingCartInfoObj, 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
                        CurrentUserInfo ui = CMSContext.CurrentUser;
                        if (!ui.IsPublic())
                        {
                            this.ShoppingCartInfoObj.UserInfoObj = ui;
                            updateCart = true;
                        }

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

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

                        // Set item in the shopping cart
                        ShoppingCartItemInfo product = this.ShoppingCartInfoObj.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
                        this.ShoppingCartInfoObj.SetShoppingCartItem(itemParams);
                    }
                }
            }

            // Avoid adding the same product after page refresh
            if (lblError.Text == "")
            {
                string url = URLRewriter.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);
                }
            }
        }
    }
Exemple #26
0
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = CMSContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, CMSContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text    = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return(false);
                }

                // Sign in customer with existing account
                CMSContext.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                // Log "login" activity
                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                activity.Log();

                LoadStep(true);

                // Return false to get to Edit customer page
                return(false);
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text             = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return(false);
                }

                // Check all sites where user will be assigned
                string checkSites = (String.IsNullOrEmpty(ShoppingCartControl.AssignToSites)) ? CMSContext.CurrentSiteName : ShoppingCartControl.AssignToSites;
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), checkSites, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return(false);
                }

                // Create new customer and user account and sign in
                // User
                ui           = new UserInfo();
                ui.UserName  = txtEmail2.Text.Trim();
                ui.Email     = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName  = txtLastName1.Text.Trim();
                ui.FullName  = ui.FirstName + " " + ui.LastName;
                ui.Enabled   = true;
                ui.UserIsGlobalAdministrator = false;
                ui.UserURLReferrer           = CMSContext.CurrentUser.URLReferrer;
                ui.UserCampaign = CMSContext.Campaign;
                ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    string[] siteList;

                    // If AssignToSites field set
                    if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                    {
                        siteList = ShoppingCartControl.AssignToSites.Split(';');
                    }
                    else // If not set user current site
                    {
                        siteList = new string[] { siteName };
                    }

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text    = ex.Message;
                    return(false);
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName  = txtLastName1.Text.Trim();
                ci.CustomerEmail     = txtEmail2.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID  = ui.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                // Log "customer registration" activity and update profile
                var activityCustomerRegistration = new ActivityCustomerRegistration(ci, CMSContext.CurrentUser, CMSContext.ActivityEnvironmentVariables);
                if (activityCustomerRegistration.Data != null)
                {
                    if (ContactID <= 0)
                    {
                        activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    }
                    activityCustomerRegistration.Log();
                }

                // Sign in
                if (ui.UserEnabled)
                {
                    CMSContext.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

                    ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activity = new ActivityUserLogin(ContactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                    activity.Log();
                }

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName  = txtLastName2.Text.Trim();
                ci.CustomerEmail     = txtEmail3.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerEnabled = true;
                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID  = CMSContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Log "customer registration" activity
                var activity = new ActivityCustomerRegistration(ci, CMSContext.CurrentUser, CMSContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID();
                    activity.Data.ContactID = ContactID;
                    activity.Log();
                }

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return(false);
            }
        }
        else
        {
            // Save the customer data
            bool         newCustomer = false;
            CustomerInfo ci          = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID  = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerEnabled = true;
                newCustomer        = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName  = txtEditLast.Text.Trim();
            ci.CustomerEmail     = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            // Log "customer registration" activity and update contact profile
            if (newCustomer)
            {
                var activity = new ActivityCustomerRegistration(ci, CMSContext.CurrentUser, CMSContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
    /// <summary>
    /// Process this step.
    /// </summary>
    public override bool ProcessStep()
    {
        // Do not process step if order is paid
        if (OrderIsPaid)
        {
            return(false);
        }

        // Shopping cart units are already saved in database (on "Update" or on "btnAddProduct_Click" actions)
        bool isOK = false;

        if (ShoppingCart != null)
        {
            // Reload data
            ReloadData();

            // Validate available items before "Check out"
            var cartValidator = new ShoppingCartValidator(ShoppingCart);

            cartValidator.Validate();

            if (!cartValidator.IsValid)
            {
                lblError.Text = cartValidator.GetErrorMessages()
                                .Select(e => HTMLHelper.HTMLEncode(e))
                                .Join("<br />");
            }
            else if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
            {
                // Indicates whether order saving process is successful
                isOK = true;

                try
                {
                    ShoppingCartInfoProvider.SetOrder(ShoppingCart);
                }
                catch (Exception ex)
                {
                    // Log exception
                    EventLogProvider.LogException("Shopping cart", "SAVEORDER", ex, ShoppingCart.ShoppingCartSiteID);
                    isOK = false;
                }

                if (isOK)
                {
                    lblInfo.Text = GetString("general.changessaved");

                    // Send order notification when editing existing order
                    if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
                    {
                        if (chkSendEmail.Checked)
                        {
                            OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                            OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                        }
                    }
                    // Send order notification emails when on the live site
                    else if (ECommerceSettings.SendOrderNotification(SiteContext.CurrentSite.SiteName))
                    {
                        OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                        OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                    }
                }
                else
                {
                    lblError.Text = GetString("ecommerce.orderpreview.errorordersave");
                }
            }
            // Go to the next step
            else
            {
                // Save other options
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                isOK = true;
            }
        }

        return(isOK);
    }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        // Validate input data
        if (!IsValid() || (this.SKU == null))
        {
            // Do not proces
            return;
        }

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

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

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

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

        // Check if it is possible to add this item to shopping cart
        if (!ShoppingCartInfoProvider.CheckNewShoppingCartItems(this.ShoppingCart, cartItemParams))
        {
            // Show error message and cancel adding the product to shopping cart
            string error = String.Format(this.GetString("ecommerce.cartcontent.productdisabled"), this.SKU.SKUName);
            ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

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

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

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

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

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

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

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

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

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

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

            // Add item to shopping cart
            ShoppingCartItemInfo addedItem = this.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 (this.RedirectToShoppingCart)
                {
                    // Set shopping cart referrer
                    SessionHelper.SetValue("ShoppingCartUrlReferrer", URLHelper.CurrentURL);

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

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

                    // Check inventory
                    string checkInventoryMessage = ShoppingCartInfoProvider.CheckShoppingCart(this.ShoppingCart).Replace(";", "\n");

                    // Get prodcut added message
                    string message = String.Format(this.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(this.Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
                }
            }
        }
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        // AddressInfo ai = null;
        bool newAddress = false;

        if (mCustomerId > 0)
        {
            // Clean the viewstate
            RemoveBillingTempValues();
            RemoveShippingTempValues();
            RemoveCompanyTempValues();

            // Process billing address

            /*if (ai == null)
             * {
             *  ai = new AddressInfo();
             *  newAddress = true;
             * }
             *
             * if (newAddress)
             * {
             *  ai.AddressIsBilling = true;
             *  ai.AddressEnabled = true;
             * }
             * ai.AddressCustomerID = mCustomerId;
             * ai.AddressName = AddressInfoProvider.GetAddressName(ai);
             *
             * // Save address and set it's ID to ShoppingCartInfoObj
             * AddressInfoProvider.SetAddressInfo(ai);*/

            // Update current contact's address
            ModuleCommands.OnlineMarketingMapAddress(AddressInfoProvider.GetAddressInfo(ShoppingCart.ShoppingCartBillingAddressID), ContactID);

            // If shopping cart does not need shipping
            if (!ShippingOptionInfoProvider.IsShippingNeeded(ShoppingCart))
            {
                ShoppingCart.ShoppingCartShippingAddressID = 0;
            }
            // If shipping address is different from billing address

            /*
             * else if (chkShippingAddr.Checked)
             * {
             *
             *  newAddress = false;
             *  // Process shipping address
             *  //-------------------------
             *  if (ai == null)
             *  {
             *      ai = new AddressInfo();
             *      newAddress = true;
             *  }
             *
             *  if (newAddress)
             *  {
             *      ai.AddressIsShipping = true;
             *      ai.AddressEnabled = true;
             *      ai.AddressIsBilling = false;
             *      ai.AddressIsCompany = false;
             *      ai.AddressEnabled = true;
             *  }
             *  ai.AddressCustomerID = mCustomerId;
             *  ai.AddressName = AddressInfoProvider.GetAddressName(ai);
             *
             *  // Save address and set it's ID to ShoppingCartInfoObj
             *  AddressInfoProvider.SetAddressInfo(ai);
             *  ShoppingCart.ShoppingCartShippingAddressID = ai.AddressID;
             * }
             * // Shipping address is the same as billing address
             * else
             * {
             *  ShoppingCart.ShoppingCartShippingAddressID = ShoppingCart.ShoppingCartBillingAddressID;
             * }*/

            try
            {
                // Update changes in database only when on the live site
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }
                return(true);
            }
            catch (Exception ex)
            {
                // Show error message
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                return(false);
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("Ecommerce.NoCustomerSelected");
            return(false);
        }
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (mCustomerId > 0)
        {
            // Clean the viewstate
            RemoveBillingTempValues();
            RemoveShippingTempValues();
            RemoveCompanyTempValues();

            // Check country presence
            if (CountrySelector1.CountryID <= 0)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("countryselector.selectedcountryerr");
                return(false);
            }

            if (!CountrySelector1.StateSelectionIsValid)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("countryselector.selectedstateerr");
                return(false);
            }

            // Process billing address
            //------------------------
            var ai = AddressInfoProvider.GetAddressInfo(ValidationHelper.GetInteger(drpBillingAddr.SelectedValue, 0)) ?? new AddressInfo();
            ai.AddressPersonalName = GetTruncatedTextBoxInput(txtBillingName);
            ai.AddressLine1        = GetTruncatedTextBoxInput(txtBillingAddr1);
            ai.AddressLine2        = GetTruncatedTextBoxInput(txtBillingAddr2);
            ai.AddressCity         = GetTruncatedTextBoxInput(txtBillingCity);
            ai.AddressZip          = GetTruncatedTextBoxInput(txtBillingZip);
            ai.AddressCountryID    = CountrySelector1.CountryID;
            ai.AddressStateID      = CountrySelector1.StateID;
            ai.AddressPhone        = GetTruncatedTextBoxInput(txtBillingPhone);
            ai.AddressCustomerID   = mCustomerId;
            ai.AddressName         = AddressInfoProvider.GetAddressName(ai);

            // Save address and set it's ID to ShoppingCartInfoObj
            AddressInfoProvider.SetAddressInfo(ai);

            // Update current contact's address
            MapContactAddress(ai);

            ShoppingCart.ShoppingCartBillingAddress = ai;

            // If shopping cart does not need shipping
            if (!ShoppingCart.IsShippingNeeded)
            {
                ShoppingCart.ShoppingCartShippingAddress = null;
            }
            // If shipping address is different from billing address
            else if (chkShippingAddr.Checked)
            {
                // Check country presence
                if (CountrySelector2.CountryID <= 0)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("countryselector.selectedcountryerr");
                    return(false);
                }

                if (!CountrySelector2.StateSelectionIsValid)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("countryselector.selectedstateerr");
                    return(false);
                }

                // Process shipping address
                //-------------------------
                ai = AddressInfoProvider.GetAddressInfo(Convert.ToInt32(drpShippingAddr.SelectedValue)) ?? new AddressInfo();
                ai.AddressPersonalName = GetTruncatedTextBoxInput(txtShippingName);
                ai.AddressLine1        = GetTruncatedTextBoxInput(txtShippingAddr1);
                ai.AddressLine2        = GetTruncatedTextBoxInput(txtShippingAddr2);
                ai.AddressCity         = GetTruncatedTextBoxInput(txtShippingCity);
                ai.AddressZip          = GetTruncatedTextBoxInput(txtShippingZip);
                ai.AddressCountryID    = CountrySelector2.CountryID;
                ai.AddressStateID      = CountrySelector2.StateID;
                ai.AddressPhone        = GetTruncatedTextBoxInput(txtShippingPhone);
                ai.AddressCustomerID   = mCustomerId;
                ai.AddressName         = AddressInfoProvider.GetAddressName(ai);

                // Save address and set it's ID to ShoppingCartInfoObj
                AddressInfoProvider.SetAddressInfo(ai);
                ShoppingCart.ShoppingCartShippingAddress = ai;
            }
            // Shipping address is the same as billing address
            else
            {
                ShoppingCart.ShoppingCartShippingAddress = ShoppingCart.ShoppingCartBillingAddress;
            }

            if (chkCompanyAddress.Checked)
            {
                // Check country presence
                if (CountrySelector3.CountryID <= 0)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("countryselector.selectedcountryerr");
                    return(false);
                }

                if (!CountrySelector3.StateSelectionIsValid)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("countryselector.selectedstateerr");
                    return(false);
                }

                // Process company address
                //-------------------------
                ai = AddressInfoProvider.GetAddressInfo(Convert.ToInt32(drpCompanyAddress.SelectedValue)) ?? new AddressInfo();
                ai.AddressPersonalName = GetTruncatedTextBoxInput(txtCompanyName);
                ai.AddressLine1        = GetTruncatedTextBoxInput(txtCompanyLine1);
                ai.AddressLine2        = GetTruncatedTextBoxInput(txtCompanyLine2);
                ai.AddressCity         = GetTruncatedTextBoxInput(txtCompanyCity);
                ai.AddressZip          = GetTruncatedTextBoxInput(txtCompanyZip);
                ai.AddressCountryID    = CountrySelector3.CountryID;
                ai.AddressStateID      = CountrySelector3.StateID;
                ai.AddressPhone        = GetTruncatedTextBoxInput(txtCompanyPhone);
                ai.AddressCustomerID   = mCustomerId;
                ai.AddressName         = AddressInfoProvider.GetAddressName(ai);

                // Save address and set it's ID to ShoppingCartInfoObj
                AddressInfoProvider.SetAddressInfo(ai);
                ShoppingCart.ShoppingCartCompanyAddress = ai;
            }
            // Company address is the same as billing address
            else
            {
                // Save information about company address or not (according to the site settings)
                if (ECommerceSettings.UseExtraCompanyAddress(mCurrentSite.SiteName))
                {
                    ShoppingCart.ShoppingCartCompanyAddress = ShoppingCart.ShoppingCartBillingAddress;
                }
                else
                {
                    ShoppingCart.ShoppingCartCompanyAddress = null;
                }
            }

            try
            {
                ShoppingCart.Evaluate();

                // Update changes in database only when on the live site
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }
                return(true);
            }
            catch (Exception ex)
            {
                // Show error message
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                return(false);
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("Ecommerce.NoCustomerSelected");
            return(false);
        }
    }