Exemplo n.º 1
0
        /// <summary>
        /// Subscribes e-mail address to specific newsletter.
        /// If no subscriber with the given e-mail is found, the new one is created.
        /// Action fails when:
        /// <list type="bullet">
        /// <item>
        /// <description>Request is performed from banned IP address</description>
        /// </item>
        /// <item>
        /// <description>Email is already subscribed to the newsletter</description>
        /// </item>
        /// <item>
        /// <description>Newsletter with the given name does not exist</description>
        /// </item>
        /// <item>
        /// <description>Current licence does not allow creating new subscribers</description>
        /// </item>
        /// </list>
        /// errorMessage output parameter is filled with localized error description in all these cases.
        /// No exception can be thrown.
        /// </summary>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterName">Name of the newsletter</param>
        /// <param name="errorMessage">Error message used when subscription failed</param>
        /// <returns>Returns true if subscription was successful</returns>
        public virtual bool Subscribe(string email, string newsletterName, out string errorMessage)
        {
            bool result = false;

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                // Saves subscriber into the database
                SubscriberInfo subscriber = SaveSubscriber(email, out errorMessage);
                if ((subscriber != null) && string.IsNullOrEmpty(errorMessage))
                {
                    // Assignes subscriber into the newsletter
                    bool newsletterSubscribed = SaveNewsletter(newsletterName, subscriber, out errorMessage);
                    if (newsletterSubscribed && string.IsNullOrEmpty(errorMessage))
                    {
                        result = true;
                    }
                }

                // Saves changes
                tr.Commit();
            }

            return(result);
        }
Exemplo n.º 2
0
    /// <summary>
    /// Executes the UnsetTragetLayout client action using parameters passed in hidden fields.
    /// </summary>
    private void UnsetTargetLayout()
    {
        int sourceLayoutId = ValidationHelper.GetInteger(SourceLayoutIdentifierHiddenField.Value, 0);

        using (var scope = new CMSTransactionScope())
        {
            LayoutInfo sourceLayout = LayoutInfoProvider.GetLayoutInfo(sourceLayoutId);
            if (sourceLayout == null)
            {
                throw new ApplicationException(GetString("device_profile.layoutmapping.errors.nosourcelayout"));
            }

            InfoObjectCollection <DeviceProfileLayoutInfo> bindings = DeviceProfileLayoutInfoProvider.GetDeviceProfileLayouts()
                                                                      .WhereEquals("DeviceProfileID", DeviceProfile.ProfileID)
                                                                      .WhereEquals("SourceLayoutID", sourceLayout.LayoutId)
                                                                      .TypedResult
                                                                      .Items;

            if (bindings.Count > 0)
            {
                DeviceProfileLayoutInfoProvider.DeleteDeviceProfileLayoutInfo(bindings[0]);
            }
            scope.Commit();
        }
    }
Exemplo n.º 3
0
    /// <summary>
    /// Saves customer data and returns customer ID.
    /// </summary>
    public int Save()
    {
        if (!IsValid())
        {
            return(0);
        }

        // Create customer
        CustomerInfo customer = new CustomerInfo()
        {
            CustomerSiteID            = CMSContext.CurrentSiteID,
            CustomerFirstName         = txtCustomerFirstName.Text.Trim().Truncate(100),
            CustomerLastName          = txtCustomerLastName.Text.Trim().Truncate(100),
            CustomerCompany           = txtCustomerCompany.Text.Trim(),
            CustomerOrganizationID    = txtOrganizationID.Text.Trim(),
            CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim(),
            CustomerCountryID         = drpCountry.CountryID,
            CustomerStateID           = drpCountry.StateID,
            CustomerEmail             = txtCustomerEmail.Text.Trim().Truncate(100),
            CustomerPhone             = txtCustomerPhone.Text.Trim(),
            CustomerFax     = txtCustomerFax.Text.Trim(),
            CustomerEnabled = true
        };

        // Save data in transaction
        using (CMSTransactionScope tr = new CMSTransactionScope())
        {
            CustomerInfoProvider.SetCustomerInfo(customer);

            if (chkCreateLogin.Checked)
            {
                // Create user
                UserInfo user = new UserInfo()
                {
                    UserName = txtUserName.Text.Trim(),
                    FullName = customer.CustomerFirstName + " " + customer.CustomerLastName,
                    IsGlobalAdministrator = false
                };

                user.SetValue("UserEnabled", true);

                UserInfoProvider.SetPassword(user, passStrength.Text);
                UserInfoProvider.AddUserToSite(user.UserName, CMSContext.CurrentSiteName);

                customer.CustomerUserID = user.UserID;
                CustomerInfoProvider.SetCustomerInfo(customer);
            }

            tr.Commit();
        }

        return(customer.CustomerID);
    }
Exemplo n.º 4
0
    /// <summary>
    /// Copies role binding from parent UI element.
    /// </summary>
    /// <param name="element">Element which are permissions copied to</param>
    private void CopyFromParent(UIElementInfo element)
    {
        using (var tr = new CMSTransactionScope())
        {
            if (element != null)
            {
                // Delete existing bindings
                DataSet elemRoles = RoleUIElementInfoProvider.GetRoleUIElements("ElementID = " + element.ElementID, null);
                if (!DataHelper.DataSourceIsEmpty(elemRoles))
                {
                    foreach (DataRow dr in elemRoles.Tables[0].Rows)
                    {
                        // Get role id
                        int roleId = ValidationHelper.GetInteger(dr["RoleID"], 0);
                        // Remove binding
                        RoleUIElementInfoProvider.DeleteRoleUIElementInfo(roleId, element.ElementID);
                    }
                }

                // Add same bindings as parent has
                int parentElemId = element.ElementParentID;

                DataSet parentRoles = RoleUIElementInfoProvider.GetRoleUIElements("ElementID = " + parentElemId, null);
                if (!DataHelper.DataSourceIsEmpty(parentRoles))
                {
                    foreach (DataRow dr in parentRoles.Tables[0].Rows)
                    {
                        // Get role id
                        int roleId = ValidationHelper.GetInteger(dr["RoleID"], 0);
                        // Create binding
                        RoleUIElementInfoProvider.AddRoleUIElementInfo(roleId, element.ElementID);
                    }
                }
            }

            // Commit transaction
            tr.Commit();
        }

        // Invalidate all users
        UserInfo.TYPEINFO.InvalidateAllObjects();

        // Clear hashtables with users
        UserInfoProvider.Clear(true);
    }
Exemplo n.º 5
0
    /// <summary>
    /// Executes the SetTragetLayout client action using parameters passed in hidden fields.
    /// </summary>
    private void SetTargetLayout()
    {
        int sourceLayoutId = ValidationHelper.GetInteger(SourceLayoutIdentifierHiddenField.Value, 0);
        int targetLayoutId = ValidationHelper.GetInteger(TargetLayoutIdentifierHiddenField.Value, 0);

        using (var scope = new CMSTransactionScope())
        {
            LayoutInfo sourceLayout = LayoutInfoProvider.GetLayoutInfo(sourceLayoutId);
            if (sourceLayout == null)
            {
                throw new ApplicationException(GetString("device_profile.layoutmapping.errors.nosourcelayout"));
            }
            LayoutInfo targetLayout = LayoutInfoProvider.GetLayoutInfo(targetLayoutId);
            if (targetLayout == null)
            {
                throw new ApplicationException(GetString("device_profile.layoutmapping.errors.notargetlayout"));
            }

            InfoObjectCollection <DeviceProfileLayoutInfo> bindings = DeviceProfileLayoutInfoProvider.GetDeviceProfileLayouts()
                                                                      .Where("DeviceProfileID", QueryOperator.Equals, DeviceProfile.ProfileID)
                                                                      .Where("SourceLayoutID", QueryOperator.Equals, sourceLayout.LayoutId)
                                                                      .TypedResult
                                                                      .Items;

            DeviceProfileLayoutInfo binding = null;
            if (bindings.Count > 0)
            {
                binding = bindings[0];
            }
            else
            {
                binding = new DeviceProfileLayoutInfo
                {
                    DeviceProfileID = DeviceProfile.ProfileID,
                    SourceLayoutID  = sourceLayout.LayoutId
                };
            }
            binding.TargetLayoutID = targetLayout.LayoutId;
            DeviceProfileLayoutInfoProvider.SetDeviceProfileLayoutInfo(binding);
            scope.Commit();
        }
    }
Exemplo n.º 6
0
    /// <summary>
    /// Executes the UnsetTragetLayout client action using parameters passed in hidden fields.
    /// </summary>
    private void UnsetTargetLayout()
    {
        int sourceLayoutId = ValidationHelper.GetInteger(SourceLayoutIdentifierHiddenField.Value, 0);

        using (CMSTransactionScope scope = new CMSTransactionScope())
        {
            LayoutInfo sourceLayout = LayoutInfoProvider.GetLayoutInfo(sourceLayoutId);
            if (sourceLayout == null)
            {
                throw new ApplicationException(GetString("device_profile.layoutmapping.errors.nosourcelayout"));
            }
            string condition = String.Format("DeviceProfileID = {0:D} AND SourceLayoutID = {1:D}", DeviceProfile.ProfileID, sourceLayout.LayoutId);
            InfoObjectCollection <DeviceProfileLayoutInfo> bindings = DeviceProfileLayoutInfoProvider.GetDeviceProfileLayouts(condition, null).Items;
            if (bindings.Count > 0)
            {
                DeviceProfileLayoutInfoProvider.DeleteDeviceProfileLayoutInfo(bindings[0]);
            }
            scope.Commit();
        }
    }
    /// <summary>
    /// Selects variant as winner.
    /// </summary>
    /// <param name="winnerGuid">Winner variant GUID</param>
    private void SelectWinner(Guid winnerGuid)
    {
        if (winnerGuid == Guid.Empty || OriginalVariant == null)
        {
            ShowError(GetString("abtesting.pushwinner.error.general"));
            return;
        }

        var variant = ABVariants.FirstOrDefault(v => v.ABVariantGUID == winnerGuid);

        if (variant == null)
        {
            ShowError(GetString("abtesting.pushwinner.error.general"));
            return;
        }

        if (!UserHasPermissions || !DocumentManager.AllowSave)
        {
            ShowError(GetString("abtesting.pushwinner.error.general"));
            return;
        }

        // Set winner GUID to ABTest
        ABTest.ABTestWinnerGUID = variant.ABVariantGUID;

        using (var transaction = new CMSTransactionScope())
        {
            abTestManager.PromoteVariant(DocumentManager.Node, variant.ABVariantGUID);
            DocumentManager.SaveDocument();

            transaction.Commit();
        }

        DisplayWinnerInformation(variant);

        // Reload data because HeaderActions_ActionPerformed event is too late to change action tooltip
        gridElem.ReloadData();

        // Reload summary box based on new status
        LoadSummaryBox();
    }
Exemplo n.º 8
0
        /// <summary>
        /// Subscribes e-mail address to the specified newsletter.
        /// If no subscriber with the given e-mail is found, a new subscriber is created.
        /// </summary>
        /// <remarks>
        /// Action fails when:
        /// <list type="bullet">
        /// <item>
        /// <description>Newsletter with the given name does not exist.</description>
        /// </item>
        /// <item>
        /// <description>Current license does not allow creating new subscribers.</description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterName">Name of the newsletter</param>
        /// <returns>Returns true if subscription was successful.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="email"/> or <paramref name="newsletterName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="newsletterName"/> is not valid.</exception>
        public virtual bool Subscribe(string email, string newsletterName)
        {
            if (email == null)
            {
                throw new ArgumentNullException("email");
            }

            if (newsletterName == null)
            {
                throw new ArgumentNullException("newsletterName");
            }

            // Gets information about newsletter on current site
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, SiteId);

            if (newsletter == null)
            {
                throw new ArgumentException("Newsletter object with the given newsletter name does not exist.", "newsletterName");
            }

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                // Saves subscriber into the database
                SubscriberInfo subscriber = SaveSubscriber(email);

                if (subscriber != null)
                {
                    // Assigns subscriber to the newsletter
                    if (SubscribeToNewsletter(subscriber, newsletter))
                    {
                        // Saves changes
                        tr.Commit();
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 9
0
        private static void ImportModule(string modulePath, string userName)
        {
            try
            {
                string moduleName = GetModuleName(modulePath);

                using (var transaction = new CMSTransactionScope())
                {
                    // Execute before.sql
                    ExecuteSqlScript(SQL_BEFORE_PATH);

                    // Import .zip package with export data
                    if (!System.IO.File.Exists(modulePath))
                    {
                        throw new ArgumentException("[ModuleExportPackageImporter.Import] File on given path '" + modulePath + "' does not exist.", "modulePath");
                    }

                    var           settings      = CreateImportSettings(modulePath, userName);
                    ImportManager importManager = new ImportManager(settings);
                    importManager.Import(null);

                    // Execute after.sql
                    ExecuteSqlScript(SQL_AFTER_PATH);

                    // Commit the module installation if the transaction succeeded
                    transaction.Commit();
                }

                // Perform finish actions
                FinishModuleInstallation(modulePath);



                CoreServices.EventLog.LogEvent("I", "ModuleInstaller", "MODULEINSTALLED", $"Module '{moduleName}' from path {modulePath} has been installed (restart could be required).");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 10
0
    private bool FinalizeCheckout()
    {
        using (var scope = new CMSTransactionScope())
        {
            ShoppingCartInfo currentShoppingCart = ShoppingCart;
            HandleAutomaticSelections(currentShoppingCart);

            // Validate all
            if (!ValidateShoppingCart(currentShoppingCart))
            {
                return(false);
            }
            // Ensure customer is saved
            if (!EnsureCartCustomer(currentShoppingCart))
            {
                return(false);
            }
            // Ensure customers address is saved
            if (!EnsureCustomerAddresses(currentShoppingCart))
            {
                return(false);
            }
            // Create and save Order
            if (!CreateOrder(currentShoppingCart))
            {
                return(false);
            }

            if (!HandleAutoRegistration(currentShoppingCart))
            {
                return(false);
            }

            HandleOrderNotification(currentShoppingCart);
            scope.Commit();
        }

        return(true);
    }
        /// <summary>
        /// Unsubscribes email from a newsletter of all marketing materials.
        /// </summary>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterGuid">Newsletter to unsubscribe email from</param>
        /// <param name="issueGuid">Issue unique identifier. When issue guid is present, number of unsubscriptions for this issue is increased</param>
        /// <param name="unsubscribeFromAll">If true, subscriber is unsubscribed from all marketing materials</param>
        /// <returns>Returns true if unsubscription was successful.</returns>
        /// <exception cref="ArgumentException"><paramref name="newsletterGuid"/> or <paramref name="issueGuid"/> is not valid.</exception>
        private bool UnsubscribeInternal(string email, Guid newsletterGuid, Guid? issueGuid, bool unsubscribeFromAll)
        {
            // Gets information about newsletter and issue
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterGuid, SiteId);
            int? issueId = null;

            if (newsletter == null)
            {
                throw new ArgumentException("Newsletter with the given newsletter guid does not exist.", "newsletterGuid");
            }

            if (issueGuid.HasValue)
            {
                IssueInfo issue = IssueInfoProvider.GetIssueInfo(issueGuid.Value, SiteId);

                if (issue == null)
                {
                    throw new ArgumentException("Issue with the given issue guid does not exist.", "issue");
                }

                issueId = issue.IssueID;
            }

            // Creates required Services
            var subscriptionService = Service<ISubscriptionService>.Entry();
            var unsubscriptionProvider = Service<IUnsubscriptionProvider>.Entry();

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                try
                {
                    if (unsubscribeFromAll)
                    {
                        // Unsubscribes if not already unsubscribed
                        if (!unsubscriptionProvider.IsUnsubscribedFromAllNewsletters(email, newsletter.NewsletterSiteID))
                        {
                            subscriptionService.UnsubscribeFromAllNewsletters(email, SiteId, issueId);
                            tr.Commit();
                        }

                        return true;
                    }

                    // Unsubscribes if not already unsubscribed
                    if (!unsubscriptionProvider.IsUnsubscribedFromSingleNewsletter(email, newsletter.NewsletterID, newsletter.NewsletterSiteID))
                    {
                        subscriptionService.UnsubscribeFromSingleNewsletter(email, newsletter.NewsletterID, issueId);
                        tr.Commit();
                    }

                    return true;
                }
                catch (Exception exception)
                {
                    Service<IEventLogService>.Entry().LogException("Newsletters", "Unsubscribe", exception);
                }

                return false;
            }

            #endregion
        }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        string errorMessage = "";

        if ((txtCustomerCompany.Text.Trim() == "") &&
            ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }
        else if (ECommerceSettings.RequireCompanyInfo(CMSContext.CurrentSite.SiteName) && (txtCustomerCompany.Text.Trim() != "" || txtOraganizationID.Text.Trim() != "" || txtTaxRegistrationID.Text.Trim() != ""))
        {
            errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text.Trim(), GetString("customers_edit.errorcompany"))
                .NotEmpty(txtOraganizationID.Text.Trim(), GetString("customers_edit.errororganizationid"))
                .NotEmpty(txtTaxRegistrationID.Text.Trim(), GetString("customers_edit.errortaxregid")).Result;
        }
        else if ((txtCustomerEmail.Text.Trim() != "") && !ValidationHelper.IsEmail(txtCustomerEmail.Text))
        {
            errorMessage = GetString("Customers_Edit.errorEmail");
        }

        if (chkHasLogin.Checked)
        {
            if (errorMessage == "")
            {
                errorMessage = new Validator().NotEmpty(txtUserName.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvUserName"))
                    .NotEmpty(passStrength.Text, GetString("Customer_Edit_Login_Edit.rqvPassword1"))
                    .NotEmpty(txtPassword2.Text, GetString("Customer_Edit_Login_Edit.rqvPassword2")).Result;
            }

            if ((errorMessage == "") && (passStrength.Text != txtPassword2.Text))
            {
                errorMessage = GetString("Customer_Edit_Login_Edit.DifferentPasswords");
            }

            // Check policy
            if ((errorMessage == "") && !passStrength.IsValid())
            {
                errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
            }

            // Check if user name is unique
            if (errorMessage == "")
            {
                UserInfo existingUser = UserInfoProvider.GetUserInfo(txtUserName.Text.Trim());
                if (existingUser != null)
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.UserExist");
                }
            }
        }

        if (errorMessage == "")
        {
            CustomerInfo customerObj = CustomerInfoProvider.GetCustomerInfo(customerid);

            // If customer does not already exist, create new one
            if (customerObj == null)
            {
                customerObj = new CustomerInfo();
                customerObj.CustomerSiteID = currentSiteId;
                customerObj.CustomerEnabled = true;
            }

            customerObj.CustomerEmail = txtCustomerEmail.Text.Trim();
            customerObj.CustomerFax = txtCustomerFax.Text.Trim();
            customerObj.CustomerLastName = txtCustomerLastName.Text.Trim();
            customerObj.CustomerPhone = txtCustomerPhone.Text.Trim();
            customerObj.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            customerObj.CustomerCompany = txtCustomerCompany.Text.Trim();
            customerObj.CustomerCountryID = drpCountry.CountryID;
            customerObj.CustomerStateID = drpCountry.StateID;
            customerObj.CustomerOrganizationID = txtOraganizationID.Text.Trim();
            customerObj.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();

            // Set customer's preferences
            customerObj.CustomerPreferredCurrencyID = drpCurrency.CurrencyID;
            customerObj.CustomerPreferredPaymentOptionID = drpPayment.PaymentID;
            customerObj.CustomerPreferredShippingOptionID = drpShipping.ShippingID;

            if (plcDiscounts.Visible && plcGlobalDiscount.Visible)
            {
                customerObj.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel;
            }

            // Only registered customer can be enabled/diabled
            if (customerObj.CustomerIsRegistered)
            {
                customerObj.CustomerEnabled = chkCustomerEnabled.Checked;
            }

            bool refreshHeader = true;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                // Create user for customer
                if (chkHasLogin.Checked)
                {
                    UserInfo ui = new UserInfo();
                    ui.UserName = txtUserName.Text.Trim();
                    ui.FullName = customerObj.CustomerFirstName + " " + customerObj.CustomerLastName;
                    ui.IsGlobalAdministrator = false;
                    ui.UserEnabled = true;

                    UserInfoProvider.SetPassword(ui, passStrength.Text);
                    UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                    customerObj.CustomerEnabled = true;
                    customerObj.CustomerUserID = ui.UserID;

                    refreshHeader = true;
                }

                // Save customer
                CustomerInfoProvider.SetCustomerInfo(customerObj);

                // Enable/disable coresponding registered user
                if (customerObj.CustomerIsRegistered && !chkHasLogin.Checked)
                {
                    UserInfo ui = UserInfoProvider.GetUserInfo(customerObj.CustomerUserID);

                    // If the customer already has the record in the CMS_User table, update email
                    if (ui != null)
                    {
                        ui.Email = customerObj.CustomerEmail;
                        UserInfoProvider.SetUserInfo(ui);
                    }

                    // Save site specific values
                    UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(customerObj.CustomerUserID, CMSContext.CurrentSiteID);
                    if (userSite != null)
                    {
                        userSite.UserPreferredCurrencyID = drpCurrency.CurrencyID;
                        userSite.UserPreferredPaymentOptionID = drpPayment.PaymentID;
                        userSite.UserPreferredShippingOptionID = drpShipping.ShippingID;
                        userSite.UserDiscountLevelID = drpDiscountLevel.DiscountLevel;

                        UserSiteInfoProvider.SetUserSiteInfo(userSite);
                    }
                }

                // Commit transaction
                tr.Commit();
            }

            URLHelper.Redirect("Customer_Edit_General.aspx?customerid=" + Convert.ToString(customerObj.CustomerID) + "&saved=1&hidebreadcrumbs=" + QueryHelper.GetInteger("hidebreadcrumbs", 0) + "&siteId=" + SiteID + (refreshHeader ? "&refreshHeader=1" : ""));
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
        }
    }
Exemplo n.º 13
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        bool global = (editedSiteId <= 0);

        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(global))
        {
            // Check module permissions
            if (global)
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
            }
            else
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
            }
        }

        // Check input value from textboxs
        string errorMessage = new Validator().NotEmpty(txtDisplayName.Text, GetString("general.requiresdisplayname"))
                              .NotEmpty(txtCategoryName.Text, GetString("general.requirescodename"))
                              .IsIdentificator(txtCategoryName.Text, GetString("optioncategory_new.errorNotIdentificator")).Result;

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string             siteWhere         = (ConfiguredSiteID > 0) ? " AND (CategorySiteID = " + ConfiguredSiteID + " OR CategorySiteID IS NULL)" : "";
            DataSet            ds = OptionCategoryInfoProvider.GetOptionCategories("CategoryName = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'" + siteWhere, null, 1, null);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                optionCategoryObj = new OptionCategoryInfo(ds.Tables[0].Rows[0]);
            }

            // If category code name value is unique
            if (optionCategoryObj == null)
            {
                // Create, fill and set OptionCategoryInfo object
                optionCategoryObj = new OptionCategoryInfo();
                optionCategoryObj.CategoryDisplayName    = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName           = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType  = radSelection.Checked ? OptionCategorySelectionTypeEnum.Dropdownlist : OptionCategorySelectionTypeEnum.TextBox;
                optionCategoryObj.CategoryEnabled        = true;
                optionCategoryObj.CategoryDefaultRecord  = "";
                optionCategoryObj.CategoryDefaultOptions = "";
                optionCategoryObj.CategorySiteID         = ConfiguredSiteID;

                // Create category and option under transaction
                using (CMSTransactionScope tr = new CMSTransactionScope())
                {
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    if (radText.Checked)
                    {
                        // Create text product option
                        SKUInfo option = new SKUInfo()
                        {
                            SKUOptionCategoryID = optionCategoryObj.CategoryID,
                            SKUProductType      = SKUProductTypeEnum.Text,
                            SKUSiteID           = ConfiguredSiteID,
                            SKUName             = optionCategoryObj.CategoryDisplayName,
                            SKUDepartmentID     = 0,
                            SKUPrice            = 0,
                            SKUNeedsShipping    = false,
                            SKUWeight           = 0,
                            SKUEnabled          = true
                        };

                        SKUInfoProvider.SetSKUInfo(option);
                    }

                    // Commit a transaction
                    tr.Commit();
                }

                URLHelper.Redirect("OptionCategory_Edit.aspx?categoryId=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + SiteID);
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = GetString("optioncategory_new.errorExistingCodeName");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }
    /// <summary>
    /// Saves data to DB without validation and permissions check.
    /// </summary>
    private void SaveData()
    {
        // If customer does not already exist, create new one
        if (Customer == null)
        {
            Customer = new CustomerInfo();
            Customer.CustomerSiteID = currentSiteId;
            Customer.CustomerEnabled = true;
        }

        Customer.CustomerEmail = txtCustomerEmail.Text.Trim().Truncate(100);
        Customer.CustomerFax = txtCustomerFax.Text.Trim();
        Customer.CustomerLastName = txtCustomerLastName.Text.Trim();
        Customer.CustomerPhone = txtCustomerPhone.Text.Trim();
        Customer.CustomerFirstName = txtCustomerFirstName.Text.Trim();
        Customer.CustomerCompany = txtCustomerCompany.Text.Trim();
        Customer.CustomerCountryID = drpCountry.CountryID;
        Customer.CustomerStateID = drpCountry.StateID;
        Customer.CustomerOrganizationID = txtOraganizationID.Text.Trim();
        Customer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();

        // Set customer's preferences
        Customer.CustomerPreferredCurrencyID = drpCurrency.CurrencyID;
        Customer.CustomerPreferredPaymentOptionID = drpPayment.PaymentID;
        Customer.CustomerPreferredShippingOptionID = drpShipping.ShippingID;

        if (plcDiscounts.Visible && plcGlobalDiscount.Visible)
        {
            Customer.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel;
        }

        // Only registered customer can be enabled/disabled
        if (Customer.CustomerIsRegistered)
        {
            Customer.CustomerEnabled = chkCustomerEnabled.Checked;
        }

        using (CMSTransactionScope tr = new CMSTransactionScope())
        {
            bool newUserCreated = false;

            // Create user for customer
            if (chkHasLogin.Checked)
            {
                UserInfo ui = new UserInfo();
                ui.UserName = txtUserName.Text.Trim();
                ui.FullName = Customer.CustomerFirstName + " " + Customer.CustomerLastName;
                ui.IsGlobalAdministrator = false;
                ui.UserEnabled = true;

                UserInfoProvider.SetPassword(ui, passStrength.Text);
                UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                Customer.CustomerEnabled = true;
                Customer.CustomerUserID = ui.UserID;

                chkCustomerEnabled.Checked = Customer.CustomerEnabled;

                newUserCreated = true;

                // Show fields requiring registered customer
                pnlEdit.Visible = false;
                pnlStatic.Visible = true;
                plcDiscounts.Visible = true;
                plcPreferences.Visible = true;
                chkHasLogin.Checked = false;
                plcSiteDiscount.Visible = true;
                lblUserNameStaticValue.Text = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName));
                if (AllowEditUser)
                {
                    btnEditUser.OnClientClick = "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Membership/Pages/Users/User_Edit_Frameset.aspx") + "?userid=" + Customer.CustomerUserID + "', 'UserEdit', 950, 700); return false;";
                    btnEditUser.Visible = true;
                }

                // Hide global discount level selector when global levels not allowed
                plcGlobalDiscount.Visible = allowGlobalDiscountLevels;
            }

            // Save customer
            CustomerInfoProvider.SetCustomerInfo(Customer);

            // Enable/disable corresponding registered user
            if (Customer.CustomerIsRegistered && !newUserCreated)
            {
                UserInfo ui = UserInfoProvider.GetUserInfo(Customer.CustomerUserID);

                // If the customer already has the record in the CMS_User table, update email
                if (ui != null)
                {
                    ui.Email = Customer.CustomerEmail;
                    UserInfoProvider.SetUserInfo(ui);
                }

                // Save site specific values
                UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, currentSiteId);
                if (userSite != null)
                {
                    userSite.UserPreferredCurrencyID = drpCurrency.CurrencyID;
                    userSite.UserPreferredPaymentOptionID = drpPayment.PaymentID;
                    userSite.UserPreferredShippingOptionID = drpShipping.ShippingID;
                    userSite.UserDiscountLevelID = drpDiscountLevel.DiscountLevel;

                    UserSiteInfoProvider.SetUserSiteInfo(userSite);
                }
            }

            // Commit transaction
            tr.Commit();

            // Raise OnSaved event
            RaiseOnSaved();
        }
    }
Exemplo n.º 15
0
        private static void ImportWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = (BackgroundWorker)sender;

                // Save import profile
                if (ImportProfile.SaveImportProfile && !ImportProfile.UsesConsole)
                {
                    SaveFile(SaveImportProfile);
                }

                // Decide whether to import
                if (!ImportProfile.ImportNow && !ImportProfile.UsesConsole)
                {
                    return;
                }

                using (new CMSActionContext()
                {
                    LogEvents = false, ContinuousIntegrationAllowObjectSerialization = false
                })
                {
                    #region "Initialization"

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    DateTime start = DateTime.Now;

                    // Initialize CMS context
                    CMSInit();

                    if (ImportProfile.UsesConsole)
                    {
                        // Ensure object in case they are not present in import profile
                        EnsureObjects();
                    }

                    if (ImportProfile.ImportUsersOnlyFromSelectedRoles)
                    {
                        // Narrow down imported users according to imported roles
                        ImportProfile.Users.Clear();
                    }

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    // Initialize cumulative changed users and roles storages
                    var rolesChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.RolesCreated, WellKnownEventLogEventsEnum.RolesUpdated, WellKnownEventLogEventsEnum.RolesDeleted);
                    var usersChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.UsersCreated, WellKnownEventLogEventsEnum.UsersUpdated, WellKnownEventLogEventsEnum.UsersDeleted);

                    #endregion

                    // Delete non-existing objects (this also prevents conflicting code names)
                    if (ImportProfile.DeleteNotExistingObjects)
                    {
                        DeleteNonExistingObjects(usersChanged, rolesChanged);
                    }

                    #region "Role import"

                    foreach (var siteInfo in ImportProfile
                             .Sites
                             .Select(site => SiteInfo.Provider.Get(site.Key))
                             .Where(info => info != null))
                    {
                        foreach (Guid groupGuid in ImportProfile.Groups)
                        {
                            // Import canceled
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // Try to get group
                            IPrincipalObject group = PrincipalProvider.GetPrincipalObject(groupGuid);

                            // If group is still null
                            if (group == null)
                            {
                                MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject"));
                                warnings++;
                                // If deleting of not existing objects is enabled
                                if (ImportProfile.DeleteNotExistingObjects)
                                {
                                    DeleteRole(siteInfo, groupGuid);
                                }
                            }
                            else
                            {
                                // Get role description
                                string roleDescription = String.Empty;
                                if (ImportProfile.ImportRoleDescription && (group.Description != null))
                                {
                                    roleDescription = group.Description;
                                }

                                // Get correct role name format
                                string roleCodeName = group.GetCMSCodeName(true);

                                // Get role display name
                                string roleDisplayName = group.GetCMSDisplayName();

                                // Get safe role name
                                roleCodeName = ValidationHelper.GetSafeRoleName(roleCodeName, siteInfo.SiteName);

                                if (!String.IsNullOrEmpty(roleCodeName))
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_ImportingRole", roleDisplayName, CMS.Helpers.ResHelper.LocalizeString(siteInfo.DisplayName)));

                                    // Import role
                                    ImportRole(roleCodeName, roleDisplayName, siteInfo.SiteID, roleDescription, groupGuid, ImportProfile.UpdateObjectData, rolesChanged);

                                    if (ImportProfile.ImportUsersOnlyFromSelectedRoles)
                                    {
                                        ImportProfile.Users.AddRange(PrincipalProvider.GetUsersOf(group).Select(u => u.Identifier));
                                    }
                                }
                                else
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyRolename", group.Identifier));
                                    warnings++;
                                }
                            }
                        }
                    }

                    // Log created and updated and removed roles to EventLog
                    rolesChanged.WriteEventsToEventLog();

                    #endregion

                    #region "User import"

                    foreach (var user in ImportProfile
                             .Users
                             .Distinct()
                             .Select(userGuid => PrincipalProvider.GetPrincipalObject(userGuid)))
                    {
                        // Import canceled
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }

                        if (user == null)
                        {
                            MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject"));
                            continue;
                        }

                        string domainName = user.GetCMSCodeName(true);

                        if (!String.IsNullOrEmpty(domainName))
                        {
                            // Get user info object
                            UserInfo userInfo = (UserInfo.Provider.Get((Guid)user.Identifier) ?? UserInfo.Provider.Get(domainName));
                            bool     newUser  = (userInfo == null);

                            // When is desired to import new users only from selected roles
                            if (newUser && ImportProfile.ImportNewUsersOnlyFromSelectedRoles)
                            {
                                // Skip users that does not belong to one of selected role
                                bool skip = ImportProfile.Groups.Cast <Guid>().All(groupGuid => !user.IsPrincipalInGroup(groupGuid));
                                if (skip)
                                {
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SkippingDoesNotBelongToSelectedRole", domainName));
                                    continue;
                                }
                            }

                            if (ImportProfile.UpdateObjectData || newUser)
                            {
                                if (userInfo == null)
                                {
                                    userInfo = new UserInfo();
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_ImportingUser", domainName));
                                }
                                else
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_UpdatingUser", domainName));
                                }

                                using (var transaction = new CMSTransactionScope())
                                {
                                    if (newUser)
                                    {
                                        userInfo.UserIsDomain = true;
                                        userInfo.UserGUID     = (Guid)user.Identifier;

                                        // Set privilege level
                                        UserPrivilegeLevelEnum privilegeLevel = ImportProfile.ConfigureAsCMSEditor ? UserPrivilegeLevelEnum.Editor : UserPrivilegeLevelEnum.None;
                                        userInfo.SiteIndependentPrivilegeLevel = privilegeLevel;
                                    }

                                    if (userInfo.UserIsDomain)
                                    {
                                        // Set user's properties
                                        userInfo.UserIsExternal = true;
                                        userInfo.UserName       = domainName;
                                        userInfo.Enabled        = ValidationHelper.GetBoolean(user.Enabled, true);

                                        // Bind properties
                                        foreach (KeyValuePair <string, string> property in ImportProfile.UserProperties)
                                        {
                                            // Get attribute
                                            object attribute = user.GetProperty(property.Value);

                                            if (attribute != null)
                                            {
                                                try
                                                {
                                                    string attrValue;

                                                    // Get string representation of the attribute
                                                    if (attribute is float || attribute is double || attribute is decimal)
                                                    {
                                                        attrValue = String.Format(CultureInfo.InvariantCulture, "{0}", attribute);
                                                    }
                                                    else if (attribute.GetType() == typeof(byte[]))
                                                    {
                                                        attrValue = PrincipalProvider.GetSID(attribute);
                                                    }
                                                    else if (attribute.GetType().BaseType == typeof(MarshalByRefObject))
                                                    {
                                                        attrValue = PrincipalProvider.GetTimeFromInterval(attribute);
                                                    }
                                                    else
                                                    {
                                                        attrValue = attribute.ToString();
                                                    }

                                                    // Set property
                                                    userInfo.SetValue(property.Key, LimitLengthForField(attrValue, property.Key));
                                                }
                                                catch
                                                {
                                                    MessageLog.LogEvent(ResHelper.GetString("Log_ErrorParsingAttr", property.Value));
                                                    warnings++;
                                                }
                                            }
                                            else
                                            {
                                                FormFieldInfo field = UserFormInfo.GetFormField(property.Key);
                                                userInfo.SetValue(property.Key, field.GetPropertyValue(FormFieldPropertyEnum.DefaultValue));
                                            }
                                        }

                                        // Create full name if empty
                                        if (String.IsNullOrEmpty(userInfo.FullName))
                                        {
                                            userInfo.FullName = user.GetCMSDisplayName();
                                        }

                                        // Store user info object and its user-settings
                                        if (userInfo.ChangedColumns().Any())
                                        {
                                            // Store created/updated user for EventLog
                                            // User name is used, because AD accounts does not have to have first and/or given name specified (e.g. Guest, …)
                                            usersChanged.Add(userInfo.UserGUID, userInfo.UserName, newUser ? ChangeActionEnum.Created : ChangeActionEnum.Updated);

                                            UserInfo.Provider.Set(userInfo);
                                        }
                                    }
                                    else
                                    {
                                        MessageLog.LogEvent(ResHelper.GetString("Log_UserIsNotDomain", userInfo.UserName));
                                        warnings++;
                                    }

                                    transaction.Commit();
                                }
                            }
                            else
                            {
                                MessageLog.LogEvent(ResHelper.GetString("Log_SkippingExistingUser", domainName));
                            }

                            // Import canceled
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // Assign user to sites and roles (for domain users only)
                            if (!userInfo.UserIsDomain)
                            {
                                continue;
                            }


                            #region "Membership (roles) synchronization"

                            if (!newUser && !ImportProfile.UpdateMemberships && !ImportProfile.UpdateMemberships)
                            {
                                // No membership synchronization will be performed
                                continue;
                            }

                            // Initialize collection to cumulate membership changes
                            var memberShipChanges = new CumulatedRolesMembership();

                            // Load all user roles from DB
                            var userRoles = new HashSet <RoleInfo>(newUser
                                ? Enumerable.Empty <RoleInfo>() // non-existing user cannot be present in a single role (in DB)
                                : RoleInfo.Provider
                                                                   .Get()
                                                                   .WhereIn("RoleID",
                                                                            UserRoleInfo.Provider
                                                                            .Get()
                                                                            .WhereEquals("UserID", userInfo.UserID)
                                                                            .Column("RoleID"))
                                                                   .Columns("RoleID", "RoleGUID", "RoleDisplayName", "RoleIsDomain"));

                            // Store user's roles before membership synchronization
                            memberShipChanges.SetRolesBefore(userRoles);
                            foreach (KeyValuePair <string, List <Guid> > site in ImportProfile.Sites)
                            {
                                // Get site info object
                                var siteInfo = SiteInfo.Provider.Get(site.Key);
                                if (siteInfo != null)
                                {
                                    try
                                    {
                                        // Add user to this site
                                        UserSiteInfo.Provider.Add(userInfo.UserID, siteInfo.SiteID);
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageLog.LogEvent(ResHelper.GetString("Log_GeneralWarning", ex.Message));
                                        warnings++;
                                    }

                                    // Assign user to roles already existing in CMS
                                    if (newUser || ImportProfile.UpdateMemberships)
                                    {
                                        SetMemberships(user, userInfo, siteInfo, userRoles, site);
                                    }

                                    // Remove user from roles they is member no more
                                    if (!newUser && ImportProfile.UpdateMemberships)
                                    {
                                        RemoveExcessiveMemberships(user, userInfo, userRoles);
                                    }
                                }
                                else
                                {
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SiteNotExist", site.Key));
                                    warnings++;
                                }
                            }

                            // Store user's roles after membership synchronization
                            memberShipChanges.SetRolesAfter(userRoles);

                            // Log created and removed memberships to EventLog
                            memberShipChanges.WriteEventsToEventLog(userInfo.UserName);

                            #endregion
                        }
                        else
                        {
                            // Add message to log
                            MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyUsername", user.Identifier));
                            warnings++;
                        }
                    }

                    // Log created and updated and deleted users to EventLog
                    usersChanged.WriteEventsToEventLog();

                    #endregion

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    TimeSpan duration = DateTime.Now - start;

                    if (!worker.CancellationPending)
                    {
                        // Add message to log
                        MessageLog.LogEvent(warnings == 0
                            ? ResHelper.GetString("Log_ImportComplete", duration.Hours, duration.Minutes, duration.Seconds)
                            : ResHelper.GetString("Log_ImportCompleteWithWarnings", warnings, duration.Hours, duration.Minutes, duration.Seconds));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageLog.LogError(ResHelper.GetString("Error_General"), ex);
            }
        }
    /// <summary>
    /// Processes the step 2 of the wizard
    /// </summary>
    private void ProcessStep2(WizardNavigationEventArgs e)
    {
        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        if (dci != null)
        {
            var tm = new TableManager(null);

            using (var tr = new CMSTransactionScope())
            {
                // New document type has custom attributes -> no wizard steps will be omitted
                if (radCustom.Checked)
                {
                    // Actions after next button click
                    bool fromExisting = (Mode == NewClassWizardModeEnum.CustomTable) && radExistingTable.Checked;

                    string tableName = (fromExisting) ? drpExistingTables.SelectedValue : txtTableName.Text.Trim();

                    // Validate checkboxes first
                    string tableNameError = new Validator()
                        .NotEmpty(tableName, GetString("DocumentType_New.ErrorEmptyTableName"))
                        .IsIdentifier(tableName, GetString("class.ErrorIdentifier"))
                        .Result;

                    string primaryKeyNameEmpty = new Validator().NotEmpty(txtPKName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyPKName")).Result;

                    bool columnExists = DocumentHelper.ColumnExistsInDocumentView(txtPKName.Text.Trim());

                    // Textboxes are filled correctly
                    if ((tableNameError == "") && (primaryKeyNameEmpty == "") && (!columnExists))
                    {
                        try
                        {
                            bool tableExists = tm.TableExists(tableName);
                            if (fromExisting)
                            {
                                // Custom table from existing table - validate the table name
                                if (!tableExists)
                                {
                                    e.Cancel = true;

                                    // Table with the same name already exists
                                    ShowError(GetString("customtable.newwizard.tablenotexists"));
                                }

                                // Check primary key
                                List<string> primaryKeys = tm.GetPrimaryKeyColumns(tableName);
                                if ((primaryKeys == null) || (primaryKeys.Count != 1))
                                {
                                    e.Cancel = true;

                                    ShowError(GetString("customtable.newwizard.musthaveprimarykey"));
                                }
                                else if (!IsIdentityColumn(tableName, primaryKeys.First()))
                                {
                                    e.Cancel = true;
                                    ShowError(GetString("customtable.newwizard.mustbeidentitypk"));
                                }
                            }
                            else if (tableExists)
                            {
                                // Check if given table name already exists in database
                                e.Cancel = true;
                                ShowError(GetString("sysdev.class_edit_gen.tablenameunique"));
                            }
                            else if (Mode == NewClassWizardModeEnum.Class)
                            {
                                // Standard class in development mode
                                tm.CreateTable(tableName, txtPKName.Text.Trim(), !chbIsMNTable.Checked);
                            }
                            else
                            {
                                tm.CreateTable(tableName, txtPKName.Text.Trim());
                            }
                        }
                        catch (Exception ex)
                        {
                            // No movement to the next step
                            e.Cancel = true;

                            // Show error message if something caused unhandled exception
                            ShowError(ex.Message);
                        }

                        if ((pnlMessages2.ErrorLabel.Text == "") && !e.Cancel)
                        {
                            // Change table owner
                            try
                            {
                                string owner = "";

                                // Get site related DB object owner setting when creating new wizard and global otherwise
                                switch (Mode)
                                {
                                    case NewClassWizardModeEnum.DocumentType:
                                    case NewClassWizardModeEnum.Class:
                                    case NewClassWizardModeEnum.CustomTable:
                                        owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName);
                                        break;
                                }

                                if ((owner != "") && (owner.ToLowerCSafe() != "dbo"))
                                {
                                    tm.ChangeDBObjectOwner(tableName, owner);
                                    tableName = SqlHelper.GetSafeOwner(owner) + "." + tableName;
                                }
                            }
                            catch
                            {
                                // Suppress error
                            }

                            FormInfo fi;
                            if (fromExisting)
                            {
                                // From existing DB table
                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);

                                string formDef = FormHelper.GetXmlFormDefinitionFromXmlSchema(dci.ClassXmlSchema, false);
                                fi = new FormInfo(formDef);
                            }
                            else
                            {
                                // Create empty form info
                                fi = CreateEmptyFormInfo();

                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);
                            }

                            dci.ClassTableName = tableName;
                            dci.ClassFormDefinition = fi.GetXmlDefinition();
                            dci.ClassIsCoupledClass = true;

                            dci.ClassInheritsFromClassID = ValidationHelper.GetInteger(selInherits.Value, 0);

                            // Update class in DB
                            using (var context = new CMSActionContext())
                            {
                                // Disable logging into event log
                                context.LogEvents = false;

                                DataClassInfoProvider.SetDataClassInfo(dci);

                                UpdateInheritedClass(dci);
                            }

                            if (Mode == NewClassWizardModeEnum.CustomTable)
                            {
                                try
                                {
                                    InitCustomTable(dci, fi, tm);
                                }
                                catch (Exception ex)
                                {
                                    // Do not move to next step.
                                    e.Cancel = true;

                                    EventLogProvider.LogException("NewClassWizard", "CREATE", ex);

                                    string message = null;
                                    if (ex is MissingSQLTypeException)
                                    {
                                        var missingSqlType = (MissingSQLTypeException) ex;
                                        message = String.Format(GetString("customtable.sqltypenotsupported"), missingSqlType.UnsupportedType, missingSqlType.ColumnName, missingSqlType.RecommendedType);
                                    }
                                    else
                                    {
                                        message = ex.Message;
                                    }

                                    pnlMessages2.ShowError(message);
                                    pnlMessages2.Visible = true;
                                }
                            }

                            if (!e.Cancel)
                            {
                                // Remember that no steps were omitted
                                SomeStepsOmitted = false;

                                // Prepare next step (3)

                                // Disable previous steps' viewstates
                                DisablePreviousStepsViewStates(e.CurrentStepIndex);

                                // Enable next step's viewstate
                                EnableNextStepViewState(e.CurrentStepIndex);

                                // Set field editor class name
                                FieldEditor.ClassName = ClassName;

                                // Fill field editor in the next step
                                FieldEditor.Reload(null);

                                wzdStep3.Title = GetString("general.fields");

                                // Set new step header based on the development mode setting
                                switch (Mode)
                                {
                                    case NewClassWizardModeEnum.DocumentType:
                                        ucHeader.Description = GetString("DocumentType_New_Step3.Description");
                                        break;

                                    case NewClassWizardModeEnum.Class:
                                        ucHeader.Description = GetString("sysdev.class_new_Step3.Description");
                                        break;

                                    case NewClassWizardModeEnum.CustomTable:
                                        ucHeader.Description = GetString("customtable.newwizzard.Step3Description");
                                        break;
                                }
                            }
                        }
                    }
                    // Some textboxes are not filled correctly
                    else
                    {
                        // Prepare current step (2)

                        // No movement to the next step
                        e.Cancel = true;

                        // Show errors
                        if (!String.IsNullOrEmpty(tableNameError))
                        {
                            lblTableNameError.Text = tableNameError;
                            lblTableNameError.Visible = true;
                        }
                        else
                        {
                            lblTableNameError.Visible = false;
                        }

                        if (!String.IsNullOrEmpty(primaryKeyNameEmpty))
                        {
                            lblPKNameError.Visible = true;
                            lblPKNameError.Text = primaryKeyNameEmpty;
                        }
                        else
                        {
                            lblPKNameError.Visible = false;
                        }

                        if (columnExists)
                        {
                            pnlMessages2.ShowError(GetString("DocumentType_New_Step2.ErrorColumnExists"));
                            pnlMessages2.Visible = true;
                        }

                        wzdStep2.Title = GetString("DocumentType_New_Step2.Title");

                        // Reset the header
                        switch (Mode)
                        {
                            case NewClassWizardModeEnum.DocumentType:
                                ucHeader.Description = GetString("DocumentType_New_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.Class:
                                ucHeader.Description = GetString("sysdev.class_new_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.CustomTable:
                                ucHeader.Description = GetString("customtable.newwizzard.Step2Description");
                                break;
                        }
                    }
                }
                // New document type is only the container -> some wizard steps will be omitted
                else
                {
                    // Actions after next button click

                    dci.ClassIsCoupledClass = false;

                    // Update class in DB
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging into event log
                        context.LogEvents = false;

                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }

                    // Remember that some steps were omitted
                    SomeStepsOmitted = true;
                    IsContainer = true;

                    // Prepare next step (5) - skip steps 3 and 4

                    // Disable previous steps' viewstates
                    DisablePreviousStepsViewStates(3);

                    // Enable next step's viewstate
                    EnableNextStepViewState(3);

                    PrepareStep5();
                    // Go to the step 5 (indexed from 0)
                    wzdNewDocType.ActiveStepIndex = 4;
                }

                // Create new icon if the wizard is used to create new document type
                if (Mode == NewClassWizardModeEnum.DocumentType)
                {
                    // Setup icon class for new doc. type
                    string iconClass = (SomeStepsOmitted) ? DEFAULT_CLASS_ICON : DEFAULT_COUPLED_CLASS_ICON;
                    dci.SetValue("ClassIconClass", iconClass);
                }

                if (!e.Cancel)
                {
                    tr.Commit();
                }
            }
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        bool global = (editedSiteId <= 0);

        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(global))
        {
            // Check module permissions
            if (global)
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
            }
            else
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
            }
        }

        // Validate the form
        string errorMessage = ValidateForm();

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string             siteWhere         = (editedSiteId > 0) ? " AND (CategorySiteID = " + editedSiteId + " OR CategorySiteID IS NULL)" : "";
            DataSet            ds = OptionCategoryInfoProvider.GetOptionCategories("CategoryName = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'" + siteWhere, null, 1, null);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                optionCategoryObj = new OptionCategoryInfo(ds.Tables[0].Rows[0]);
            }

            // If category code name value is unique
            if ((optionCategoryObj == null) || (optionCategoryObj.CategoryID == categoryID))
            {
                // If optionCategory doesn't already exist, create new one
                if (optionCategoryObj == null)
                {
                    optionCategoryObj = OptionCategoryInfoProvider.GetOptionCategoryInfo(categoryID);
                    if (optionCategoryObj == null)
                    {
                        optionCategoryObj = new OptionCategoryInfo();
                        optionCategoryObj.CategorySiteID = editedSiteId;
                    }
                }

                // Set category properties
                optionCategoryObj.CategoryID             = categoryID;
                optionCategoryObj.CategoryDisplayName    = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName           = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType  = GetOptionCategoryEnum(drpCategorySelectionType.SelectedValue);
                optionCategoryObj.CategoryDefaultOptions = productOptionSelector.GetSelectedSKUOptions();
                optionCategoryObj.CategoryDescription    = txtCategoryDecription.Text.Trim();
                optionCategoryObj.CategoryDefaultRecord  = txtDefaultRecord.Text.Trim();
                optionCategoryObj.CategoryEnabled        = chkCategoryEnabled.Checked;
                optionCategoryObj.CategoryDisplayPrice   = chkCategoryDisplayPrice.Checked;
                optionCategoryObj.CategoryTextMaxLength  = ValidationHelper.GetInteger(txtTextMaxLength.Text.Trim(), 0);

                using (CMSTransactionScope tran = new CMSTransactionScope())
                {
                    // Save changes
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    // Add text option to text category only if it is empty
                    if (((optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextBox) ||
                         (optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextArea)) &&
                        (SKUInfoProvider.GetSKUOptionsCount(categoryID) == 0))
                    {
                        // Create default text product option
                        SKUInfo option = new SKUInfo();
                        option.SKUName        = optionCategoryObj.CategoryDisplayName;
                        option.SKUDescription = optionCategoryObj.CategoryDescription;
                        option.SKUSiteID      = optionCategoryObj.CategorySiteID;
                        option.SKUPrice       = 0;
                    }

                    tran.Commit();
                }

                // If hidebreadcrumbs (is in modal window)
                if (QueryHelper.GetBoolean("hidebreadcrumbs", false))
                {
                    // Close window and refresh opener
                    ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "CloseAndRefresh", ScriptHelper.GetScript("parent.wopener.Refresh(); parent.window.close();"));
                }
                else
                {
                    // Normal save
                    //URLHelper.Redirect("OptionCategory_Edit_General.aspx?CategoryID=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + this.SiteID);
                    ScriptHelper.RefreshTabHeader(this, "general");

                    lblInfo.Visible = true;
                    lblInfo.Text    = GetString("General.ChangesSaved");
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = GetString("optioncategory_new.errorExistingCodeName");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }
    /// <summary>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);

        tree.AllowAsyncActions = false;

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentCulture));

            bool oneSubmission = chkSeparateSubmissions.Checked;

            // Prepare translation settings
            TranslationSettings settings = new TranslationSettings();
            settings.TargetLanguage             = targetCulture;
            settings.TranslateWebpartProperties = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
            settings.SourceLanguage             = translationElem.FromLanguage;
            settings.Instructions           = translationElem.Instructions;
            settings.Priority               = translationElem.Priority;
            settings.TranslateAttachments   = translationElem.ProcessBinary;
            settings.ProcessBinary          = translationElem.ProcessBinary;
            settings.TranslationDeadline    = translationElem.Deadline;
            settings.TranslationServiceName = translationElem.SelectedService;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                // Get the translation provider
                AbstractMachineTranslationService machineService = null;
                AbstractHumanTranslationService   humanService   = null;
                TranslationSubmissionInfo         submission     = null;
                TranslationServiceInfo            ti             = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
                if (ti != null)
                {
                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);

                            if (oneSubmission)
                            {
                                submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, CMSContext.CurrentUser.UserID, CMSContext.CurrentSiteID, "Document submission " + DateTime.Now);
                            }
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            // Prepare the where condition
                            string where = SqlHelperClass.GetWhereCondition("NodeID", (int[])nodeIds.ToArray(typeof(int)));
                            string columns = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";

                            string submissionFileName = "";
                            string submissionName     = "";
                            int    charCount          = 0;
                            int    wordCount          = 0;

                            int docCount = 0;

                            // Get the documents in target culture to be able to check if "Skip already translated" option is on
                            // Combine both, source and target culture (at least one hit has to be found - to find the source of translation)
                            where = SqlHelperClass.AddWhereCondition(where, "DocumentCulture = N'" + settings.SourceLanguage + "' OR DocumentCulture = N'" + settings.TargetLanguage + "'");

                            DataSet ds = tree.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                List <int> processedNodes = new List <int>();

                                // Translate the documents
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    refreshId = ValidationHelper.GetInteger(dr["NodeParentID"], 0);
                                    int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                                    if (!processedNodes.Contains(nodeId))
                                    {
                                        processedNodes.Add(nodeId);

                                        string aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], "");
                                        string culture   = ValidationHelper.GetString(dr["DocumentCulture"], "");

                                        if (chkSkipTranslated.Checked)
                                        {
                                            if (culture == settings.TargetLanguage)
                                            {
                                                // Document already exists in requested culture, skip it
                                                AddLog(string.Format(ResHelper.GetString("content.translatedalready"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));
                                                continue;
                                            }
                                        }

                                        AddLog(string.Format(ResHelper.GetString("content.translating"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));

                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);

                                        // Save the first document as a base for submission name
                                        if (string.IsNullOrEmpty(submissionName))
                                        {
                                            submissionName = node.GetDocumentName();
                                        }
                                        if (string.IsNullOrEmpty(submissionFileName))
                                        {
                                            submissionFileName = node.NodeAlias;
                                        }

                                        docCount++;

                                        // Submit the document
                                        if (machineService != null)
                                        {
                                            TranslationServiceHelper.Translate(machineService, settings, node);
                                        }
                                        else
                                        {
                                            if (oneSubmission && (humanService != null))
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false);
                                                TranslationSubmissionItemInfo submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID);

                                                charCount += submissionItem.SubmissionItemCharCount;
                                                wordCount += submissionItem.SubmissionItemWordCount;
                                            }
                                            else
                                            {
                                                TranslationServiceHelper.SubmitToTranslation(settings, node, out submission);
                                            }
                                        }
                                    }
                                }

                                if (docCount > 0)
                                {
                                    if (oneSubmission && (humanService != null))
                                    {
                                        AddLog(ResHelper.GetString("content.submitingtranslation"));

                                        // Set submission name
                                        int itemCount = processedNodes.Count;
                                        if (itemCount > 1)
                                        {
                                            submissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), itemCount - 1);
                                        }
                                        submission.SubmissionName      = submissionName;
                                        submission.SubmissionCharCount = charCount;
                                        submission.SubmissionWordCount = wordCount;
                                        submission.SubmissionItemCount = itemCount;
                                        submission.SubmissionParameter = submissionFileName;

                                        string err = humanService.CreateSubmission(submission);
                                        if (!string.IsNullOrEmpty(err))
                                        {
                                            AddError(err);
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                        }
                        else
                        {
                            AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentCulture));
                        }
                    }
                }

                tr.Commit();
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (isModal)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog();";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }
    /// <summary>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);
        tree.AllowAsyncActions = false;

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentCulture));

            bool oneSubmission = chkSeparateSubmissions.Checked;

            // Prepare translation settings
            TranslationSettings settings = new TranslationSettings();
            settings.TargetLanguage = targetCulture;
            settings.TranslateWebpartProperties = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
            settings.SourceLanguage = translationElem.FromLanguage;
            settings.Instructions = translationElem.Instructions;
            settings.Priority = translationElem.Priority;
            settings.TranslateAttachments = translationElem.ProcessBinary;
            settings.ProcessBinary = translationElem.ProcessBinary;
            settings.TranslationDeadline = translationElem.Deadline;
            settings.TranslationServiceName = translationElem.SelectedService;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                // Get the translation provider
                AbstractMachineTranslationService machineService = null;
                AbstractHumanTranslationService humanService = null;
                TranslationSubmissionInfo submission = null;
                TranslationServiceInfo ti = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
                if (ti != null)
                {
                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);

                            if (oneSubmission)
                            {
                                submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, CMSContext.CurrentUser.UserID, CMSContext.CurrentSiteID, "Document submission " + DateTime.Now);
                            }
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            // Prepare the where condition
                            string where = SqlHelperClass.GetWhereCondition("NodeID", (int[])nodeIds.ToArray(typeof(int)));
                            string columns = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";

                            string submissionFileName = "";
                            string submissionName = "";
                            int charCount = 0;
                            int wordCount = 0;

                            int docCount = 0;

                            // Get the documents in target culture to be able to check if "Skip already translated" option is on
                            // Combine both, source and target culture (at least one hit has to be found - to find the source of translation)
                            where = SqlHelperClass.AddWhereCondition(where, "DocumentCulture = N'" + settings.SourceLanguage + "' OR DocumentCulture = N'" + settings.TargetLanguage + "'");

                            DataSet ds = tree.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                List<int> processedNodes = new List<int>();

                                // Translate the documents
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    refreshId = ValidationHelper.GetInteger(dr["NodeParentID"], 0);
                                    int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                                    if (!processedNodes.Contains(nodeId))
                                    {
                                        processedNodes.Add(nodeId);

                                        string aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], "");
                                        string culture = ValidationHelper.GetString(dr["DocumentCulture"], "");

                                        if (chkSkipTranslated.Checked)
                                        {
                                            if (culture == settings.TargetLanguage)
                                            {
                                                // Document already exists in requested culture, skip it
                                                AddLog(string.Format(ResHelper.GetString("content.translatedalready"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));
                                                continue;
                                            }
                                        }

                                        AddLog(string.Format(ResHelper.GetString("content.translating"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));

                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);

                                        // Save the first document as a base for submission name
                                        if (string.IsNullOrEmpty(submissionName))
                                        {
                                            submissionName = node.GetDocumentName();
                                        }
                                        if (string.IsNullOrEmpty(submissionFileName))
                                        {
                                            submissionFileName = node.NodeAlias;
                                        }

                                        docCount++;

                                        // Submit the document
                                        if (machineService != null)
                                        {
                                            TranslationServiceHelper.Translate(machineService, settings, node);
                                        }
                                        else
                                        {
                                            if (oneSubmission && (humanService != null))
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false);
                                                TranslationSubmissionItemInfo submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID);

                                                charCount += submissionItem.SubmissionItemCharCount;
                                                wordCount += submissionItem.SubmissionItemWordCount;
                                            }
                                            else
                                            {
                                                TranslationServiceHelper.SubmitToTranslation(settings, node, out submission);
                                            }
                                        }
                                    }
                                }

                                if (docCount > 0)
                                {
                                    if (oneSubmission && (humanService != null))
                                    {
                                        AddLog(ResHelper.GetString("content.submitingtranslation"));

                                        // Set submission name
                                        int itemCount = processedNodes.Count;
                                        if (itemCount > 1)
                                        {
                                            submissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), itemCount - 1);
                                        }
                                        submission.SubmissionName = submissionName;
                                        submission.SubmissionCharCount = charCount;
                                        submission.SubmissionWordCount = wordCount;
                                        submission.SubmissionItemCount = itemCount;
                                        submission.SubmissionParameter = submissionFileName;

                                        string err = humanService.CreateSubmission(submission);
                                        if (!string.IsNullOrEmpty(err))
                                        {
                                            AddError(err);
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                        }
                        else
                        {
                            AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentCulture));
                        }
                    }
                }

                tr.Commit();
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (isModal)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog();";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }
    /// <summary>
    /// Processes the step 1 of the wizard
    /// </summary>
    private void ProcessStep1(WizardNavigationEventArgs e)
    {
        // Actions after next button click

        // Validate checkboxes first
        string errorMessage = "";

        // Display proper error message based on development mode wizard setting
        switch (Mode)
        {
            case NewClassWizardModeEnum.DocumentType:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("DocumentType_New.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("DocumentType_New.NamespaceNameIdentifier")).Result;
                break;

            case NewClassWizardModeEnum.Class:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("sysdev.class_new.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("sysdev.class_new.NamespaceNameIdentifier")).Result;
                break;

            case NewClassWizardModeEnum.CustomTable:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("customtable.newwizzard.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("customtable.newwizzard.NamespaceNameIdentifier")).Result;
                break;
        }

        if (errorMessage == "")
        {
            // Set new class info
            DataClassInfo dci = new DataClassInfo();
            dci.ClassDisplayName = txtDisplayName.Text.Trim();
            dci.ClassName = txtNamespaceName.Text.Trim() + "." + txtCodeName.Text.Trim();

            // Set class type according development mode setting
            switch (Mode)
            {
                case NewClassWizardModeEnum.DocumentType:
                    dci.ClassIsDocumentType = true;
                    dci.ClassUsePublishFromTo = true;
                    break;

                case NewClassWizardModeEnum.Class:
                    dci.ClassShowAsSystemTable = false;
                    dci.ClassShowTemplateSelection = false;
                    dci.ClassIsDocumentType = false;
                    dci.ClassCreateSKU = false;
                    dci.ClassIsProduct = false;
                    dci.ClassIsMenuItemType = false;
                    dci.ClassUsesVersioning = false;
                    dci.ClassUsePublishFromTo = false;
                    break;

                case NewClassWizardModeEnum.CustomTable:
                    dci.ClassShowAsSystemTable = false;
                    dci.ClassShowTemplateSelection = false;
                    dci.ClassIsDocumentType = false;
                    dci.ClassCreateSKU = false;
                    dci.ClassIsProduct = false;
                    dci.ClassIsMenuItemType = false;
                    dci.ClassUsesVersioning = false;
                    dci.ClassUsePublishFromTo = false;
                    // Sets custom table
                    dci.ClassIsCustomTable = true;
                    break;
            }

            try
            {
                using (var tr = new CMSTransactionScope())
                {
                    // Insert new class into DB
                    DataClassInfoProvider.SetDataClass(dci);

                    // Set permissions and queries
                    switch (Mode)
                    {
                        case NewClassWizardModeEnum.DocumentType:
                            // Ensure default permissions
                            PermissionNameInfoProvider.CreateDefaultClassPermissions(dci.ClassID);

                            // Generate special document queries, for possible premature exit from wizzard
                            if (SqlGenerator.GenerateDefaultQueriesToDB)
                            {
                                SqlGenerator.GenerateQuery(dci.ClassName, QueryProvider.QUERYNAME_SEARCHTREE, SqlOperationTypeEnum.SearchTree, false, false);
                                SqlGenerator.GenerateQuery(dci.ClassName, QueryProvider.QUERYNAME_SELECTDOCUMENTS, SqlOperationTypeEnum.SelectDocuments, false, false);
                                SqlGenerator.GenerateQuery(dci.ClassName, QueryProvider.QUERYNAME_SELECTVERSIONS, SqlOperationTypeEnum.SelectVersions, false, false);
                            }
                            break;

                        case NewClassWizardModeEnum.Class:
                            break;

                        case NewClassWizardModeEnum.CustomTable:
                            // Ensure default custom table permissions
                            PermissionNameInfoProvider.CreateDefaultCustomTablePermissions(dci.ClassID);
                            break;
                    }

                    tr.Commit();
                }
            }
            catch (Exception ex)
            {
                // No movement to the next step
                e.Cancel = true;

                // Class with the same class name already exists
                lblErrorStep1.Visible = true;
                lblErrorStep1.Text = ex.Message;

                EventLogProvider.LogException("NewClassWizard", "CREATE", ex);
            }

            // Prepare next step (2)
            if (lblErrorStep1.Text == "")
            {
                // Disable previous steps' viewstates
                DisablePreviousStepsViewStates(e.CurrentStepIndex);

                // Enable next step's viewstate
                EnableNextStepViewState(e.CurrentStepIndex);

                // Save ClassName to viewstate to use in the next steps
                ClassName = dci.ClassName;

                // Prefill textboxes in the next step with default values
                txtTableName.Text = txtNamespaceName.Text.Trim() + "_" + txtCodeName.Text.Trim();
                txtPKName.Text = FirstLetterToUpper(txtCodeName.Text.Trim() + "ID");

                wzdStep2.Title = GetString("DocumentType_New_Step2.Title");

                // Prepare next step by mode setting
                switch (Mode)
                {
                    case NewClassWizardModeEnum.DocumentType:
                        {
                            // Document type
                            lblPKName.Text = GetString("DocumentType_New.PrimaryKeyName");
                            lblTableName.Text = GetString("DocumentType_New.TableName");
                            radCustom.Text = GetString("DocumentType_New.Custom");

                            // Display container option based on the development mode setting
                            radContainer.Text = GetString("DocumentType_New.Container");
                            radContainer.Visible = true;

                            ucHeader.Description = GetString("DocumentType_New_Step2.Description");

                            // Setup the inheritance selector
                            plcDocTypeOptions.Visible = true;
                            selInherits.WhereCondition = "ClassIsCoupledClass = 1 AND ClassID <> " + dci.ClassID;
                        }
                        break;

                    case NewClassWizardModeEnum.Class:
                        {
                            // Standard class
                            lblPKName.Text = GetString("sysdev.class_new.PrimaryKeyName");
                            lblTableName.Text = GetString("sysdev.class_new.TableName");
                            radCustom.Text = GetString("sysdev.class_new.Custom");
                            lblIsMNTable.Text = GetString("sysdev.class_new.MNTable");

                            radContainer.Visible = false;
                            if (SystemDevelopmentMode)
                            {
                                plcMNClassOptions.Visible = true;
                            }

                            ucHeader.Description = GetString("sysdev.class_new_Step2.Description");
                        }
                        break;

                    case NewClassWizardModeEnum.CustomTable:
                        {
                            // Custom table
                            lblPKName.Text = GetString("customtable.newwizzard.PrimaryKeyName");
                            lblTableName.Text = GetString("customtable.newwizzard.TableName");

                            radCustom.Visible = false;
                            radContainer.Visible = false;

                            radNewTable.Text = GetString("customtable.newwizard.newtable");
                            radExistingTable.Text = GetString("customtable.newwizard.existingtable");

                            plcExisting.Visible = true;

                            // Custom tables have always ItemID as primary key
                            txtPKName.Text = "ItemID";

                            // Primary key name can't be edited
                            txtPKName.Enabled = false;

                            // Show custom tables columns options
                            plcCustomTablesOptions.Visible = true;

                            lblItemGUID.Text = GetString("customtable.newwizzard.lblItemGUID");
                            lblItemCreatedBy.Text = GetString("customtable.newwizzard.lblItemCreatedBy");
                            lblItemCreatedWhen.Text = GetString("customtable.newwizzard.lblItemCreatedWhen");
                            lblItemModifiedBy.Text = GetString("customtable.newwizzard.lblItemModifiedBy");
                            lblItemModifiedWhen.Text = GetString("customtable.newwizzard.lblItemModifiedWhen");
                            lblItemOrder.Text = GetString("customtable.newwizzard.lblItemOrder");

                            ucHeader.Description = GetString("customtable.newwizzard.Step2Description");
                        }
                        break;
                }
            }
        }
        else
        {
            // No movement to the next step
            e.Cancel = true;

            // Textboxes are not filled correctly
            lblErrorStep1.Visible = true;
            lblErrorStep1.Text = errorMessage;
        }
    }
Exemplo n.º 21
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        string errorMessage = "";

        if ((txtCustomerCompany.Text == null || txtCustomerCompany.Text.Trim() == "") &&
            ((txtCustomerFirstName.Text == null || txtCustomerFirstName.Text.Trim() == "") ||
             (txtCustomerLastName.Text == null || txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }

        if (errorMessage == "")
        {
            if (this.chkCreateLogin.Checked)
            {
                errorMessage = new Validator().NotEmpty(txtUserName.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvUserName"))
                               .NotEmpty(passStrength.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvPassword1"))
                               .NotEmpty(txtPassword2.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvPassword2")).Result;

                // Check policy
                if ((errorMessage == "") && !passStrength.IsValid())
                {
                    errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }

                // Compare passwords
                if ((errorMessage == "") && (passStrength.Text != txtPassword2.Text))
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.DifferentPasswords");
                }
            }
        }

        if (errorMessage == "")
        {
            if (this.chkCreateLogin.Checked)
            {
                // If user already has the record in the CMS_User table
                UserInfo existingUser = UserInfoProvider.GetUserInfo(txtUserName.Text.Trim());
                if (existingUser != null)
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.UserExist");
                }
            }
        }

        if (errorMessage == "")
        {
            CustomerInfo customerObj = CustomerInfoProvider.GetCustomerInfo(customerid);

            // If customer doesn't already exist, create new one
            if (customerObj == null)
            {
                customerObj = new CustomerInfo();
                customerObj.CustomerSiteID = CMSContext.CurrentSiteID;
            }

            customerObj.CustomerLastName  = txtCustomerLastName.Text.Trim();
            customerObj.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            customerObj.CustomerCompany   = txtCustomerCompany.Text.Trim();
            customerObj.CustomerCountryID = drpCountry.CountryID;
            customerObj.CustomerStateID   = drpCountry.StateID;
            customerObj.CustomerEnabled   = true;
            //customerObj.CustomerCreated = ucCustomerCreated.SelectedDateTime;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                CustomerInfoProvider.SetCustomerInfo(customerObj);

                // If create login checked
                if (this.chkCreateLogin.Checked)
                {
                    UserInfo ui = new UserInfo();
                    ui.UserName = txtUserName.Text.Trim();
                    ui.FullName = customerObj.CustomerFirstName + " " + customerObj.CustomerLastName;
                    ui.IsGlobalAdministrator = false;
                    ui.SetValue("UserEnabled", true);
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    // Add user to current site
                    UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                    customerObj.CustomerUserID = ui.UserID;

                    CustomerInfoProvider.SetCustomerInfo(customerObj);
                }

                // Commit transaction
                tr.Commit();
            }

            URLHelper.Redirect("Customer_Edit_Frameset.aspx?customerid=" + Convert.ToString(customerObj.CustomerID) + "&saved=1");
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }
Exemplo n.º 22
0
    /// <summary>
    /// Copies role binding from parent UI element.
    /// </summary>
    /// <param name="element">Element which are permissions copied to</param>
    private void CopyFromParent(UIElementInfo element)
    {
        using (var tr = new CMSTransactionScope())
        {
            if (element != null)
            {
                // Delete existing bindings
                DataSet elemRoles = RoleUIElementInfoProvider.GetRoleUIElements("ElementID = " + element.ElementID, null);
                if (!DataHelper.DataSourceIsEmpty(elemRoles))
                {
                    foreach (DataRow dr in elemRoles.Tables[0].Rows)
                    {
                        // Get role id
                        int roleId = ValidationHelper.GetInteger(dr["RoleID"], 0);
                        // Remove binding
                        RoleUIElementInfoProvider.DeleteRoleUIElementInfo(roleId, element.ElementID);
                    }
                }

                // Add same bindings as parent has
                int parentElemId = element.ElementParentID;

                DataSet parentRoles = RoleUIElementInfoProvider.GetRoleUIElements("ElementID = " + parentElemId, null);
                if (!DataHelper.DataSourceIsEmpty(parentRoles))
                {
                    foreach (DataRow dr in parentRoles.Tables[0].Rows)
                    {
                        // Get role id
                        int roleId = ValidationHelper.GetInteger(dr["RoleID"], 0);
                        // Create binding
                        RoleUIElementInfoProvider.AddRoleUIElementInfo(roleId, element.ElementID);
                    }
                }
            }

            // Commit transaction
            tr.Commit();
        }

        // Invalidate all users
        UserInfo.TYPEINFO.InvalidateAllObjects();

        // Clear hashtables with users
        UserInfoProvider.Clear(true);
    }
Exemplo n.º 23
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        string errorMessage = "";

        if ((txtCustomerCompany.Text == null || txtCustomerCompany.Text.Trim() == "") &&
            ((txtCustomerFirstName.Text == null || txtCustomerFirstName.Text.Trim() == "") ||
             (txtCustomerLastName.Text == null || txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }

        if (errorMessage == "")
        {
            if (this.chkCreateLogin.Checked)
            {
                errorMessage = new Validator().NotEmpty(txtUserName.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvUserName"))
                                              .NotEmpty(passStrength.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvPassword1"))
                                              .NotEmpty(txtPassword2.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvPassword2")).Result;

                // Check policy
                if ((errorMessage == "") && !passStrength.IsValid())
                {
                    errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }

                // Compare passwords
                if ((errorMessage == "") && (passStrength.Text != txtPassword2.Text))
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.DifferentPasswords");
                }
            }
        }

        if (errorMessage == "")
        {
            if (this.chkCreateLogin.Checked)
            {
                // If user already has the record in the CMS_User table
                UserInfo existingUser = UserInfoProvider.GetUserInfo(txtUserName.Text.Trim());
                if (existingUser != null)
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.UserExist");
                }
            }
        }

        if (errorMessage == "")
        {
            CustomerInfo customerObj = CustomerInfoProvider.GetCustomerInfo(customerid);

            // If customer doesn't already exist, create new one
            if (customerObj == null)
            {
                customerObj = new CustomerInfo();
                customerObj.CustomerSiteID = CMSContext.CurrentSiteID;
            }

            customerObj.CustomerLastName = txtCustomerLastName.Text.Trim();
            customerObj.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            customerObj.CustomerCompany = txtCustomerCompany.Text.Trim();
            customerObj.CustomerCountryID = drpCountry.CountryID;
            customerObj.CustomerStateID = drpCountry.StateID;
            customerObj.CustomerEnabled = true;
            //customerObj.CustomerCreated = ucCustomerCreated.SelectedDateTime;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                CustomerInfoProvider.SetCustomerInfo(customerObj);

                // If create login checked
                if (this.chkCreateLogin.Checked)
                {
                    UserInfo ui = new UserInfo();
                    ui.UserName = txtUserName.Text.Trim();
                    ui.FullName = customerObj.CustomerFirstName + " " + customerObj.CustomerLastName;
                    ui.IsGlobalAdministrator = false;
                    ui.SetValue("UserEnabled", true);
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    // Add user to current site
                    UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                    customerObj.CustomerUserID = ui.UserID;

                    CustomerInfoProvider.SetCustomerInfo(customerObj);
                }

                // Commit transaction
                tr.Commit();
            }

            URLHelper.Redirect("Customer_Edit_Frameset.aspx?customerid=" + Convert.ToString(customerObj.CustomerID) + "&saved=1");
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
        }
    }
Exemplo n.º 24
0
        /// <summary>
        /// Unsubscribes subscriber.
        /// </summary>
        /// <param name="newsletterGuid">Newsletter unique identifier</param>
        /// <param name="subscriberGuid">Subscriber unique identifier</param>
        /// <param name="issueGuid">Issue unique identifier</param>
        /// <param name="unsubscribeFromAll">If true, subscriber is unsubscribed from all marketing materials</param>
        /// <param name="additionalInformation">Additional information (status message etc.)</param>
        /// <returns>Returns true if unsubscription was successful</returns>
        private bool UnsubscribeInternal(Guid newsletterGuid, Guid subscriberGuid, Guid issueGuid, bool unsubscribeFromAll, out string additionalInformation)
        {
            // Creates required Services
            var subscriptionService = Service <ISubscriptionService> .Entry();

            var unSubscriptionProvider = Service <IUnsubscriptionProvider> .Entry();

            // Validates Subscriber and Newsletter GUIDs
            if ((subscriberGuid == Guid.Empty) || (newsletterGuid == Guid.Empty))
            {
                // Either SubscriberGUID or NewsletterGUID was not supplied, don't unsubscribe
                additionalInformation = ResHelper.GetString("TestMvcDemo.News.InvallidUnsubscriptionLink");
                return(false);
            }

            // Gets information about subscriber, newsletter and issue
            SubscriberInfo subscriber = SubscriberInfoProvider.GetSubscriberInfo(subscriberGuid, SiteId);
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterGuid, SiteId);
            IssueInfo      issue      = IssueInfoProvider.GetIssueInfo(issueGuid, SiteId);

            if ((subscriber == null) || (newsletter == null) || (issue == null))
            {
                additionalInformation = ResHelper.GetString("TestMvcDemo.News.InvallidUnsubscriptionLink");
                return(false);
            }

            int?issueId = issue.IssueID;

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                try
                {
                    if (unsubscribeFromAll)
                    {
                        // Unsubscribes if not already unsubscribed
                        if (!unSubscriptionProvider.IsUnsubscribedFromAllNewsletters(subscriber.SubscriberEmail, newsletter.NewsletterSiteID))
                        {
                            subscriptionService.UnsubscribeFromAllNewsletters(subscriber.SubscriberEmail, SiteId, issueId);
                            tr.Commit();
                        }

                        additionalInformation = ResHelper.GetString("TestMvcDemo.News.UnsubscribedAll");
                        return(true);
                    }

                    // Unsubscribes if not already unsubscribed
                    if (!unSubscriptionProvider.IsUnsubscribedFromSingleNewsletter(subscriber.SubscriberEmail, newsletter.NewsletterID, newsletter.NewsletterSiteID))
                    {
                        subscriptionService.UnsubscribeFromSingleNewsletter(subscriber.SubscriberEmail, newsletter.NewsletterID, issueId);
                        tr.Commit();
                    }

                    additionalInformation = ResHelper.GetString("TestMvcDemo.News.Unsubscribed");
                    return(true);
                }
                catch (Exception exception)
                {
                    Service <IEventLogService> .Entry().LogException("Newsletters", "Unsubscribe", exception);

                    additionalInformation = ResHelper.GetString("newsletter.unsubscribefailed");
                    return(false);
                }
            }
        }
        /// <summary>
        /// Subscribes e-mail address to the specified newsletter. 
        /// If no subscriber with the given e-mail is found, a new subscriber is created.
        /// </summary>
        /// <remarks>
        /// Action fails when:
        /// <list type="bullet">
        /// <item>
        /// <description>Newsletter with the given name does not exist.</description>
        /// </item>
        /// <item>
        /// <description>Current license does not allow creating new subscribers.</description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterName">Name of the newsletter</param>
        /// <returns>Returns true if subscription was successful.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="email"/> or <paramref name="newsletterName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="newsletterName"/> is not valid.</exception>
        public virtual bool Subscribe(string email, string newsletterName)
        {
            if (email == null)
            {
                throw new ArgumentNullException("email");
            }

            if (newsletterName == null)
            {
                throw new ArgumentNullException("newsletterName");
            }

            // Gets information about newsletter on current site
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, SiteId);
            if (newsletter == null)
            {
                throw new ArgumentException("Newsletter object with the given newsletter name does not exist.", "newsletterName");
            }

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                // Saves subscriber into the database
                SubscriberInfo subscriber = SaveSubscriber(email);

                if (subscriber != null)
                {
                    // Assigns subscriber to the newsletter
                    if (SubscribeToNewsletter(subscriber, newsletter))
                    {
                        // Saves changes
                        tr.Commit();
                        return true;
                    }
                }
            }

            return false;
        }
    /// <summary>
    /// Processes the step 2 of the wizard
    /// </summary>
    private void ProcessStep2(WizardNavigationEventArgs e)
    {
        FormFieldInfo ffiPrimaryKey = null;
        DataClassInfo dci = DataClassInfoProvider.GetDataClass(ClassName);
        FormInfo fi = null;

        if (dci != null)
        {
            TableManager tm = new TableManager(null);

            using (var tr = new CMSTransactionScope())
            {
                var genDci = dci.Generalized;

                // New document type has custom attributes -> no wizard steps will be omitted
                if (radCustom.Checked)
                {
                    // Actions after next button click
                    bool fromExisting = (Mode == NewClassWizardModeEnum.CustomTable) && radExistingTable.Checked;

                    string tableName = txtTableName.Text.Trim();
                    if (fromExisting)
                    {
                        tableName = drpExistingTables.SelectedValue;
                    }

                    // Validate checkboxes first
                    string tableNameError = new Validator()
                        .NotEmpty(tableName, GetString("DocumentType_New.ErrorEmptyTableName"))
                        .IsIdentifier(tableName, GetString("class.ErrorIdentifier"))
                        .Result;

                    string primaryKeyNameEmpty = new Validator().NotEmpty(txtPKName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyPKName")).Result;

                    bool columnExists = DocumentHelper.ColumnExistsInSystemTable(txtPKName.Text.Trim());

                    // Textboxes are filled correctly
                    if ((tableNameError == "") && (primaryKeyNameEmpty == "") && (!columnExists))
                    {
                        try
                        {
                            if (fromExisting)
                            {
                                // Custom table from existing table - validate the table name
                                if (!tm.TableExists(tableName))
                                {
                                    e.Cancel = true;

                                    // Table with the same name already exists
                                    ShowError(GetString("customtable.newwizard.tablenotexists"));
                                }

                                // Check primary key
                                List<string> primaryKeys = tm.GetPrimaryKeyColumns(tableName);
                                if ((primaryKeys == null) || (primaryKeys.Count != 1))
                                {
                                    e.Cancel = true;

                                    ShowError(GetString("customtable.newwizard.musthaveprimarykey"));
                                }
                            }
                            else if (SystemDevelopmentMode && (Mode == NewClassWizardModeEnum.Class))
                            {
                                // Standard class in development mode
                                tm.CreateTable(tableName, txtPKName.Text.Trim(), !chbIsMNTable.Checked);
                            }
                            else
                            {
                                tm.CreateTable(tableName, txtPKName.Text.Trim());
                            }
                        }
                        catch (Exception ex)
                        {
                            // No movement to the next step
                            e.Cancel = true;

                            // Table with the same name already exists
                            ShowError(ex.Message);
                        }

                        if ((lblErrorStep2.Text == "") && !e.Cancel)
                        {
                            // Change table owner
                            try
                            {
                                string owner = "";

                                // Get site related DB object owner setting when creating new wizard and global otherwise
                                switch (Mode)
                                {
                                    case NewClassWizardModeEnum.DocumentType:
                                    case NewClassWizardModeEnum.Class:
                                    case NewClassWizardModeEnum.CustomTable:
                                        owner = SqlHelperClass.GetDBSchema(CMSContext.CurrentSiteName);
                                        break;
                                }

                                if ((owner != "") && (owner.ToLowerCSafe() != "dbo"))
                                {
                                    tm.ChangeDBObjectOwner(tableName, owner);
                                    tableName = DataHelper.GetSafeOwner(owner) + "." + tableName;
                                }
                            }
                            catch
                            {
                            }

                            if (fromExisting)
                            {
                                // From existing DB table
                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);

                                string formDef = FormHelper.GetXmlFormDefinitionFromXmlSchema(dci.ClassXmlSchema, false);
                                fi = new FormInfo(formDef);
                            }
                            else
                            {
                                // Create empty form definition
                                fi = new FormInfo("<form></form>");
                                ffiPrimaryKey = new FormFieldInfo();

                                // Fill FormInfo object
                                ffiPrimaryKey.Name = txtPKName.Text;
                                ffiPrimaryKey.Caption = txtPKName.Text;
                                ffiPrimaryKey.DataType = FormFieldDataTypeEnum.Integer;
                                ffiPrimaryKey.DefaultValue = "";
                                ffiPrimaryKey.Description = "";
                                ffiPrimaryKey.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                ffiPrimaryKey.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                ffiPrimaryKey.PrimaryKey = true;
                                ffiPrimaryKey.System = false;
                                ffiPrimaryKey.Visible = false;
                                ffiPrimaryKey.Size = 0;
                                ffiPrimaryKey.AllowEmpty = false;

                                // Add field to form definition
                                fi.AddFormField(ffiPrimaryKey);

                                dci.ClassXmlSchema = tm.GetXmlSchema(tableName);
                            }

                            dci.ClassTableName = tableName;
                            dci.ClassFormDefinition = fi.GetXmlDefinition();
                            dci.ClassIsCoupledClass = true;

                            dci.ClassInheritsFromClassID = ValidationHelper.GetInteger(selInherits.Value, 0);

                            // Update class in DB
                            using (CMSActionContext context = new CMSActionContext())
                            {
                                // Disable logging into event log
                                context.LogEvents = false;

                                DataClassInfoProvider.SetDataClass(dci);

                                // Ensure inherited fields
                                if (dci.ClassInheritsFromClassID > 0)
                                {
                                    DataClassInfo parentCi = DataClassInfoProvider.GetDataClass(dci.ClassInheritsFromClassID);
                                    if (parentCi != null)
                                    {
                                        FormHelper.UpdateInheritedClass(parentCi, dci);
                                    }
                                }
                            }

                            if (Mode == NewClassWizardModeEnum.CustomTable)
                            {
                                #region "Custom tables optional columns"

                                // Created by
                                if (chkItemCreatedBy.Checked && !fi.FieldExists("ItemCreatedBy"))
                                {
                                    FormFieldInfo ffi = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffi.Name = "ItemCreatedBy";
                                    ffi.Caption = "Created by";
                                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                                    ffi.DefaultValue = "";
                                    ffi.Description = "";
                                    ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffi.PrimaryKey = false;
                                    ffi.System = true;
                                    ffi.Visible = false;
                                    ffi.Size = 0;
                                    ffi.AllowEmpty = true;

                                    fi.AddFormField(ffi);
                                }

                                // Created when
                                if (chkItemCreatedWhen.Checked && !fi.FieldExists("ItemCreatedWhen"))
                                {
                                    FormFieldInfo ffi = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffi.Name = "ItemCreatedWhen";
                                    ffi.Caption = "Created when";
                                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                                    ffi.DefaultValue = "";
                                    ffi.Description = "";
                                    ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffi.PrimaryKey = false;
                                    ffi.System = true;
                                    ffi.Visible = false;
                                    ffi.Size = 0;
                                    ffi.AllowEmpty = true;

                                    fi.AddFormField(ffi);
                                }

                                // Modified by
                                if (chkItemModifiedBy.Checked && !fi.FieldExists("ItemModifiedBy"))
                                {
                                    FormFieldInfo ffi = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffi.Name = "ItemModifiedBy";
                                    ffi.Caption = "Modified by";
                                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                                    ffi.DefaultValue = "";
                                    ffi.Description = "";
                                    ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffi.PrimaryKey = false;
                                    ffi.System = true;
                                    ffi.Visible = false;
                                    ffi.Size = 0;
                                    ffi.AllowEmpty = true;

                                    fi.AddFormField(ffi);
                                }

                                // Modified when
                                if (chkItemModifiedWhen.Checked && !fi.FieldExists("ItemModifiedWhen"))
                                {
                                    FormFieldInfo ffi = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffi.Name = "ItemModifiedWhen";
                                    ffi.Caption = "Modified when";
                                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                                    ffi.DefaultValue = "";
                                    ffi.Description = "";
                                    ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffi.PrimaryKey = false;
                                    ffi.System = true;
                                    ffi.Visible = false;
                                    ffi.Size = 0;
                                    ffi.AllowEmpty = true;

                                    fi.AddFormField(ffi);
                                }

                                // Item order
                                if (chkItemOrder.Checked && !fi.FieldExists("ItemOrder"))
                                {
                                    FormFieldInfo ffi = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffi.Name = "ItemOrder";
                                    ffi.Caption = "Order";
                                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                                    ffi.DefaultValue = "";
                                    ffi.Description = "";
                                    ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffi.PrimaryKey = false;
                                    ffi.System = true;
                                    ffi.Visible = false;
                                    ffi.Size = 0;
                                    ffi.AllowEmpty = true;

                                    fi.AddFormField(ffi);
                                }

                                #endregion

                                if (chkItemGUID.Checked && !fi.FieldExists("ItemGUID"))
                                {
                                    FormFieldInfo ffiGuid = new FormFieldInfo();

                                    // Fill FormInfo object
                                    ffiGuid.Name = "ItemGUID";
                                    ffiGuid.Caption = "GUID";
                                    ffiGuid.DataType = FormFieldDataTypeEnum.GUID;
                                    ffiGuid.DefaultValue = "";
                                    ffiGuid.Description = "";
                                    ffiGuid.FieldType = FormFieldControlTypeEnum.CustomUserControl;
                                    ffiGuid.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
                                    ffiGuid.PrimaryKey = false;
                                    ffiGuid.System = true;
                                    ffiGuid.Visible = false;
                                    ffiGuid.Size = 0;
                                    ffiGuid.AllowEmpty = false;

                                    fi.AddFormField(ffiGuid);
                                }

                                // Update table structure - columns could be added
                                bool old = TableManager.UpdateSystemFields;

                                TableManager.UpdateSystemFields = true;

                                string schema = fi.GetXmlDefinition();
                                tm.UpdateTableBySchema(tableName, schema);

                                TableManager.UpdateSystemFields = old;

                                // Update xml schema and form definition
                                dci.ClassFormDefinition = schema;
                                dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

                                using (CMSActionContext context = new CMSActionContext())
                                {
                                    // Disable logging into event log
                                    context.LogEvents = false;

                                    DataClassInfoProvider.SetDataClass(dci);
                                }
                            }

                            // Remember that no steps were omitted
                            SomeStepsOmitted = false;

                            // Prepare next step (3)

                            // Disable previous steps' viewstates
                            DisablePreviousStepsViewStates(e.CurrentStepIndex);

                            // Enable next step's viewstate
                            EnableNextStepViewState(e.CurrentStepIndex);

                            // Set field editor class name
                            FieldEditor.ClassName = ClassName;

                            // Fill field editor in the next step
                            FieldEditor.Reload(null);

                            wzdStep3.Title = GetString("general.fields");

                            // Set new step header based on the development mode setting
                            switch (Mode)
                            {
                                case NewClassWizardModeEnum.DocumentType:
                                    ucHeader.Description = GetString("DocumentType_New_Step3.Description");
                                    break;

                                case NewClassWizardModeEnum.Class:
                                    ucHeader.Description = GetString("sysdev.class_new_Step3.Description");
                                    break;

                                case NewClassWizardModeEnum.CustomTable:
                                    ucHeader.Description = GetString("customtable.newwizzard.Step3Description");
                                    break;
                            }
                        }
                    }
                    // Some textboxes are not filled correctly
                    else
                    {
                        // Prepare current step (2)

                        // No movement to the next step
                        e.Cancel = true;

                        // Show errors
                        lblTableNameError.Text = tableNameError;
                        lblPKNameError.Text = primaryKeyNameEmpty;

                        if (columnExists)
                        {
                            lblErrorStep2.Text = GetString("DocumentType_New_Step2.ErrorColumnExists");
                            lblErrorStep2.Visible = true;
                        }

                        wzdStep2.Title = GetString("DocumentType_New_Step2.Title");

                        // Reset the header
                        switch (Mode)
                        {
                            case NewClassWizardModeEnum.DocumentType:
                                ucHeader.Description = GetString("DocumentType_New_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.Class:
                                ucHeader.Description = GetString("sysdev.class_new_Step2.Description");
                                break;

                            case NewClassWizardModeEnum.CustomTable:
                                ucHeader.Description = GetString("customtable.newwizzard.Step2Description");
                                break;
                        }
                    }
                }
                // New document type is only the container -> some wizard steps will be omitted
                else
                {
                    // Actions after next button click

                    dci.ClassIsCoupledClass = false;

                    // Update class in DB
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging into event log
                        context.LogEvents = false;

                        DataClassInfoProvider.SetDataClass(dci);
                    }

                    // Remember that some steps were omitted
                    SomeStepsOmitted = true;
                    IsContainer = true;

                    // Prepare next step (5) - skip steps 3 and 4

                    // Disable previous steps' viewstates
                    DisablePreviousStepsViewStates(3);

                    // Enable next step's viewstate
                    EnableNextStepViewState(3);

                    PrepareStep5();
                    // Go to the step 5 (indexed from 0)
                    wzdNewDocType.ActiveStepIndex = 4;
                }

                // Create new icon if the wizard is used to create new document type
                if (Mode == NewClassWizardModeEnum.DocumentType)
                {
                    string sourceFile = "";
                    string destFile = GetDocumentTypeIconUrl(ClassName, false);
                    string sourceLargeFile = "";
                    string destLargeFile = GetDocumentTypeIconPath(ClassName, "48x48", false);

                    // If class is not coupled class
                    if (SomeStepsOmitted)
                    {
                        sourceFile = GetDocumentTypeIconPath("defaultcontainer", "", true);
                        sourceLargeFile = GetDocumentTypeIconPath("defaultcontainer", "48x48", true);
                    }
                    else
                    {
                        sourceFile = GetDocumentTypeIconPath("default", "", true);
                        sourceLargeFile = GetDocumentTypeIconPath("default", "48x48", true);
                    }

                    if (SettingsKeyProvider.DevelopmentMode)
                    {
                        // Ensure '.gif' image for large icon in development mode
                        sourceLargeFile = sourceLargeFile.Replace(".png", ".gif");
                    }

                    // Ensure same extension
                    if (sourceFile.ToLowerCSafe().EndsWithCSafe(".gif"))
                    {
                        destFile = destFile.Replace(".png", ".gif");
                    }
                    // Ensure same extension
                    if (sourceLargeFile.ToLowerCSafe().EndsWithCSafe(".gif"))
                    {
                        destLargeFile = destLargeFile.Replace(".png", ".gif");
                    }

                    if (!FileHelper.FileExists(destFile))
                    {
                        try
                        {
                            // Create new document type icon via copying default icon
                            File.Copy(Server.MapPath(sourceFile), Server.MapPath(destFile), false);
                        }
                        catch
                        {
                            FieldEditor.ShowError(string.Format(GetString("DocumentType_New_Step2.ErrorCopyIcon"), sourceFile, destFile));
                        }
                    }

                    // Copy large file icon
                    if (!FileHelper.FileExists(destLargeFile))
                    {
                        try
                        {
                            // Create new document type large icon via copying default icon
                            File.Copy(Server.MapPath(sourceLargeFile), Server.MapPath(destLargeFile), false);
                        }
                        catch
                        {
                            FieldEditor.ShowError(string.Format(GetString("DocumentType_New_Step2.ErrorCopyIcon"), sourceLargeFile, destLargeFile));
                        }
                    }
                }

                if (!e.Cancel)
                {
                    tr.Commit();
                }
            }
        }
    }
    /// <summary>
    /// Saves customer data and returns customer ID.
    /// </summary>
    public int Save()
    {
        if (!IsValid())
        {
            return 0;
        }

        // Create customer
        CustomerInfo customer = new CustomerInfo()
        {
            CustomerSiteID = CMSContext.CurrentSiteID,
            CustomerFirstName = txtCustomerFirstName.Text.Trim().Truncate(100),
            CustomerLastName = txtCustomerLastName.Text.Trim().Truncate(100),
            CustomerCompany = txtCustomerCompany.Text.Trim(),
            CustomerOrganizationID = txtOrganizationID.Text.Trim(),
            CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim(),
            CustomerCountryID = drpCountry.CountryID,
            CustomerStateID = drpCountry.StateID,
            CustomerEmail = txtCustomerEmail.Text.Trim().Truncate(100),
            CustomerPhone = txtCustomerPhone.Text.Trim(),
            CustomerFax = txtCustomerFax.Text.Trim(),
            CustomerEnabled = true
        };

        // Save data in transaction
        using (CMSTransactionScope tr = new CMSTransactionScope())
        {
            CustomerInfoProvider.SetCustomerInfo(customer);

            if (chkCreateLogin.Checked)
            {
                // Create user
                UserInfo user = new UserInfo()
                {
                    UserName = txtUserName.Text.Trim(),
                    FullName = customer.CustomerFirstName + " " + customer.CustomerLastName,
                    IsGlobalAdministrator = false
                };

                user.SetValue("UserEnabled", true);

                UserInfoProvider.SetPassword(user, passStrength.Text);
                UserInfoProvider.AddUserToSite(user.UserName, CMSContext.CurrentSiteName);

                customer.CustomerUserID = user.UserID;
                CustomerInfoProvider.SetCustomerInfo(customer);
            }

            tr.Commit();
        }

        return customer.CustomerID;
    }
    private bool FinalizeCheckout()
    {
        using (var scope = new CMSTransactionScope())
        {
            ShoppingCartInfo currentShoppingCart = ShoppingCart;

            // Validate breaking errors (No recovery)
            if (!CheckBreakingErrors(currentShoppingCart))
            {
                return false;
            }
            // Ensure customer is saved
            if (!EnsureCartCustomer(currentShoppingCart))
            {
                return false;
            }
            // Ensure customers address is saved
            if (!EnsureCustomerAddresses(currentShoppingCart))
            {
                return false;
            }
            // Create and save Order
            if (!CreateOrder(currentShoppingCart))
            {
                return false;
            }

            if (!HandleAutoRegistration(currentShoppingCart))
            {
                return false;
            }

            HandleOrderNotification(currentShoppingCart);
            scope.Commit();
        }

        return true;
    }
Exemplo n.º 29
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!BizFormInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.BizForms, ObjectActionEnum.Insert))
        {
            ShowError(GetString("LicenseVersion.BizForm"));
            return;
        }

        DataClassInfo dci        = null;
        BizFormInfo   bizFormObj = null;

        string errorMessage = new Validator().NotEmpty(txtFormDisplayName.Text, rfvFormDisplayName.ErrorMessage).
                              NotEmpty(txtFormName.Text, rfvFormName.ErrorMessage).
                              NotEmpty(txtTableName.Text, rfvTableName.ErrorMessage).
                              IsIdentifier(txtFormName.Text, GetString("bizform_edit.errorformnameinidentifierformat")).
                              IsIdentifier(txtTableName.Text, GetString("BizForm_Edit.ErrorFormTableNameInIdentifierFormat")).Result;

        if (String.IsNullOrEmpty(errorMessage))
        {
            using (var tr = new CMSTransactionScope())
            {
                // Prepare the values
                string formDisplayName = txtFormDisplayName.Text.Trim();

                bizFormObj = new BizFormInfo();
                bizFormObj.FormDisplayName             = formDisplayName;
                bizFormObj.FormName                    = txtFormName.Text.Trim();
                bizFormObj.FormSiteID                  = SiteContext.CurrentSiteID;
                bizFormObj.FormEmailAttachUploadedDocs = true;
                bizFormObj.FormItems                   = 0;
                bizFormObj.FormClearAfterSave          = false;
                bizFormObj.FormLogActivity             = true;

                // Ensure the code name
                bizFormObj.Generalized.EnsureCodeName();

                // Table name is combined from prefix ('BizForm_<sitename>_') and custom table name
                string safeFormName = ValidationHelper.GetIdentifier(bizFormObj.FormName);
                bizFormObj.FormName = safeFormName;

                string className = bizFormNamespace + "." + safeFormName;

                // Generate the table name
                string tableName = txtTableName.Text.Trim();
                if (String.IsNullOrEmpty(tableName) || (tableName == InfoHelper.CODENAME_AUTOMATIC))
                {
                    tableName = safeFormName;
                }
                tableName = FormTablePrefix + tableName;

                TableManager tm = new TableManager(null);

                // TableName wont be longer than 60 letters and will be unique
                if (tableName.Length > 60)
                {
                    int x = 1;

                    while (tm.TableExists(tableName.Substring(0, 59) + x.ToString()))
                    {
                        x++;
                    }

                    tableName = tableName.Substring(0, 59) + x.ToString();
                }

                // If first letter of safeFormName is digit, add "PK" to beginning
                string primaryKey = BizFormInfoProvider.GenerateFormPrimaryKeyName(bizFormObj.FormName);

                try
                {
                    // Create new table in DB
                    tm.CreateTable(tableName, primaryKey);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Table with the same name already exists
                    ShowError(string.Format(GetString("bizform_edit.errortableexists"), tableName));
                    return;
                }

                // Change table owner
                try
                {
                    string owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName);
                    if ((!String.IsNullOrEmpty(owner)) && (owner.ToLowerCSafe() != "dbo"))
                    {
                        tm.ChangeDBObjectOwner(tableName, owner);
                        tableName = owner + "." + tableName;
                    }
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("BIZFORM_NEW", "E", ex);
                }

                // Convert default datetime to string in english format
                string defaultDateTime = DateTime.Now.ToString(CultureHelper.EnglishCulture.DateTimeFormat);

                try
                {
                    // Add FormInserted and FormUpdated columns to the table
                    tm.AddTableColumn(tableName, "FormInserted", "datetime", false, defaultDateTime);
                    tm.AddTableColumn(tableName, "FormUpdated", "datetime", false, defaultDateTime);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Column wasn't added successfully
                    ShowError(errorMessage);

                    return;
                }

                // Create the BizForm class
                dci = BizFormInfoProvider.CreateBizFormDataClass(className, formDisplayName, tableName, primaryKey);

                try
                {
                    // Create new bizform dataclass
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging of tasks
                        context.DisableLogging();

                        // Set default search settings
                        dci.ClassSearchEnabled = true;

                        DataClassInfoProvider.SetDataClassInfo(dci);

                        // Create default search settings
                        dci.ClassSearchSettings           = SearchHelper.GetDefaultSearchSettings(dci);
                        dci.ClassSearchCreationDateColumn = "FormInserted";
                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Class with the same name already exists
                    ShowError(errorMessage);

                    return;
                }

                // Create new bizform
                bizFormObj.FormClassID = dci.ClassID;

                try
                {
                    // Create new bizform
                    BizFormInfoProvider.SetBizFormInfo(bizFormObj);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    ShowError(errorMessage);

                    return;
                }

                tr.Commit();

                if (String.IsNullOrEmpty(errorMessage))
                {
                    // Redirect to Form builder tab
                    string url = UIContextHelper.GetElementUrl("CMS.Form", "Forms.Properties", false, bizFormObj.FormID);
                    url = URLHelper.AddParameterToUrl(url, "tabname", "Forms.FormBuldier");
                    URLHelper.Redirect(url);
                }
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Creates new web part.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Validate the text box fields
        string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result;

        // Check file name
        if (!chkGenerateFiles.Checked && radNewWebPart.Checked)
        {
            if (errorMessage == String.Empty)
            {
                string webpartPath = WebPartInfoProvider.GetWebPartPhysicalPath(FileSystemSelector.Value.ToString());

                if (!radInherited.Checked)
                {
                    errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result;
                }
            }
        }

        if (errorMessage != String.Empty)
        {
            ShowError(HTMLHelper.HTMLEncode(errorMessage));
            return;
        }

        // Run in transaction
        using (var tr = new CMSTransactionScope())
        {
            WebPartInfo wi = new WebPartInfo();

            // Check if new name is unique
            WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text);
            if (webpart != null)
            {
                ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text));
                return;
            }

            string filename = FileSystemSelector.Value.ToString().Trim();
            if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/"))
            {
                filename = filename.Substring("~/cmswebparts/".Length);
            }

            wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim();
            wi.WebPartFileName = filename;
            wi.WebPartName = txtWebPartName.Text.Trim();
            wi.WebPartCategoryID = QueryHelper.GetInteger("parentobjectid", 0);
            wi.WebPartDescription = "";
            wi.WebPartDefaultValues = "<form></form>";
            // Initialize WebPartType - fill it with the default value
            wi.WebPartType = wi.WebPartType;

            // Inherited web part
            if (radInherited.Checked)
            {
                // Check if is selected webpart and isn't category item
                if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0)
                {
                    ShowError(GetString("WebPartNew.InheritedCategory"));
                    return;
                }

                int parentId = ValidationHelper.GetInteger(webpartSelector.Value, 0);
                var parent = WebPartInfoProvider.GetWebPartInfo(parentId);
                if (parent != null)
                {
                    wi.WebPartType = parent.WebPartType;
                    wi.WebPartResourceID = parent.WebPartResourceID;
                    wi.WebPartSkipInsertProperties = parent.WebPartSkipInsertProperties;
                }

                wi.WebPartParentID = parentId;

                // Create empty default values definition
                wi.WebPartProperties = "<defaultvalues></defaultvalues>";
            }
            else
            {
                // Check if filename was added
                if (!FileSystemSelector.IsValid())
                {
                    ShowError(FileSystemSelector.ValidationError);

                    return;
                }
                else
                {
                    wi.WebPartProperties = "<form></form>";
                    wi.WebPartParentID = 0;
                }
            }

            // Save the web part
            WebPartInfoProvider.SetWebPartInfo(wi);

            if (chkGenerateFiles.Checked && radNewWebPart.Checked)
            {
                string physicalFile = WebPartInfoProvider.GetFullPhysicalPath(wi);
                if (!File.Exists(physicalFile))
                {
                    string ascx;
                    string code;
                    string designer;

                    // Write the files
                    try
                    {
                        WebPartInfoProvider.GenerateWebPartCode(wi, null, out ascx, out code, out designer);

                        string folder = Path.GetDirectoryName(physicalFile);

                        // Ensure the folder
                        if (!Directory.Exists(folder))
                        {
                            Directory.CreateDirectory(folder);
                        }

                        File.WriteAllText(physicalFile, ascx);
                        File.WriteAllText(physicalFile + ".cs", code);

                        // Designer file
                        if (!String.IsNullOrEmpty(designer))
                        {
                            File.WriteAllText(physicalFile + ".designer.cs", designer);
                        }

                    }
                    catch (Exception ex)
                    {
                        LogAndShowError("WebParts", "GENERATEFILES", ex, true);
                        return;
                    }
                }
                else
                {
                    ShowError(String.Format(GetString("General.FileExistsPath"), physicalFile));
                    return;
                }
            }

            // Refresh web part tree
            ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframee", ScriptHelper.GetScript(
                "parent.location = '" + UIContextHelper.GetElementUrl("cms.design", "Development.Webparts", false, wi.WebPartID) + "';"));

            PageBreadcrumbs.Items[1].Text = HTMLHelper.HTMLEncode(wi.WebPartDisplayName);
            ShowChangesSaved();
            plcTable.Visible = false;

            tr.Commit();
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!BizFormInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.BizForms, ObjectActionEnum.Insert))
        {
            ShowError(GetString("LicenseVersion.BizForm"));
            return;
        }

        DataClassInfo dci = null;
        BizFormInfo bizFormObj = null;

        string errorMessage = new Validator().NotEmpty(txtFormDisplayName.Text, rfvFormDisplayName.ErrorMessage).
            NotEmpty(txtFormName.Text, rfvFormName.ErrorMessage).
            NotEmpty(txtTableName.Text, rfvTableName.ErrorMessage).
            IsIdentifier(txtFormName.Text, GetString("bizform_edit.errorformnameinidentifierformat")).
            IsIdentifier(txtTableName.Text, GetString("BizForm_Edit.ErrorFormTableNameInIdentifierFormat")).Result;

        if (String.IsNullOrEmpty(errorMessage))
        {
            using (var tr = new CMSTransactionScope())
            {
                // Prepare the values
                string formDisplayName = txtFormDisplayName.Text.Trim();

                bizFormObj = new BizFormInfo();
                bizFormObj.FormDisplayName = formDisplayName;
                bizFormObj.FormName = txtFormName.Text.Trim();
                bizFormObj.FormSiteID = SiteContext.CurrentSiteID;
                bizFormObj.FormEmailAttachUploadedDocs = true;
                bizFormObj.FormItems = 0;
                bizFormObj.FormClearAfterSave = false;
                bizFormObj.FormLogActivity = true;

                // Ensure the code name
                bizFormObj.Generalized.EnsureCodeName();

                // Table name is combined from prefix ('BizForm_<sitename>_') and custom table name
                string safeFormName = ValidationHelper.GetIdentifier(bizFormObj.FormName);
                bizFormObj.FormName = safeFormName;

                string className = bizFormNamespace + "." + safeFormName;

                // Generate the table name
                string tableName = txtTableName.Text.Trim();
                if (String.IsNullOrEmpty(tableName) || (tableName == InfoHelper.CODENAME_AUTOMATIC))
                {
                    tableName = safeFormName;
                }
                tableName = FormTablePrefix + tableName;

                TableManager tm = new TableManager(null);

                // TableName wont be longer than 60 letters and will be unique
                if (tableName.Length > 60)
                {
                    int x = 1;

                    while (tm.TableExists(tableName.Substring(0, 59) + x.ToString()))
                    {
                        x++;
                    }

                    tableName = tableName.Substring(0, 59) + x.ToString();
                }

                // If first letter of safeFormName is digit, add "PK" to beginning
                string primaryKey = BizFormInfoProvider.GenerateFormPrimaryKeyName(bizFormObj.FormName);

                try
                {
                    // Create new table in DB
                    tm.CreateTable(tableName, primaryKey);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Table with the same name already exists
                    ShowError(string.Format(GetString("bizform_edit.errortableexists"), tableName));
                    return;
                }

                // Change table owner
                try
                {
                    string owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName);
                    if ((!String.IsNullOrEmpty(owner)) && (owner.ToLowerCSafe() != "dbo"))
                    {
                        tm.ChangeDBObjectOwner(tableName, owner);
                        tableName = owner + "." + tableName;
                    }
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("BIZFORM_NEW", "E", ex);
                }

                // Convert default datetime to string in english format
                string defaultDateTime = DateTime.Now.ToString(CultureHelper.EnglishCulture.DateTimeFormat);

                try
                {
                    // Add FormInserted and FormUpdated columns to the table
                    tm.AddTableColumn(tableName, "FormInserted", "datetime", false, defaultDateTime);
                    tm.AddTableColumn(tableName, "FormUpdated", "datetime", false, defaultDateTime);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Column wasn't added successfully
                    ShowError(errorMessage);

                    return;
                }

                // Create the BizForm class
                dci = BizFormInfoProvider.CreateBizFormDataClass(className, formDisplayName, tableName, primaryKey);

                try
                {
                    // Create new bizform dataclass
                    using (CMSActionContext context = new CMSActionContext())
                    {
                        // Disable logging of tasks
                        context.DisableLogging();

                        // Set default search settings
                        dci.ClassSearchEnabled = true;

                        DataClassInfoProvider.SetDataClassInfo(dci);

                        // Create default search settings
                        dci.ClassSearchSettings = SearchHelper.GetDefaultSearchSettings(dci);
                        dci.ClassSearchCreationDateColumn = "FormInserted";
                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    // Class with the same name already exists
                    ShowError(errorMessage);

                    return;
                }

                // Create new bizform
                bizFormObj.FormClassID = dci.ClassID;

                try
                {
                    // Create new bizform
                    BizFormInfoProvider.SetBizFormInfo(bizFormObj);
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;

                    ShowError(errorMessage);

                    return;
                }

                tr.Commit();

                if (String.IsNullOrEmpty(errorMessage))
                {
                    // Redirect to Form builder tab
                    string url = UIContextHelper.GetElementUrl("CMS.Form", "Forms.Properties", false, bizFormObj.FormID);
                    url = URLHelper.AddParameterToUrl(url, "tabname", "Forms.FormBuldier");
                    URLHelper.Redirect(url);
                }
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Processes the step 1 of the wizard
    /// </summary>
    private void ProcessStep1(WizardNavigationEventArgs e)
    {
        // Actions after next button click

        // Validate checkboxes first
        string errorMessage = null;

        // Display proper error message based on development mode wizard setting
        switch (Mode)
        {
            case NewClassWizardModeEnum.DocumentType:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("DocumentType_New.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("DocumentType_New.NamespaceNameIdentifier")).Result;
                break;

            case NewClassWizardModeEnum.Class:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("sysdev.class_new.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("sysdev.class_new.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("sysdev.class_new.NamespaceNameIdentifier")).Result;
                break;

            case NewClassWizardModeEnum.CustomTable:
                errorMessage = new Validator().NotEmpty(txtDisplayName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyDisplayName")).
                    NotEmpty(txtCodeName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyCodeName")).
                    NotEmpty(txtNamespaceName.Text.Trim(), GetString("customtable.newwizzard.ErrorEmptyNamespaceName")).
                    IsCodeName(txtCodeName.Text.Trim(), GetString("customtable.newwizzard.CodeNameIdentifier")).
                    IsIdentifier(txtNamespaceName.Text.Trim(), GetString("customtable.newwizzard.NamespaceNameIdentifier")).Result;
                break;
        }

        if (String.IsNullOrEmpty(errorMessage))
        {
            string className = txtNamespaceName.Text.Trim() + "." + txtCodeName.Text.Trim();
            if (DataClassInfoProvider.GetDataClassInfo(className) != null)
            {
                errorMessage = GetString("sysdev.class_edit_gen.codenameunique");
            }
            else
            {
                // Set new class info
                DataClassInfo.ClassDisplayName = txtDisplayName.Text.Trim();
                DataClassInfo.ClassName = className;

                // Set class type according development mode setting
                switch (Mode)
                {
                    case NewClassWizardModeEnum.DocumentType:
                        DataClassInfo.ClassIsDocumentType = true;
                        DataClassInfo.ClassUsePublishFromTo = true;
                        break;

                    case NewClassWizardModeEnum.Class:
                        DataClassInfo.ClassShowAsSystemTable = false;
                        DataClassInfo.ClassShowTemplateSelection = false;
                        DataClassInfo.ClassIsDocumentType = false;
                        DataClassInfo.ClassCreateSKU = false;
                        DataClassInfo.ClassIsProduct = false;
                        DataClassInfo.ClassIsMenuItemType = false;
                        DataClassInfo.ClassUsesVersioning = false;
                        DataClassInfo.ClassUsePublishFromTo = false;
                        DataClassInfo.ClassResourceID = ModuleID;
                        break;

                    case NewClassWizardModeEnum.CustomTable:
                        DataClassInfo.ClassShowAsSystemTable = false;
                        DataClassInfo.ClassShowTemplateSelection = false;
                        DataClassInfo.ClassIsDocumentType = false;
                        DataClassInfo.ClassCreateSKU = false;
                        DataClassInfo.ClassIsProduct = false;
                        DataClassInfo.ClassIsMenuItemType = false;
                        DataClassInfo.ClassUsesVersioning = false;
                        DataClassInfo.ClassUsePublishFromTo = false;
                        // Sets custom table
                        DataClassInfo.ClassIsCustomTable = true;
                        break;
                }

                var errorMsg = String.Empty;

                try
                {
                    using (var tr = new CMSTransactionScope())
                    {
                        // Insert new class into DB
                        DataClassInfoProvider.SetDataClassInfo(DataClassInfo);

                        // Set permissions and queries
                        switch (Mode)
                        {
                            case NewClassWizardModeEnum.DocumentType:
                                // Ensure default permissions
                                PermissionNameInfoProvider.CreateDefaultClassPermissions(DataClassInfo.ClassID);
                                break;

                            case NewClassWizardModeEnum.Class:
                                break;

                            case NewClassWizardModeEnum.CustomTable:
                                // Ensure default custom table permissions
                                PermissionNameInfoProvider.CreateDefaultCustomTablePermissions(DataClassInfo.ClassID);
                                break;
                        }

                        tr.Commit();
                    }
                }
                catch (Exception ex)
                {
                    // No movement to the next step
                    e.Cancel = true;

                    // Class with the same class name already exists
                    pnlMessages1.Visible = true;

                    errorMsg = ex.Message;

                    pnlMessages1.ShowError(errorMsg);

                    EventLogProvider.LogException("NewClassWizard", "CREATE", ex);
                }

                // Prepare next step (2)
                if (errorMsg == "")
                {
                    // Disable previous steps' view states
                    DisablePreviousStepsViewStates(e.CurrentStepIndex);

                    // Enable next step's view state
                    EnableNextStepViewState(e.CurrentStepIndex);

                    // Save ClassName to viewstate to use in the next steps
                    ClassName = DataClassInfo.ClassName;

                    // Prefill textboxes in the next step with default values
                    txtTableName.Text = txtNamespaceName.Text.Trim() + "_" + txtCodeName.Text.Trim();
                    txtPKName.Text = TextHelper.FirstLetterToUpper(txtCodeName.Text.Trim() + "ID");

                    wzdStep2.Title = GetString("DocumentType_New_Step2.Title");

                    // Prepare next step by mode setting
                    switch (Mode)
                    {
                        case NewClassWizardModeEnum.DocumentType:
                            {
                                // Document type
                                lblFullCodeName.ResourceString = "DocumentType_New.FullCodeName";
                                lblPKName.Text = GetString("DocumentType_New.PrimaryKeyName");
                                lblTableName.Text = GetString("DocumentType_New.TableName");
                                radCustom.Text = GetString("DocumentType_New.Custom");

                                // Display container option based on the development mode setting
                                radContainer.Text = GetString("DocumentType_New.Container");
                                radContainer.Visible = true;

                                ucHeader.Description = GetString("DocumentType_New_Step2.Description");

                                // Setup the inheritance selector
                                plcDocTypeOptions.Visible = true;
                                selInherits.WhereCondition = "ClassID <> " + DataClassInfo.ClassID;
                                selInherits.ReloadData();
                            }
                            break;

                        case NewClassWizardModeEnum.Class:
                            {
                                // Standard class
                                lblFullCodeName.ResourceString = "sysdev.class_new.fullcodename";
                                lblPKName.Text = GetString("sysdev.class_new.PrimaryKeyName");
                                lblTableName.Text = GetString("sysdev.class_new.TableName");
                                radCustom.Text = GetString("sysdev.class_new.Custom");
                                lblIsMNTable.Text = GetString("sysdev.class_new.MNTable");

                                radContainer.Visible = false;
                                plcMNClassOptions.Visible = true;

                                ucHeader.Description = GetString("sysdev.class_new_Step2.Description");
                            }
                            break;

                        case NewClassWizardModeEnum.CustomTable:
                            {
                                // Custom table
                                lblFullCodeName.ResourceString = "customtable.newwizzard.FullCodeName";
                                lblPKName.Text = GetString("customtable.newwizzard.PrimaryKeyName");
                                lblTableName.Text = GetString("customtable.newwizzard.TableName");

                                radCustom.Visible = false;
                                radContainer.Visible = false;

                                radNewTable.Text = GetString("customtable.newwizard.newtable");
                                radExistingTable.Text = GetString("customtable.newwizard.existingtable");

                                plcExisting.Visible = true;

                                // Custom tables have always ItemID as primary key
                                txtPKName.Text = "ItemID";

                                // Primary key name can't be edited
                                txtPKName.Enabled = false;

                                // Show custom tables columns options
                                plcCustomTablesOptions.Visible = true;

                                lblItemGUID.Text = GetString("customtable.newwizzard.lblItemGUID");
                                lblItemCreatedBy.Text = GetString("customtable.newwizzard.lblItemCreatedBy");
                                lblItemCreatedWhen.Text = GetString("customtable.newwizzard.lblItemCreatedWhen");
                                lblItemModifiedBy.Text = GetString("customtable.newwizzard.lblItemModifiedBy");
                                lblItemModifiedWhen.Text = GetString("customtable.newwizzard.lblItemModifiedWhen");
                                lblItemOrder.Text = GetString("customtable.newwizzard.lblItemOrder");

                                ucHeader.Description = GetString("customtable.newwizzard.Step2Description");
                            }
                            break;
                    }
                }
            }
        }

        if (!String.IsNullOrEmpty(errorMessage))
        {
            // No movement to the next step
            e.Cancel = true;

            // Textboxes are not filled correctly
            pnlMessages1.Visible = true;
            pnlMessages1.ShowError(errorMessage);
        }
    }
        /// <summary>
        /// Subscribes e-mail address to specific newsletter. 
        /// If no subscriber with the given e-mail is found, the new one is created.
        /// Action fails when:
        /// <list type="bullet">
        /// <item>
        /// <description>Request is performed from banned IP address</description>
        /// </item>
        /// <item>
        /// <description>Email is already subscribed to the newsletter</description>
        /// </item>
        /// <item>
        /// <description>Newsletter with the given name does not exist</description>
        /// </item>
        /// <item>
        /// <description>Current licence does not allow creating new subscribers</description>
        /// </item>
        /// </list>
        /// errorMessage output parameter is filled with localized error description in all these cases.
        /// No exception can be thrown.
        /// </summary>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterName">Name of the newsletter</param>
        /// <param name="errorMessage">Error message used when subscription failed</param>
        /// <returns>Returns true if subscription was successful</returns>
        public virtual bool Subscribe(string email, string newsletterName, out string errorMessage)
        {
            bool result = false;

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                // Saves subscriber into the database
                SubscriberInfo subscriber = SaveSubscriber(email, out errorMessage);
                if ((subscriber != null) && string.IsNullOrEmpty(errorMessage))
                {
                    // Assignes subscriber into the newsletter
                    bool newsletterSubscribed = SaveNewsletter(newsletterName, subscriber, out errorMessage);
                    if (newsletterSubscribed && string.IsNullOrEmpty(errorMessage))
                    {
                        result = true;
                    }
                }

                // Saves changes
                tr.Commit();
            }

            return result;
        }
Exemplo n.º 34
0
    /// <summary>
    /// Creates new web part.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Validate the text box fields
        string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result;

        // Validate and trim file name textbox only if it's visible
        if (radNewWebPart.Checked && radNewFile.Checked)
        {
            if (String.IsNullOrEmpty(errorMessage))
            {
                errorMessage = new Validator().IsFileName(Path.GetFileName(txtCodeFileName.Text), GetString("WebPart_Clone.InvalidFileName")).Result;
            }
        }

        // Check file name
        if (radExistingFile.Checked && radNewWebPart.Checked)
        {
            if (String.IsNullOrEmpty(errorMessage))
            {
                string webpartPath = WebPartInfoProvider.GetWebPartPhysicalPath(FileSystemSelector.Value.ToString());
                errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result;
            }
        }

        if (!String.IsNullOrEmpty(errorMessage))
        {
            ShowError(HTMLHelper.HTMLEncode(errorMessage));
            return;
        }

        // Run in transaction
        using (var tr = new CMSTransactionScope())
        {
            WebPartInfo wi = new WebPartInfo();

            // Check if new name is unique
            WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text);
            if (webpart != null)
            {
                ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text));
                return;
            }

            string filename = String.Empty;

            if (radNewWebPart.Checked)
            {
                if (radExistingFile.Checked)
                {
                    filename = FileSystemSelector.Value.ToString().Trim();

                    if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/"))
                    {
                        filename = filename.Substring("~/cmswebparts/".Length);
                    }
                }
                else
                {
                    filename = txtCodeFileName.Text.Trim();

                    if (!filename.EndsWithCSafe(".ascx"))
                    {
                        filename += ".ascx";
                    }
                }
            }

            wi.WebPartDisplayName   = txtWebPartDisplayName.Text.Trim();
            wi.WebPartFileName      = filename;
            wi.WebPartName          = txtWebPartName.Text.Trim();
            wi.WebPartCategoryID    = QueryHelper.GetInteger("parentobjectid", 0);
            wi.WebPartDescription   = "";
            wi.WebPartDefaultValues = "<form></form>";
            // Initialize WebPartType - fill it with the default value
            wi.WebPartType = wi.WebPartType;

            // Inherited web part
            if (radInherited.Checked)
            {
                // Check if is selected webpart and isn't category item
                if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0)
                {
                    ShowError(GetString("WebPartNew.InheritedCategory"));
                    return;
                }

                int parentId = ValidationHelper.GetInteger(webpartSelector.Value, 0);
                var parent   = WebPartInfoProvider.GetWebPartInfo(parentId);
                if (parent != null)
                {
                    wi.WebPartType                 = parent.WebPartType;
                    wi.WebPartResourceID           = parent.WebPartResourceID;
                    wi.WebPartSkipInsertProperties = parent.WebPartSkipInsertProperties;
                }

                wi.WebPartParentID = parentId;

                // Create empty default values definition
                wi.WebPartProperties = "<defaultvalues></defaultvalues>";
            }
            else
            {
                // Check if filename was added
                if (FileSystemSelector.Visible && !FileSystemSelector.IsValid())
                {
                    ShowError(FileSystemSelector.ValidationError);
                    return;
                }

                wi.WebPartProperties = "<form></form>";
                wi.WebPartParentID   = 0;
            }

            // Save the web part
            WebPartInfoProvider.SetWebPartInfo(wi);

            if (radNewFile.Checked && radNewWebPart.Checked)
            {
                string physicalFile = WebPartInfoProvider.GetFullPhysicalPath(wi);
                if (!File.Exists(physicalFile))
                {
                    string ascx;
                    string code;
                    string designer;

                    // Write the files
                    try
                    {
                        WebPartInfoProvider.GenerateWebPartCode(wi, null, out ascx, out code, out designer);

                        string folder = Path.GetDirectoryName(physicalFile);

                        // Ensure the folder
                        if (!Directory.Exists(folder))
                        {
                            Directory.CreateDirectory(folder);
                        }

                        File.WriteAllText(physicalFile, ascx);
                        File.WriteAllText(physicalFile + ".cs", code);

                        // Designer file
                        if (!String.IsNullOrEmpty(designer))
                        {
                            File.WriteAllText(physicalFile + ".designer.cs", designer);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogAndShowError("WebParts", "GENERATEFILES", ex, true);
                        return;
                    }
                }
                else
                {
                    ShowError(String.Format(GetString("General.FileExistsPath"), physicalFile));
                    return;
                }
            }

            // Refresh web part tree
            ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframee", ScriptHelper.GetScript(
                                                   "parent.location = '" + UIContextHelper.GetElementUrl("cms.design", "Development.Webparts", false, wi.WebPartID) + "';"));

            PageBreadcrumbs.Items[1].Text = HTMLHelper.HTMLEncode(wi.WebPartDisplayName);
            ShowChangesSaved();
            plcTable.Visible = false;

            tr.Commit();
        }
    }
Exemplo n.º 35
0
        /// <summary>
        /// Unsubscribes email from a newsletter of all marketing materials.
        /// </summary>
        /// <param name="email">Subscriber's e-mail address</param>
        /// <param name="newsletterGuid">Newsletter to unsubscribe email from</param>
        /// <param name="issueGuid">Issue unique identifier. When issue guid is present, number of unsubscriptions for this issue is increased</param>
        /// <param name="unsubscribeFromAll">If true, subscriber is unsubscribed from all marketing materials</param>
        /// <returns>Returns true if unsubscription was successful.</returns>
        /// <exception cref="ArgumentException"><paramref name="newsletterGuid"/> or <paramref name="issueGuid"/> is not valid.</exception>
        private bool UnsubscribeInternal(string email, Guid newsletterGuid, Guid?issueGuid, bool unsubscribeFromAll)
        {
            // Gets information about newsletter and issue
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterGuid, SiteId);
            int?           issueId    = null;

            if (newsletter == null)
            {
                throw new ArgumentException("Newsletter with the given newsletter guid does not exist.", "newsletterGuid");
            }

            if (issueGuid.HasValue)
            {
                IssueInfo issue = IssueInfoProvider.GetIssueInfo(issueGuid.Value, SiteId);

                if (issue == null)
                {
                    throw new ArgumentException("Issue with the given issue guid does not exist.", "issue");
                }

                issueId = issue.IssueID;
            }

            // Creates required Services
            var subscriptionService = Service <ISubscriptionService> .Entry();

            var unsubscriptionProvider = Service <IUnsubscriptionProvider> .Entry();

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                try
                {
                    if (unsubscribeFromAll)
                    {
                        // Unsubscribes if not already unsubscribed
                        if (!unsubscriptionProvider.IsUnsubscribedFromAllNewsletters(email, newsletter.NewsletterSiteID))
                        {
                            subscriptionService.UnsubscribeFromAllNewsletters(email, SiteId, issueId);
                            tr.Commit();
                        }

                        return(true);
                    }

                    // Unsubscribes if not already unsubscribed
                    if (!unsubscriptionProvider.IsUnsubscribedFromSingleNewsletter(email, newsletter.NewsletterID, newsletter.NewsletterSiteID))
                    {
                        subscriptionService.UnsubscribeFromSingleNewsletter(email, newsletter.NewsletterID, issueId);
                        tr.Commit();
                    }

                    return(true);
                }
                catch (Exception exception)
                {
                    Service <IEventLogService> .Entry().LogException("Newsletters", "Unsubscribe", exception);
                }

                return(false);
            }

            #endregion
        }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        bool global = (editedSiteId <= 0);
        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(global))
        {
            // Check module permissions
            if (global)
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
            }
            else
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
            }
        }

        // Validate the form
        string errorMessage = ValidateForm();

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string siteWhere = (editedSiteId > 0) ? " AND (CategorySiteID = " + editedSiteId + " OR CategorySiteID IS NULL)" : "";
            DataSet ds = OptionCategoryInfoProvider.GetOptionCategories("CategoryName = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'" + siteWhere, null, 1, null);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                optionCategoryObj = new OptionCategoryInfo(ds.Tables[0].Rows[0]);
            }

            // If category code name value is unique
            if ((optionCategoryObj == null) || (optionCategoryObj.CategoryID == categoryID))
            {
                // If optionCategory doesn't already exist, create new one
                if (optionCategoryObj == null)
                {
                    optionCategoryObj = OptionCategoryInfoProvider.GetOptionCategoryInfo(categoryID);
                    if (optionCategoryObj == null)
                    {
                        optionCategoryObj = new OptionCategoryInfo();
                        optionCategoryObj.CategorySiteID = editedSiteId;
                    }
                }

                // Set category properties
                optionCategoryObj.CategoryID = categoryID;
                optionCategoryObj.CategoryDisplayName = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType = GetOptionCategoryEnum(drpCategorySelectionType.SelectedValue);
                optionCategoryObj.CategoryDefaultOptions = productOptionSelector.GetSelectedSKUOptions();
                optionCategoryObj.CategoryDescription = txtCategoryDecription.Text.Trim();
                optionCategoryObj.CategoryDefaultRecord = txtDefaultRecord.Text.Trim();
                optionCategoryObj.CategoryEnabled = chkCategoryEnabled.Checked;
                optionCategoryObj.CategoryDisplayPrice = chkCategoryDisplayPrice.Checked;
                optionCategoryObj.CategoryTextMaxLength = ValidationHelper.GetInteger(txtTextMaxLength.Text.Trim(),0);

                using (CMSTransactionScope tran = new CMSTransactionScope())
                {
                    // Save changes
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    // Add text option to text category only if it is empty
                    if (((optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextBox) ||
                        (optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextArea)) &&
                        (SKUInfoProvider.GetSKUOptionsCount(categoryID) == 0))
                    {
                        // Create default text product option
                        SKUInfo option = new SKUInfo();
                        option.SKUName = optionCategoryObj.CategoryDisplayName;
                        option.SKUDescription = optionCategoryObj.CategoryDescription;
                        option.SKUSiteID =  optionCategoryObj.CategorySiteID;
                        option.SKUPrice = 0;
                    }

                    tran.Commit();
                }

                // If hidebreadcrumbs (is in modal window)
                if (QueryHelper.GetBoolean("hidebreadcrumbs", false))
                {
                    // Close window and refresh opener
                    ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "CloseAndRefresh", ScriptHelper.GetScript("parent.wopener.Refresh(); parent.window.close();"));
                }
                else
                {
                    // Normal save
                    //URLHelper.Redirect("OptionCategory_Edit_General.aspx?CategoryID=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + this.SiteID);
                    ScriptHelper.RefreshTabHeader(this, "general");

                    lblInfo.Visible = true;
                    lblInfo.Text = GetString("General.ChangesSaved");
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = GetString("optioncategory_new.errorExistingCodeName");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
        }
    }
Exemplo n.º 37
0
    /// <summary>
    /// Clones the object to the DB according to provided settings.
    /// </summary>
    ///
    public CloneResult CloneObject()
    {
        if (InfoToClone == null)
        {
            return(null);
        }

        TransferExcludedTypes();

        // Check code name
        if (plcCodeName.Visible)
        {
            bool checkCodeName = customProperties?.ValidateCodeName ?? true;
            if (checkCodeName && !ValidationHelper.IsCodeName(txtCodeName.Text))
            {
                ShowError(GetString("general.invalidcodename"));

                return(null);
            }
        }

        // Check display name length
        if (plcDisplayName.Visible && (txtDisplayName.Text.Length > mDisplayNameMaxLength))
        {
            ShowError(string.Format(GetString("cloning.displayname.maxlengthexceed"), mDisplayNameMaxLength));

            return(null);
        }

        // Check permissions
        string targetSiteName = SiteContext.CurrentSiteName;

        if (plcCloneUnderSite.Visible && siteElem.Visible && (siteElem.SiteID > 0))
        {
            targetSiteName = SiteInfoProvider.GetSiteName(siteElem.SiteID);
        }

        // Check object permissions (Create & Modify)
        try
        {
            InfoToClone.CheckPermissions(PermissionsEnum.Create, targetSiteName, CurrentUser, true);
            InfoToClone.CheckPermissions(PermissionsEnum.Modify, targetSiteName, CurrentUser, true);
        }
        catch (PermissionCheckException ex)
        {
            RedirectToAccessDenied(ex.ModuleName, ex.PermissionFailed);
        }

        CloneSettings settings = InitializeCloneSettings();

        if (settings == null)
        {
            return(null);
        }

        var      result = new CloneResult();
        BaseInfo clone;

        if (chkUseTransaction.Checked)
        {
            using (var transaction = new CMSTransactionScope())
            {
                clone = InfoToClone.Generalized.InsertAsClone(settings, result);
                transaction.Commit();
            }
        }
        else
        {
            clone = InfoToClone.Generalized.InsertAsClone(settings, result);
        }

        string script = customProperties?.CloseScript;

        if (!string.IsNullOrEmpty(script))
        {
            mCloseScript = script.Replace("{0}", clone.Generalized.ObjectID.ToString());
        }

        return(result);
    }
    /// <summary>
    /// Clones the object to the DB according to provided settings.
    /// </summary>
    public CloneResult CloneObject()
    {
        if (InfoToClone != null)
        {
            // Check code name
            if (plcCodeName.Visible)
            {
                if (!ValidationHelper.IsCodeName(txtCodeName.Text))
                {
                    ShowError(GetString("general.invalidcodename"));
                    return null;
                }
            }

            // Check permissions
            string targetSiteName = CMSContext.CurrentSiteName;
            int targetSiteId = 0;
            if (plcCloneUnderSite.Visible && siteElem.Visible)
            {
                targetSiteId = siteElem.SiteID;
                if (targetSiteId > 0)
                {
                    targetSiteName = SiteInfoProvider.GetSiteName(targetSiteId);
                }
            }

            // Check object permissions (Create & Modify)
            try
            {
                CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Create, InfoToClone, targetSiteName, true);
                CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Modify, InfoToClone, targetSiteName, true);
            }
            catch (PermissionCheckException ex)
            {
                RedirectToAccessDenied(ex.ModuleName, ex.PermissionFailed);
            }

            CloneSettings settings = new CloneSettings();
            settings.KeepFieldsTranslated = chkKeepFieldsTranslated.Checked;
            settings.CloneBase = InfoToClone;
            settings.CodeName = txtCodeName.Text;
            settings.DisplayName = txtDisplayName.Text;
            settings.IncludeBindings = chkBindings.Checked;
            settings.IncludeOtherBindings = chkBindings.Checked;
            settings.IncludeChildren = chkChildren.Checked;
            settings.IncludeMetafiles = chkMetafiles.Checked;
            settings.IncludeSiteBindings = chkSiteBindings.Checked;
            if (plcAssignToCurrentSite.Visible)
            {
                settings.AssignToSiteID = (chkAssignToCurrentSite.Checked ? CMSContext.CurrentSiteID : 0);
            }
            settings.MaxRelativeLevel = ValidationHelper.GetInteger(drpMaxRelativeLevel.SelectedValue, -1);
            if (plcCloneUnderSite.Visible && siteElem.Visible)
            {
                settings.CloneToSiteID = siteElem.SiteID;
            }
            else
            {
                settings.CloneToSiteID = InfoToClone.Generalized.ObjectSiteID;
            }
            if (customProperties != null)
            {
                if (customProperties.IsValid(settings))
                {
                    Hashtable p = customProperties.CustomParameters;
                    if (p != null)
                    {
                        settings.CustomParameters = p;
                    }

                    settings.ExcludedChildTypes.AddRange(excludedChildren);
                    settings.ExcludedBindingTypes.AddRange(excludedBindings);
                    settings.ExcludedOtherBindingTypes.AddRange(excludedOtherBindings);
                }
                else
                {
                    return null;
                }
            }
            if (InfoToClone.Parent != null)
            {
                settings.ParentID = InfoToClone.Parent.Generalized.ObjectID;
            }

            CloneResult result = new CloneResult();
            BaseInfo clone = null;

            if (chkUseTransaction.Checked)
            {
                using (CMSTransactionScope transaction = new CMSTransactionScope())
                {
                    clone = InfoToClone.Generalized.InsertAsClone(settings, result);
                    transaction.Commit();
                }
            }
            else
            {
                clone = InfoToClone.Generalized.InsertAsClone(settings, result);
            }

            if (customProperties != null)
            {
                string script = customProperties.CloseScript;
                if (!string.IsNullOrEmpty(script))
                {
                    mCloseScript = script.Replace("{0}", clone.Generalized.ObjectID.ToString());
                }
            }

            return result;
        }
        return null;
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        bool global = (editedSiteId <= 0);
        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(global))
        {
            // Check module permissions
            if (global)
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
            }
            else
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
            }
        }

        // Check input value from textboxes
        string errorMessage = new Validator().NotEmpty(txtDisplayName.Text, GetString("general.requiresdisplayname"))
            .NotEmpty(txtCategoryName.Text, GetString("general.requirescodename"))
            .IsIdentifier(txtCategoryName.Text, GetString("optioncategory_new.errorNotIdentifier")).Result;

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string siteWhere = (ConfiguredSiteID > 0) ? " AND (CategorySiteID = " + ConfiguredSiteID + " OR CategorySiteID IS NULL)" : "";
            DataSet ds = OptionCategoryInfoProvider.GetOptionCategories("CategoryName = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'" + siteWhere, null, 1, null);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                optionCategoryObj = new OptionCategoryInfo(ds.Tables[0].Rows[0]);
            }

            // If category code name value is unique
            if (optionCategoryObj == null)
            {
                // Create, fill and set OptionCategoryInfo object
                optionCategoryObj = new OptionCategoryInfo();
                optionCategoryObj.CategoryDisplayName = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType = radSelection.Checked ? OptionCategorySelectionTypeEnum.Dropdownlist : OptionCategorySelectionTypeEnum.TextBox;
                optionCategoryObj.CategoryEnabled = true;
                optionCategoryObj.CategoryDefaultRecord = "";
                optionCategoryObj.CategoryDefaultOptions = "";
                optionCategoryObj.CategorySiteID = ConfiguredSiteID;

                // Create category and option under transaction
                using (CMSTransactionScope tr = new CMSTransactionScope())
                {
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    if (radText.Checked)
                    {
                        // Create text product option
                        SKUInfo option = new SKUInfo()
                                             {
                                                 SKUOptionCategoryID = optionCategoryObj.CategoryID,
                                                 SKUProductType = SKUProductTypeEnum.Text,
                                                 SKUSiteID = ConfiguredSiteID,
                                                 SKUName = optionCategoryObj.CategoryDisplayName,
                                                 SKUDepartmentID = 0,
                                                 SKUPrice = 0,
                                                 SKUNeedsShipping = false,
                                                 SKUWeight = 0,
                                                 SKUEnabled = true
                                             };

                        SKUInfoProvider.SetSKUInfo(option);
                    }

                    // Commit a transaction
                    tr.Commit();
                }

                URLHelper.Redirect("OptionCategory_Edit.aspx?categoryId=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + SiteID);
            }
            else
            {
                // Show error message
                ShowError(GetString("optioncategory_new.errorExistingCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(errorMessage);
        }
    }
Exemplo n.º 40
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        string errorMessage = "";

        if ((txtCustomerCompany.Text.Trim() == "") &&
            ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }
        else if (ECommerceSettings.RequireCompanyInfo(CMSContext.CurrentSite.SiteName) && (txtCustomerCompany.Text.Trim() != "" || txtOraganizationID.Text.Trim() != "" || txtTaxRegistrationID.Text.Trim() != ""))
        {
            errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text.Trim(), GetString("customers_edit.errorcompany"))
                           .NotEmpty(txtOraganizationID.Text.Trim(), GetString("customers_edit.errororganizationid"))
                           .NotEmpty(txtTaxRegistrationID.Text.Trim(), GetString("customers_edit.errortaxregid")).Result;
        }
        else if ((txtCustomerEmail.Text.Trim() != "") && !ValidationHelper.IsEmail(txtCustomerEmail.Text))
        {
            errorMessage = GetString("Customers_Edit.errorEmail");
        }

        if (chkHasLogin.Checked)
        {
            if (errorMessage == "")
            {
                errorMessage = new Validator().NotEmpty(txtUserName.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvUserName"))
                               .NotEmpty(passStrength.Text, GetString("Customer_Edit_Login_Edit.rqvPassword1"))
                               .NotEmpty(txtPassword2.Text, GetString("Customer_Edit_Login_Edit.rqvPassword2")).Result;
            }

            if ((errorMessage == "") && (passStrength.Text != txtPassword2.Text))
            {
                errorMessage = GetString("Customer_Edit_Login_Edit.DifferentPasswords");
            }

            // Check policy
            if ((errorMessage == "") && !passStrength.IsValid())
            {
                errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
            }

            // Check if user name is unique
            if (errorMessage == "")
            {
                UserInfo existingUser = UserInfoProvider.GetUserInfo(txtUserName.Text.Trim());
                if (existingUser != null)
                {
                    errorMessage = GetString("Customer_Edit_Login_Edit.UserExist");
                }
            }
        }

        if (errorMessage == "")
        {
            CustomerInfo customerObj = CustomerInfoProvider.GetCustomerInfo(customerid);

            // If customer does not already exist, create new one
            if (customerObj == null)
            {
                customerObj = new CustomerInfo();
                customerObj.CustomerSiteID  = currentSiteId;
                customerObj.CustomerEnabled = true;
            }

            customerObj.CustomerEmail             = txtCustomerEmail.Text.Trim();
            customerObj.CustomerFax               = txtCustomerFax.Text.Trim();
            customerObj.CustomerLastName          = txtCustomerLastName.Text.Trim();
            customerObj.CustomerPhone             = txtCustomerPhone.Text.Trim();
            customerObj.CustomerFirstName         = txtCustomerFirstName.Text.Trim();
            customerObj.CustomerCompany           = txtCustomerCompany.Text.Trim();
            customerObj.CustomerCountryID         = drpCountry.CountryID;
            customerObj.CustomerStateID           = drpCountry.StateID;
            customerObj.CustomerOrganizationID    = txtOraganizationID.Text.Trim();
            customerObj.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();

            // Set customer's preferences
            customerObj.CustomerPreferredCurrencyID       = drpCurrency.CurrencyID;
            customerObj.CustomerPreferredPaymentOptionID  = drpPayment.PaymentID;
            customerObj.CustomerPreferredShippingOptionID = drpShipping.ShippingID;

            if (plcDiscounts.Visible && plcGlobalDiscount.Visible)
            {
                customerObj.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel;
            }

            // Only registered customer can be enabled/diabled
            if (customerObj.CustomerIsRegistered)
            {
                customerObj.CustomerEnabled = chkCustomerEnabled.Checked;
            }

            bool refreshHeader = true;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                // Create user for customer
                if (chkHasLogin.Checked)
                {
                    UserInfo ui = new UserInfo();
                    ui.UserName = txtUserName.Text.Trim();
                    ui.FullName = customerObj.CustomerFirstName + " " + customerObj.CustomerLastName;
                    ui.IsGlobalAdministrator = false;
                    ui.UserEnabled           = true;

                    UserInfoProvider.SetPassword(ui, passStrength.Text);
                    UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                    customerObj.CustomerEnabled = true;
                    customerObj.CustomerUserID  = ui.UserID;

                    refreshHeader = true;
                }

                // Save customer
                CustomerInfoProvider.SetCustomerInfo(customerObj);

                // Enable/disable coresponding registered user
                if (customerObj.CustomerIsRegistered && !chkHasLogin.Checked)
                {
                    UserInfo ui = UserInfoProvider.GetUserInfo(customerObj.CustomerUserID);

                    // If the customer already has the record in the CMS_User table, update email
                    if (ui != null)
                    {
                        ui.Email = customerObj.CustomerEmail;
                        UserInfoProvider.SetUserInfo(ui);
                    }

                    // Save site specific values
                    UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(customerObj.CustomerUserID, CMSContext.CurrentSiteID);
                    if (userSite != null)
                    {
                        userSite.UserPreferredCurrencyID       = drpCurrency.CurrencyID;
                        userSite.UserPreferredPaymentOptionID  = drpPayment.PaymentID;
                        userSite.UserPreferredShippingOptionID = drpShipping.ShippingID;
                        userSite.UserDiscountLevelID           = drpDiscountLevel.DiscountLevel;

                        UserSiteInfoProvider.SetUserSiteInfo(userSite);
                    }
                }

                // Commit transaction
                tr.Commit();
            }

            URLHelper.Redirect("Customer_Edit_General.aspx?customerid=" + Convert.ToString(customerObj.CustomerID) + "&saved=1&hidebreadcrumbs=" + QueryHelper.GetInteger("hidebreadcrumbs", 0) + "&siteId=" + SiteID + (refreshHeader ? "&refreshHeader=1" : ""));
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }
Exemplo n.º 41
0
    /// <summary>
    /// Saves data to DB without validation and permissions check.
    /// </summary>
    private void SaveData()
    {
        // If customer does not already exist, create new one
        if (Customer == null)
        {
            Customer = new CustomerInfo();
            Customer.CustomerSiteID  = currentSiteId;
            Customer.CustomerEnabled = true;
        }

        Customer.CustomerEmail             = txtCustomerEmail.Text.Trim().Truncate(100);
        Customer.CustomerFax               = txtCustomerFax.Text.Trim();
        Customer.CustomerLastName          = txtCustomerLastName.Text.Trim();
        Customer.CustomerPhone             = txtCustomerPhone.Text.Trim();
        Customer.CustomerFirstName         = txtCustomerFirstName.Text.Trim();
        Customer.CustomerCompany           = txtCustomerCompany.Text.Trim();
        Customer.CustomerCountryID         = drpCountry.CountryID;
        Customer.CustomerStateID           = drpCountry.StateID;
        Customer.CustomerOrganizationID    = txtOraganizationID.Text.Trim();
        Customer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();

        // Set customer's preferences
        Customer.CustomerPreferredCurrencyID       = drpCurrency.CurrencyID;
        Customer.CustomerPreferredPaymentOptionID  = drpPayment.PaymentID;
        Customer.CustomerPreferredShippingOptionID = drpShipping.ShippingID;

        if (plcDiscounts.Visible && plcGlobalDiscount.Visible)
        {
            Customer.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel;
        }

        // Only registered customer can be enabled/disabled
        if (Customer.CustomerIsRegistered)
        {
            Customer.CustomerEnabled = chkCustomerEnabled.Checked;
        }

        using (CMSTransactionScope tr = new CMSTransactionScope())
        {
            bool newUserCreated = false;

            // Create user for customer
            if (chkHasLogin.Checked)
            {
                UserInfo ui = new UserInfo();
                ui.UserName = txtUserName.Text.Trim();
                ui.FullName = Customer.CustomerFirstName + " " + Customer.CustomerLastName;
                ui.IsGlobalAdministrator = false;
                ui.UserEnabled           = true;

                UserInfoProvider.SetPassword(ui, passStrength.Text);
                UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName);

                Customer.CustomerEnabled = true;
                Customer.CustomerUserID  = ui.UserID;

                chkCustomerEnabled.Checked = Customer.CustomerEnabled;

                newUserCreated = true;

                // Show fields requiring registered customer
                pnlEdit.Visible             = false;
                pnlStatic.Visible           = true;
                plcDiscounts.Visible        = true;
                plcPreferences.Visible      = true;
                chkHasLogin.Checked         = false;
                plcSiteDiscount.Visible     = true;
                lblUserNameStaticValue.Text = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName));
                if (AllowEditUser)
                {
                    btnEditUser.OnClientClick = "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Membership/Pages/Users/User_Edit_Frameset.aspx") + "?userid=" + Customer.CustomerUserID + "', 'UserEdit', 950, 700); return false;";
                    btnEditUser.Visible       = true;
                }

                // Hide global discount level selector when global levels not allowed
                plcGlobalDiscount.Visible = allowGlobalDiscountLevels;
            }

            // Save customer
            CustomerInfoProvider.SetCustomerInfo(Customer);

            // Enable/disable corresponding registered user
            if (Customer.CustomerIsRegistered && !newUserCreated)
            {
                UserInfo ui = UserInfoProvider.GetUserInfo(Customer.CustomerUserID);

                // If the customer already has the record in the CMS_User table, update email
                if (ui != null)
                {
                    ui.Email = Customer.CustomerEmail;
                    UserInfoProvider.SetUserInfo(ui);
                }

                // Save site specific values
                UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, currentSiteId);
                if (userSite != null)
                {
                    userSite.UserPreferredCurrencyID       = drpCurrency.CurrencyID;
                    userSite.UserPreferredPaymentOptionID  = drpPayment.PaymentID;
                    userSite.UserPreferredShippingOptionID = drpShipping.ShippingID;
                    userSite.UserDiscountLevelID           = drpDiscountLevel.DiscountLevel;

                    UserSiteInfoProvider.SetUserSiteInfo(userSite);
                }
            }

            // Commit transaction
            tr.Commit();

            // Raise OnSaved event
            RaiseOnSaved();
        }
    }
Exemplo n.º 42
0
    /// <summary>
    /// Clones the object to the DB according to provided settings.
    /// </summary>
    public CloneResult CloneObject()
    {
        if (InfoToClone != null)
        {
            TransferExcludedTypes();

            // Check code name
            if (plcCodeName.Visible)
            {
                bool checkCodeName = true;
                if (customProperties != null)
                {
                    checkCodeName = customProperties.ValidateCodeName;
                }

                if (checkCodeName && !ValidationHelper.IsCodeName(txtCodeName.Text))
                {
                    ShowError(GetString("general.invalidcodename"));
                    return(null);
                }
            }

            // Check permissions
            string targetSiteName = SiteContext.CurrentSiteName;
            if (plcCloneUnderSite.Visible && siteElem.Visible)
            {
                int targetSiteId = siteElem.SiteID;
                if (targetSiteId > 0)
                {
                    targetSiteName = SiteInfoProvider.GetSiteName(targetSiteId);
                }
            }

            // Check object permissions (Create & Modify)
            try
            {
                InfoToClone.CheckPermissions(PermissionsEnum.Create, targetSiteName, CurrentUser, true);
                InfoToClone.CheckPermissions(PermissionsEnum.Modify, targetSiteName, CurrentUser, true);
            }
            catch (PermissionCheckException ex)
            {
                RedirectToAccessDenied(ex.ModuleName, ex.PermissionFailed);
            }

            CloneSettings settings = new CloneSettings();
            settings.KeepFieldsTranslated = chkKeepFieldsTranslated.Checked;
            settings.CloneBase            = InfoToClone;
            settings.CodeName             = txtCodeName.Text;
            settings.DisplayName          = txtDisplayName.Text;
            settings.IncludeBindings      = chkBindings.Checked;
            settings.IncludeOtherBindings = chkBindings.Checked;
            settings.IncludeChildren      = chkChildren.Checked;
            settings.IncludeMetafiles     = chkMetafiles.Checked;
            settings.IncludeSiteBindings  = chkSiteBindings.Checked;
            if (plcAssignToCurrentSite.Visible)
            {
                settings.AssignToSiteID = (chkAssignToCurrentSite.Checked ? SiteContext.CurrentSiteID : 0);
            }
            settings.MaxRelativeLevel = ValidationHelper.GetInteger(drpMaxRelativeLevel.SelectedValue, -1);
            if (plcCloneUnderSite.Visible && siteElem.Visible)
            {
                settings.CloneToSiteID = siteElem.SiteID;
            }
            else
            {
                settings.CloneToSiteID = InfoToClone.Generalized.ObjectSiteID;
            }
            if (customProperties != null)
            {
                if (customProperties.IsValid(settings))
                {
                    Hashtable p = customProperties.CustomParameters;
                    if (p != null)
                    {
                        settings.CustomParameters = p;
                    }

                    settings.ExcludedChildTypes.AddRange(excludedChildren);
                    settings.ExcludedBindingTypes.AddRange(excludedBindings);
                    settings.ExcludedOtherBindingTypes.AddRange(excludedOtherBindings);
                }
                else
                {
                    return(null);
                }
            }
            if (InfoToClone.Parent != null)
            {
                settings.ParentID = InfoToClone.Parent.Generalized.ObjectID;
            }

            CloneResult result = new CloneResult();
            BaseInfo    clone  = null;

            if (chkUseTransaction.Checked)
            {
                using (var transaction = new CMSTransactionScope())
                {
                    clone = InfoToClone.Generalized.InsertAsClone(settings, result);
                    transaction.Commit();
                }
            }
            else
            {
                clone = InfoToClone.Generalized.InsertAsClone(settings, result);
            }

            if (customProperties != null)
            {
                string script = customProperties.CloseScript;
                if (!string.IsNullOrEmpty(script))
                {
                    mCloseScript = script.Replace("{0}", clone.Generalized.ObjectID.ToString());
                }
            }

            return(result);
        }
        return(null);
    }
        /// <summary>
        /// Unsubscribes subscriber.
        /// </summary>
        /// <param name="newsletterGuid">Newsletter unique identifier</param>
        /// <param name="subscriberGuid">Subscriber unique identifier</param>
        /// <param name="issueGuid">Issue unique identifier</param>
        /// <param name="unsubscribeFromAll">If true, subscriber is unsubscribed from all marketing materials</param>
        /// <param name="additionalInformation">Additional information (status message etc.)</param>
        /// <returns>Returns true if unsubscription was successful</returns>
        private bool UnsubscribeInternal(Guid newsletterGuid, Guid subscriberGuid, Guid issueGuid, bool unsubscribeFromAll, out string additionalInformation)
        {
            // Creates required Services
            var subscriptionService = Service<ISubscriptionService>.Entry();
            var unSubscriptionProvider = Service<IUnsubscriptionProvider>.Entry();

            // Validates Subscriber and Newsletter GUIDs
            if ((subscriberGuid == Guid.Empty) || (newsletterGuid == Guid.Empty))
            {
                // Either SubscriberGUID or NewsletterGUID was not supplied, don't unsubscribe
                additionalInformation = ResHelper.GetString("TestMvcDemo.News.InvallidUnsubscriptionLink");
                return false;
            }

            // Gets information about subscriber, newsletter and issue
            SubscriberInfo subscriber = SubscriberInfoProvider.GetSubscriberInfo(subscriberGuid, SiteId);
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterGuid, SiteId);
            IssueInfo issue = IssueInfoProvider.GetIssueInfo(issueGuid, SiteId);

            if ((subscriber == null) || (newsletter == null) || (issue == null))
            {
                additionalInformation = ResHelper.GetString("TestMvcDemo.News.InvallidUnsubscriptionLink");
                return false;
            }

            int? issueId = issue.IssueID;

            // Creates new transaction for saving subscriber's information
            using (var tr = new CMSTransactionScope())
            {
                try
                {
                    if (unsubscribeFromAll)
                    {
                        // Unsubscribes if not already unsubscribed
                        if (!unSubscriptionProvider.IsUnsubscribedFromAllNewsletters(subscriber.SubscriberEmail, newsletter.NewsletterSiteID))
                        {
                            subscriptionService.UnsubscribeFromAllNewsletters(subscriber.SubscriberEmail, SiteId, issueId);
                            tr.Commit();
                        }

                        additionalInformation = ResHelper.GetString("TestMvcDemo.News.UnsubscribedAll");
                        return true;
                    }

                    // Unsubscribes if not already unsubscribed
                    if (!unSubscriptionProvider.IsUnsubscribedFromSingleNewsletter(subscriber.SubscriberEmail, newsletter.NewsletterID, newsletter.NewsletterSiteID))
                    {
                        subscriptionService.UnsubscribeFromSingleNewsletter(subscriber.SubscriberEmail, newsletter.NewsletterID, issueId);
                        tr.Commit();
                    }

                    additionalInformation = ResHelper.GetString("TestMvcDemo.News.Unsubscribed");
                    return true;
                }
                catch (Exception exception)
                {
                    Service<IEventLogService>.Entry().LogException("Newsletters", "Unsubscribe", exception);
                    additionalInformation = ResHelper.GetString("newsletter.unsubscribefailed");
                    return false;
                }
            }
        }