/// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        int id = actionArgument.ToInteger(0);

        switch (actionName.ToLowerCSafe())
        {
        case "edit":
            URLHelper.Redirect("OrderStatus_Edit.aspx?orderstatusid=" + id + "&siteId=" + SiteID);
            break;

        case "delete":
            CheckConfigurationModification();

            var status = OrderStatusInfoProvider.GetOrderStatusInfo(id);
            if (status != null)
            {
                if (status.Generalized.CheckDependencies())
                {
                    // Show error message
                    ShowError(ECommerceHelper.GetDependencyMessage(status));

                    return;
                }

                // Delete OrderStatusInfo object from database
                OrderStatusInfoProvider.DeleteOrderStatusInfo(status);
            }

            break;
        }
    }
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void uniGrid_OnAction(string actionName, object actionArgument)
    {
        if (actionName == "edit")
        {
            var editElementName = IsMultiStoreConfiguration ? "edit.configuration.GlobalPaymentoption" : "edit.configuration.paymentoption";
            URLHelper.Redirect(UIContextHelper.GetElementUrl("cms.ecommerce", editElementName, false, ValidationHelper.GetInteger(actionArgument, 0)));
        }
        else if (actionName == "delete")
        {
            var paymentInfoObj = PaymentOptionInfoProvider.GetPaymentOptionInfo(ValidationHelper.GetInteger(actionArgument, 0));

            // Nothing to delete
            if (paymentInfoObj == null)
            {
                return;
            }

            // Check permissions
            CheckConfigurationModification(paymentInfoObj.PaymentOptionSiteID);

            if (paymentInfoObj.Generalized.CheckDependencies())
            {
                // Show error message
                ShowError(ECommerceHelper.GetDependencyMessage(paymentInfoObj));

                return;
            }

            // Delete PaymentOptionInfo object from database
            PaymentOptionInfoProvider.DeletePaymentOptionInfo(paymentInfoObj);
        }
    }
Beispiel #3
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        int id = actionArgument.ToInteger(0);

        if (actionName == "edit")
        {
            URLHelper.Redirect("InternalStatus_Edit.aspx?statusid=" + id + "&siteId=" + SiteID);
        }
        else if (actionName == "delete")
        {
            CheckConfigurationModification();

            var status = InternalStatusInfoProvider.GetInternalStatusInfo(id);
            if (status != null)
            {
                if (status.Generalized.CheckDependencies())
                {
                    // Show error message
                    ShowError(ECommerceHelper.GetDependencyMessage(status));

                    return;
                }

                // delete InternalStatusInfo object from database
                InternalStatusInfoProvider.DeleteInternalStatusInfo(status);
            }
        }
    }
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!StopProcessing)
        {
            if (AuthenticationHelper.IsAuthenticated())
            {
                // Get site id of credits main currency
                int creditSiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

                gridCreditEvents.HideControlForZeroRows = true;
                gridCreditEvents.IsLiveSite             = IsLiveSite;
                gridCreditEvents.OnExternalDataBound   += gridCreditEvents_OnExternalDataBound;
                gridCreditEvents.OrderBy        = "EventDate DESC, EventName ASC";
                gridCreditEvents.WhereCondition = "EventCustomerID = " + CustomerId + " AND ISNULL(EventSiteID, 0) = " + creditSiteId;

                // Get total credit value
                double credit = CreditEventInfoProvider.GetTotalCredit(CustomerId, SiteContext.CurrentSiteID);

                if (Currency != null)
                {
                    // Convert global credit to site main currency when using one
                    string siteName = SiteContext.CurrentSiteName;
                    rate   = ExchangeRateInfoProvider.GetLastExchangeRate(Currency.CurrencyID, SiteContext.CurrentSiteID, ECommerceSettings.UseGlobalCredit(siteName));
                    credit = ExchangeRateInfoProvider.ApplyExchangeRate(credit, rate);
                }

                lblCreditValue.Text = CurrencyInfoProvider.GetFormattedPrice(credit, Currency);
            }
            else
            {
                // Hide if user is not authenticated
                Visible = false;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        creditSiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

        CreditEventInfo creditEvent = EditedObject as CreditEventInfo;

        // Check site of credit event
        if ((creditEvent != null) && (creditEvent.EventID > 0) && (creditEvent.EventSiteID != creditSiteId))
        {
            EditedObject = null;
        }

        creditEvent = EditForm.Data as CreditEventInfo;
        if ((creditEvent != null) && (creditEvent.EventID == 0))
        {
            creditEvent.EventSiteID = creditSiteId;
        }

        CustomerInfo customer = EditedObjectParent as CustomerInfo;

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customer))
        {
            EditedObject = null;
        }

        // Check presence of main currency
        CheckMainCurrency(creditSiteId);

        // Register check permissions
        EditForm.OnCheckPermissions += (s, args) => CheckPermissions();
    }
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void uniGrid_OnAction(string actionName, object actionArgument)
    {
        int addressId = ValidationHelper.GetInteger(actionArgument, 0);

        if (actionName == "edit")
        {
            URLHelper.Redirect("Customer_Edit_Address_Edit.aspx?customerId=" + customerObj.CustomerID + "&addressId=" + addressId);
        }
        else if (actionName == "delete")
        {
            if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
            }

            var address = AddressInfoProvider.GetAddressInfo(addressId);

            // Check for the address dependencies
            if ((address != null) && address.Generalized.CheckDependencies())
            {
                ShowError(ECommerceHelper.GetDependencyMessage(address));
                return;
            }

            // Delete AddressInfo object from database
            AddressInfoProvider.DeleteAddressInfo(address);
        }
    }
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void uniGrid_OnAction(string actionName, object actionArgument)
    {
        var id = ValidationHelper.GetInteger(actionArgument, 0);

        if (actionName == "edit")
        {
            URLHelper.Redirect(UIContextHelper.GetElementUrl("CMS.Ecommerce", "EditCustomersProperties", false, id));
        }
        else if (actionName == "delete")
        {
            // Check module permissions
            if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
                return;
            }

            // Get customer to be deleted
            var customer = CustomerInfoProvider.GetCustomerInfo(id);

            // Check customers dependencies
            if ((customer != null) && customer.Generalized.CheckDependencies())
            {
                ShowError(ECommerceHelper.GetDependencyMessage(customer));
                return;
            }

            // Delete CustomerInfo object from database
            CustomerInfoProvider.DeleteCustomerInfo(customer);

            UniGrid.ReloadData();
        }
    }
Beispiel #8
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void uniGrid_OnAction(string actionName, object actionArgument)
    {
        if (actionName == "edit")
        {
            URLHelper.Redirect(UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "Edit.Configuration.ShippingOptionProperties", false, actionArgument.ToInteger(0)));
        }
        else if (actionName == "delete")
        {
            var shippingInfoObj = ShippingOptionInfoProvider.GetShippingOptionInfo(ValidationHelper.GetInteger(actionArgument, 0));
            // Nothing to delete
            if (shippingInfoObj == null)
            {
                return;
            }

            // Check permissions
            CheckConfigurationModification();

            // Check dependencies
            if (shippingInfoObj.Generalized.CheckDependencies())
            {
                // Show error message
                ShowError(ECommerceHelper.GetDependencyMessage(shippingInfoObj));

                return;
            }
            // Delete ShippingOptionInfo object from database
            ShippingOptionInfoProvider.DeleteShippingOptionInfo(shippingInfoObj);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Customers.Credit"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Customers.Credit");
        }

        // Get site id of credits main currency
        creditCurrencySiteId = ECommerceHelper.GetSiteID(CMSContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

        // Get currency in which credit is expressed in
        currency = CurrencyInfoProvider.GetMainCurrency(creditCurrencySiteId);

        // Get customerId from url
        customerId = QueryHelper.GetInteger("customerid", 0);

        // Load customer info
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        // Check, if edited customer exists
        EditedObject = customerObj;

        // Init unigrid
        UniGrid.HideControlForZeroRows = true;
        UniGrid.OnAction            += new OnActionEventHandler(uniGrid_OnAction);
        UniGrid.OnExternalDataBound += new OnExternalDataBoundEventHandler(UniGrid_OnExternalDataBound);
        UniGrid.OrderBy              = "EventDate DESC, EventName ASC";
        UniGrid.WhereCondition       = "EventCustomerID = " + customerId + " AND ISNULL(EventSiteID, 0) = " + creditCurrencySiteId;

        if (customerObj != null)
        {
            InitializeMasterPage();

            // Configuring global records
            if (creditCurrencySiteId == 0)
            {
                // Show "using global settings" info message only if showing global store settings
                lblGlobalInfo.Visible = true;
                lblGlobalInfo.Text    = GetString("com.UsingGlobalSettings");
            }

            // Display customer total credit
            lblCredit.Text      = GetString("CreditEvent_List.TotalCredit");
            lblCreditValue.Text = GetFormatedTotalCredit();
        }
    }
    /// <summary>
    /// Clean specified part of the form.
    /// </summary>
    private void CleanForm(bool billing, bool shipping, bool company)
    {
        AddressInfo defaultCustomerAddress = null;

        if (ShoppingCart?.Customer != null)
        {
            defaultCustomerAddress = ECommerceHelper.GetLastUsedOrDefaultAddress(ShoppingCart.Customer.CustomerID);
        }

        if (shipping)
        {
            txtShippingName.Text  = "";
            txtShippingAddr1.Text = "";
            txtShippingAddr2.Text = "";
            txtShippingCity.Text  = "";
            txtShippingZip.Text   = "";
            txtShippingPhone.Text = "";

            // Pre-load default country
            CountrySelector2.CountryID = defaultCustomerAddress?.AddressCountryID ?? 0;
            CountrySelector2.StateID   = defaultCustomerAddress?.AddressStateID ?? 0;
            CountrySelector2.ReloadData(true);
        }
        if (billing)
        {
            txtBillingName.Text  = "";
            txtBillingAddr1.Text = "";
            txtBillingAddr2.Text = "";
            txtBillingCity.Text  = "";
            txtBillingZip.Text   = "";
            txtBillingPhone.Text = "";

            // Pre-load default country
            CountrySelector1.CountryID = defaultCustomerAddress?.AddressCountryID ?? 0;
            CountrySelector1.StateID   = defaultCustomerAddress?.AddressStateID ?? 0;
            CountrySelector1.ReloadData(true);
        }
        if (company)
        {
            txtCompanyName.Text  = "";
            txtCompanyLine1.Text = "";
            txtCompanyLine2.Text = "";
            txtCompanyCity.Text  = "";
            txtCompanyZip.Text   = "";
            txtCompanyPhone.Text = "";

            // Pre-load default country
            CountrySelector3.CountryID = defaultCustomerAddress?.AddressCountryID ?? 0;
            CountrySelector3.StateID   = defaultCustomerAddress?.AddressStateID ?? 0;
            CountrySelector3.ReloadData(true);
        }
    }
Beispiel #11
0
    private IEnumerable <string> GetExistingCodes()
    {
        // Prepare query for codes cache
        var existingQuery = ECommerceHelper.GetAllCouponCodesQuery(SiteContext.CurrentSiteID);

        // Restrict cache if prefix specified
        if (!string.IsNullOrEmpty(prefix))
        {
            existingQuery.WhereStartsWith("CouponCodeCode", prefix);
        }

        // Create cache of this site coupon codes
        return(existingQuery.GetListResult <string>());
    }
Beispiel #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get site id of credits main currency
        creditCurrencySiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

        // Get currency in which credit is expressed in
        currency = CurrencyInfoProvider.GetMainCurrency(creditCurrencySiteId);

        // Get customerId from url
        customerId = QueryHelper.GetInteger("customerid", 0);

        // Load customer info
        customerObj = CustomerInfoProvider.GetCustomerInfo(customerId);

        // Check if customer belongs to current site
        if (!CheckCustomerSiteID(customerObj))
        {
            customerObj = null;
        }

        // Check, if edited customer exists
        EditedObject = customerObj;

        // Init unigrid
        UniGrid.HideControlForZeroRows = true;
        UniGrid.OnAction            += uniGrid_OnAction;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;
        UniGrid.OrderBy              = "EventDate DESC, EventName ASC";
        UniGrid.WhereCondition       = "EventCustomerID = " + customerId + " AND ISNULL(EventSiteID, 0) = " + creditCurrencySiteId;

        if (customerObj != null)
        {
            InitializeMasterPage();

            // Configuring global credit
            if (creditCurrencySiteId == 0)
            {
                var site = SiteContext.CurrentSite;
                if (site != null)
                {
                    // Show "using global credit" info message
                    ShowInformation(string.Format(GetString("com.UsingGlobalSettings"), site.DisplayName, GetString("com.ui.creditevents")));
                }
            }

            // Display customer total credit
            headTotalCredit.Text = string.Format(GetString("CreditEvent_List.TotalCredit"), GetFormattedTotalCredit());
        }
    }
    private void gridData_OnAction(string actionName, object actionArgument)
    {
        int argument = ValidationHelper.GetInteger(actionArgument, 0);

        actionName = actionName.ToLowerCSafe();

        switch (actionName)
        {
        case "edit":
        {
            string url   = ProductUIHelper.GetProductEditUrl();
            string query = DocumentListingDisplayed ? "?sectionId=" + NodeID + "&nodeId=" + argument + "&culture=" + CultureCode : "?productid=" + argument;

            url = URLHelper.AppendQuery(url, query);

            URLHelper.Redirect(url);
        }
        break;

        case "delete":
            if (DocumentListingDisplayed)
            {
                var url = "Product_Section.aspx?action=delete&nodeId=" + argument;
                URLHelper.Redirect(URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(url)));
            }
            else
            {
                SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(argument);

                // Check module permissions
                CheckModifyPermission(skuObj);

                // Check dependencies
                if (SKUInfoProvider.CheckDependencies(argument))
                {
                    // Show error message
                    ShowError(ECommerceHelper.GetDependencyMessage(skuObj));

                    return;
                }

                SKUInfoProvider.DeleteSKUInfo(skuObj);
            }

            break;
        }
    }
Beispiel #14
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        if (actionName == "edit")
        {
            // Discount coupon detail url
            var redirectURL = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "EditDiscountCouponProperties", false, actionArgument.ToInteger(0));
            redirectURL = URLHelper.AddParameterToUrl(redirectURL, "siteid", SiteContext.CurrentSiteID.ToString());

            URLHelper.Redirect(redirectURL);
        }
        else if (actionName == "delete")
        {
            int id = ValidationHelper.GetInteger(actionArgument, 0);

            DiscountCouponInfo discountCouponInfoObj = DiscountCouponInfoProvider.GetDiscountCouponInfo(id);
            // Nothing to delete
            if (discountCouponInfoObj == null)
            {
                return;
            }

            // Check module permissions
            if (!ECommerceContext.IsUserAuthorizedToModifyDiscountCoupon(discountCouponInfoObj))
            {
                if (discountCouponInfoObj.IsGlobal)
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL);
                }
                else
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyDiscounts");
                }
            }

            if (discountCouponInfoObj.Generalized.CheckDependencies())
            {
                ShowError(ECommerceHelper.GetDependencyMessage(discountCouponInfoObj));
                return;
            }

            // Delete DiscountCouponInfo object from database
            DiscountCouponInfoProvider.DeleteDiscountCouponInfo(discountCouponInfoObj);
        }
    }
Beispiel #15
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        int supplierId = ValidationHelper.GetInteger(actionArgument, 0);

        if (actionName == "edit")
        {
            var url = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "edit.supplier", false, supplierId);
            url = URLHelper.AddParameterToUrl(url, "action", "edit");
            URLHelper.Redirect(url);
        }
        else if (actionName == "delete")
        {
            var supplierObj = SupplierInfoProvider.GetSupplierInfo(supplierId);

            if (supplierObj == null)
            {
                return;
            }

            // Check module permissions
            if (!ECommerceContext.IsUserAuthorizedToModifySupplier(supplierObj))
            {
                if (supplierObj.IsGlobal)
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL);
                }
                else
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifySuppliers");
                }
            }

            if (supplierObj.Generalized.CheckDependencies())
            {
                // Show error message
                ShowError(ECommerceHelper.GetDependencyMessage(supplierObj));

                return;
            }

            // Delete SupplierInfo object from database
            SupplierInfoProvider.DeleteSupplierInfo(supplierObj);
        }
    }
    private bool CreateOrder(ShoppingCartInfo shoppingCart)
    {
        try
        {
            // Set order culture
            shoppingCart.ShoppingCartCulture = LocalizationContext.PreferredCultureCode;
            // Update customer preferences
            CustomerInfoProvider.SetCustomerPreferredSettings(shoppingCart);
            // Create order
            ShoppingCartInfoProvider.SetOrder(shoppingCart);
        }
        catch (Exception ex)
        {
            // Log exception
            loggedExceptions.Add(ex);
            return(false);
        }

        if (shoppingCart.OrderId > 0)
        {
            // Track order conversion
            var name = ECommerceSettings.OrderConversionName(shoppingCart.SiteName);
            ECommerceHelper.TrackOrderConversion(shoppingCart, name);
            ECommerceHelper.TrackOrderItemsConversions(shoppingCart);
            // Log purchase activity
            if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(MembershipContext.AuthenticatedUser))
            {
                var totalPriceInMainCurrency = shoppingCart.TotalPriceInMainCurrency;
                var formattedPrice           = CurrencyInfoProvider.GetFormattedPrice(totalPriceInMainCurrency, CurrencyInfoProvider.GetMainCurrency(shoppingCart.ShoppingCartSiteID));

                TrackActivityPurchasedProducts(shoppingCart, ContactID);
                TrackActivityPurchase(shoppingCart.OrderId,
                                      ContactID,
                                      totalPriceInMainCurrency,
                                      formattedPrice);
            }

            return(true);
        }

        LogError("Save order action failed", EVENT_CODE_SAVING);
        return(false);
    }
    /// <summary>
    /// Handles the UniGrid's OnExternalDataBound event.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="sourceName">Source name</param>
    /// <param name="parameter">Parameter</param>
    protected object UniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerInvariant())
        {
        case "discountvalue":
            DataRowView row    = (DataRowView)parameter;
            decimal     value  = ValidationHelper.GetDecimal(row["VolumeDiscountValue"], 0);
            bool        isFlat = ValidationHelper.GetBoolean(row["VolumeDiscountIsFlatValue"], false);

            // If value is relative, add "%" next to the value.
            if (isFlat)
            {
                return(CurrencyInfoProvider.GetFormattedPrice(value, productCurrency));
            }

            return(ECommerceHelper.GetFormattedPercentageValue(value, CultureHelper.PreferredUICultureInfo));
        }

        return(parameter);
    }
    /// <summary>
    /// Checks and processes the dependencies of the meta file and related SKU file that is being deleted.
    /// Returns true if the related SKU file object that is being deleted has no existing dependencies and it can be deleted, otherwise returns false.
    /// </summary>
    private bool ProcessDeleteForExistingEproduct()
    {
        MetaFileInfo metaFile = fileListElem.CurrentlyHandledMetaFile;

        DataSet skuFiles = SKUFileInfoProvider.GetSKUFiles().WhereEquals("FileMetaFileGUID", metaFile.MetaFileGUID);

        if (!DataHelper.DataSourceIsEmpty(skuFiles))
        {
            SKUFileInfo skuFile = new SKUFileInfo(skuFiles.Tables[0].Rows[0]);
            if (skuFile.Generalized.CheckDependencies())
            {
                ErrorMessage = ECommerceHelper.GetDependencyMessage(skuFile);
                return(false);
            }

            SKUFileInfoProvider.DeleteSKUFileInfo(skuFile);
        }

        return(true);
    }
Beispiel #19
0
    /// <summary>
    /// New address form initialization.
    /// </summary>
    protected void InitData()
    {
        lblAddress.Text = "> " + GetString("Customer_Edit_Address_Edit.NewItemCaption");
        // Fill default values
        var customer = CustomerInfoProvider.GetCustomerInfo(mCustomerId);

        if (customer != null)
        {
            var customerAddress = ECommerceHelper.GetLastUsedOrDefaultAddress(mCustomerId);

            txtAddressDeliveryPhone.Text = customer.CustomerPhone;
            txtPersonalName.Text         = customer.CustomerFirstName + " " + customer.CustomerLastName;

            txtAddressZip.Text          = "";
            txtAddressLine1.Text        = "";
            txtAddressLine2.Text        = "";
            txtAddressCity.Text         = "";
            ucCountrySelector.CountryID = customerAddress.AddressCountryID;
            ucCountrySelector.StateID   = customerAddress.AddressStateID;
        }
    }
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void uniGrid_OnAction(string actionName, object actionArgument)
    {
        int manufacturerId = ValidationHelper.GetInteger(actionArgument, 0);

        if (actionName == "edit")
        {
            URLHelper.Redirect(UIContextHelper.GetElementUrl("CMS.Ecommerce", "EditManufacturer", false, actionArgument.ToInteger(0)));
        }
        else if (actionName == "delete")
        {
            // Check module permissions
            var manufacturerObj = ManufacturerInfoProvider.GetManufacturerInfo(manufacturerId);
            if (manufacturerObj != null)
            {
                if (!ECommerceContext.IsUserAuthorizedToModifyManufacturer(manufacturerObj))
                {
                    if (manufacturerObj.IsGlobal)
                    {
                        RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
                    }
                    else
                    {
                        RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyManufacturers");
                    }
                }

                // Check dependencies
                if (manufacturerObj.Generalized.CheckDependencies())
                {
                    // Show error message
                    ShowError(ECommerceHelper.GetDependencyMessage(manufacturerObj));

                    return;
                }

                // Delete ManufacturerInfo object from database
                ManufacturerInfoProvider.DeleteManufacturerInfo(manufacturerObj);
            }
        }
    }
    /// <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 bool EnsureCartCustomer(ShoppingCartInfo shoppingCart)
    {
        CustomerInfo customer = shoppingCart.Customer;

        customer.CustomerSiteID = shoppingCart.ShoppingCartSiteID;
        customer.CustomerUserID = shoppingCart.ShoppingCartUserID;

        CustomerInfoProvider.SetCustomerInfo(customer);
        shoppingCart.ShoppingCartCustomerID = customer.CustomerID;

        if (customer.CustomerID > 0)
        {
            // Track successful registration conversion
            string name = ECommerceSettings.RegistrationConversionName(shoppingCart.SiteName);
            ECommerceHelper.TrackRegistrationConversion(shoppingCart.SiteName, name);
            // Log customer registration activity
            var activityCustomerRegistration = new ActivityCustomerRegistration(customer, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
            if (activityCustomerRegistration.Data != null)
            {
                if ((ContactID <= 0) && (customer.CustomerUser != null))
                {
                    activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(customer.CustomerUser);
                }
                else
                {
                    activityCustomerRegistration.Data.ContactID = ContactID;
                }

                activityCustomerRegistration.Log();
            }

            return(true);
        }
        else
        {
            LogError("Save customer action failed", EVENT_CODE_SAVING);
            return(false);
        }
    }
Beispiel #23
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        if (actionName == "edit")
        {
            URLHelper.Redirect("Currency_Edit.aspx?currencyid=" + Convert.ToString(actionArgument) + "&siteId=" + SiteID);
        }
        else if (actionName == "delete")
        {
            // Check permissions
            CheckConfigurationModification();

            int          currencyId = ValidationHelper.GetInteger(actionArgument, 0);
            CurrencyInfo currency   = CurrencyInfoProvider.GetCurrencyInfo(currencyId);

            if (currency != null)
            {
                if (currency.Generalized.CheckDependencies())
                {
                    // Show error message
                    ShowError(ECommerceHelper.GetDependencyMessage(currency));

                    return;
                }

                // An attempt to delete main currency
                if (currency.CurrencyIsMain)
                {
                    // Show error message
                    ShowError(string.Format(GetString("com.deletemaincurrencyerror"), HTMLHelper.HTMLEncode(currency.CurrencyDisplayName)));

                    return;
                }

                // Delete CurrencyInfo object from database
                CurrencyInfoProvider.DeleteCurrencyInfo(currency);
            }
        }
    }
    protected void EditForm_OnAfterDataLoad(object sender, EventArgs e)
    {
        // Fill default values to the form
        var customerInfo = CustomerInfoProvider.GetCustomerInfo(CustomerID);

        if (customerInfo != null)
        {
            var customerAddressInfo = ECommerceHelper.GetLastUsedOrDefaultAddress(CustomerID);

            if ((string.IsNullOrEmpty(customerInfo.CustomerFirstName)) && (string.IsNullOrEmpty(customerInfo.CustomerLastName)))
            {
                FillDefaultValue("AddressPersonalName", customerInfo.CustomerCompany);
            }
            else
            {
                FillDefaultValue("AddressPersonalName", customerInfo.CustomerFirstName + " " + customerInfo.CustomerLastName);
            }

            FillDefaultValue("AddressPhone", customerInfo.CustomerPhone);
            FillDefaultValue("AddressCountryID", customerAddressInfo.AddressCountryID);
            EditForm.Data.SetValue("AddressStateID", customerAddressInfo.AddressStateID);
        }
    }
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!StopProcessing)
        {
            if (AuthenticationHelper.IsAuthenticated())
            {
                // Get site id of credits main currency
                var creditSiteId = ECommerceHelper.GetSiteID(SiteContext.CurrentSiteID, ECommerceSettings.USE_GLOBAL_CREDIT);

                gridCreditEvents.HideControlForZeroRows = true;
                gridCreditEvents.IsLiveSite             = IsLiveSite;
                gridCreditEvents.OnExternalDataBound   += gridCreditEvents_OnExternalDataBound;
                gridCreditEvents.OrderBy        = "EventDate DESC, EventName ASC";
                gridCreditEvents.WhereCondition = new WhereCondition()
                                                  .WhereEquals("EventCustomerID", CustomerId)
                                                  .WhereEquals("EventSiteID".AsColumn().IsNull(0), creditSiteId)
                                                  .ToString(true);

                // Get total credit value
                var credit = CreditEventInfoProvider.GetTotalCredit(CustomerId, SiteContext.CurrentSiteID);

                if (Currency != null)
                {
                    // Convert credit to current currency when using one
                    CurrencyConverter.TryGetExchangeRate(creditSiteId == 0, Currency.CurrencyCode, SiteContext.CurrentSiteID, ref rate);
                    credit = CurrencyConverter.ApplyExchangeRate(credit, rate);
                }

                lblCreditValue.Text = CurrencyInfoProvider.GetFormattedPrice(credit, Currency);
            }
            else
            {
                // Hide if user is not authenticated
                Visible = false;
            }
        }
    }
    private HashSet <string> GetExistingCodes()
    {
        // Prepare query for codes cache
        var existingQuery = ECommerceHelper.GetAllCouponCodesQuery(SiteContext.CurrentSiteID);

        // Restrict cache if prefix specified
        if (!string.IsNullOrEmpty(prefix))
        {
            existingQuery.WhereStartsWith("CouponCodeCode", prefix);
        }

        // Create cache of this site coupon codes
        var existingCodes = new HashSet <string>();

        using (DbDataReader reader = existingQuery.ExecuteReader())
        {
            while (reader.Read())
            {
                existingCodes.Add(reader.GetString(0));
            }
        }

        return(existingCodes);
    }
    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);
        }
    }
 private static string GetDiscountGridValue(DiscountInfo discount)
 {
     return(discount.DiscountIsFlat
         ? CurrencyInfoProvider.GetFormattedPrice(discount.DiscountValue, discount.DiscountSiteID)
         : ECommerceHelper.GetFormattedPercentageValue(discount.DiscountValue, CultureHelper.PreferredUICultureInfo));
 }
    /// <summary>
    /// Saves order information from ShoppingCartInfo object to database as new order.
    /// </summary>
    public override bool ProcessStep()
    {
        // Load first step if there is no currency or no address
        if ((this.ShoppingCartInfoObj.ShoppingCartBillingAddressID <= 0) || (this.ShoppingCartInfoObj.ShoppingCartCurrencyID <= 0))
        {
            this.ShoppingCartControl.LoadStep(0);
            return(false);
        }

        // Deal with order note
        this.ShoppingCartControl.SetTempValue(ORDER_NOTE, null);
        this.ShoppingCartInfoObj.ShoppingCartNote = this.txtNote.Text.Trim();

        try
        {
            // Set order culture
            ShoppingCartInfoObj.ShoppingCartCulture = CMSContext.PreferredCultureCode;

            // Update customer preferences
            CustomerInfoProvider.SetCustomerPreferredSettings(ShoppingCartInfoObj);

            // Create order
            ShoppingCartInfoProvider.SetOrder(this.ShoppingCartInfoObj);
        }
        catch (Exception ex)
        {
            lblError.Text = GetString("Ecommerce.OrderPreview.ErrorOrderSave") + " (" + ex.Message + ")";
            return(false);
        }

        // Track order items conversions
        ECommerceHelper.TrackOrderItemsConversions(ShoppingCartInfoObj);

        // Track order conversion
        string name = this.ShoppingCartControl.OrderTrackConversionName;

        ECommerceHelper.TrackOrderConversion(ShoppingCartInfoObj, name);

        // Track order activity
        string siteName = CMSContext.CurrentSiteName;

        if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) && this.LogActivityForCustomer && (this.ContactID > 0))
        {
            // Track individual items
            if (ActivitySettingsHelper.PurchasedProductEnabled(siteName))
            {
                this.ShoppingCartControl.TrackActivityPurchasedProducts(ShoppingCartInfoObj, siteName, this.ContactID);
            }
            // Tack entire purchase
            if (ActivitySettingsHelper.PurchaseEnabled(siteName))
            {
                this.ShoppingCartControl.TrackActivityPurchase(ShoppingCartInfoObj.OrderId, this.ContactID,
                                                               CMSContext.CurrentSiteName, URLHelper.CurrentRelativePath,
                                                               ShoppingCartInfoObj.TotalPriceInMainCurrency, CurrencyInfoProvider.GetFormattedPrice(ShoppingCartInfoObj.TotalPriceInMainCurrency,
                                                                                                                                                    CurrencyInfoProvider.GetMainCurrency(CMSContext.CurrentSiteID)));
            }
        }

        // Raise finish order event
        this.ShoppingCartControl.RaiseOrderCompletedEvent();

        // When in CMSDesk
        if (this.ShoppingCartControl.IsInternalOrder)
        {
            if (chkSendEmail.Checked)
            {
                // Send order notification emails
                OrderInfoProvider.SendOrderNotificationToAdministrator(this.ShoppingCartInfoObj);
                OrderInfoProvider.SendOrderNotificationToCustomer(this.ShoppingCartInfoObj);
            }
        }
        // When on the live site
        else if (ECommerceSettings.SendOrderNotification(CMSContext.CurrentSite.SiteName))
        {
            // Send order notification emails
            OrderInfoProvider.SendOrderNotificationToAdministrator(this.ShoppingCartInfoObj);
            OrderInfoProvider.SendOrderNotificationToCustomer(this.ShoppingCartInfoObj);
        }

        return(true);
    }