/// <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>
    /// 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>
    /// 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();
                }
            }
        }
    }
Esempio n. 4
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();
        }
    }
    /// <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>
    /// 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;
            wi.WebPartIconClass = PortalHelper.DefaultWebPartIconClass;

            // 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.WebPartIconClass            = parent.WebPartIconClass;
                }

                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))
                {
                    // Write the files
                    try
                    {
                        var generator = new WebPartCodeGenerator(SystemContext.ApplicationPath);
                        var result    = generator.GenerateWebPartCode(wi);

                        string folder = Path.GetDirectoryName(physicalFile);

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

                        File.WriteAllText(physicalFile, result.Markup);
                        File.WriteAllText(physicalFile + ".cs", result.Code);

                        // Designer file
                        if (!String.IsNullOrEmpty(result.Designer))
                        {
                            File.WriteAllText(physicalFile + ".designer.cs", result.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)
    {
        // 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);
        }
    }
    /// <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>
    /// 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.CategoryFormControlName = null;
                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();
                }

                // Reload defautl option selector
                //ReloadDefaultOptionSelector();

                // 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.CloseDialog();"));
                }
                else
                {
                    // Normal save
                    //URLHelper.Redirect("OptionCategory_Edit_General.aspx?CategoryID=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + this.SiteID);
                    ScriptHelper.RefreshTabHeader(this, "general");

                    // Show message
                    ShowChangesSaved();
                }
            }
            else
            {
                // Show error message
                ShowError(GetString("optioncategory_new.errorExistingCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(errorMessage);
        }
    }
    /// <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;
        }
    }
Esempio n. 11
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;
        }
    }
    /// <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;
    }
Esempio n. 13
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>
        /// 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;
        }
        /// <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>
    /// 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);
        }
    }
    /// <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>
    /// 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();
        }
    }
    /// <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>
        /// 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
        }
Esempio n. 21
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;
        }
    }
        /// <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 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;
        }
    }
Esempio 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);
                }
            }
        }
    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;
    }
    /// <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);
    }
    /// <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);
        }
    }
Esempio n. 28
0
    /// <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 = SettingsKeyInfoProvider.GetBoolValue(SiteContext.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 (var 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)
                {
                    // Set if we need target tag (Translations.com workaround)
                    settings.GenerateTargetTag = ti.TranslationServiceGenerateTargetTag;

                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                        else
                        {
                            submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID, "Page submission " + DateTime.Now);
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            const string columns            = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";
                            string       submissionFileName = "";
                            string       submissionName     = "";
                            int          charCount          = 0;
                            int          wordCount          = 0;
                            int          docCount           = 0;

                            // Prepare the where condition
                            var where = new WhereCondition().WhereIn("NodeID", nodeIds);

                            // 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.WhereIn("DocumentCulture", new[] { settings.SourceLanguage, settings.TargetLanguage });

                            DataSet ds = tree.SelectNodes(SiteContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where.ToString(true), "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;
                                            }
                                        }

                                        // Get document in source language
                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);
                                        if (node == null)
                                        {
                                            // Document doesn't exist in source culture, skip it
                                            continue;
                                        }

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

                                        // 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)
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false, !settings.TranslateAttachments);
                                                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 = docCount;
                                        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(LocalizationHelper.GetString("ContentRequest.TranslationFailed") + " \"" + err + "\"");
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                            else
                            {
                                TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                AddError(ResHelper.GetString("TranslateDocument.NoSourceDocuments", 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 (IsDialog)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); wopener.RefreshTree(null, null);";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Overwrite refreshId variable if sub-levels are visible
                    if (ValidationHelper.GetBoolean(parameter, false) && Parameters.ContainsKey("refreshnodeid"))
                    {
                        refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                    }

                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, 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");
            }
        }

        // 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;
        }
    }
Esempio n. 30
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;
        }
    }
    /// <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 = 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("parentid", 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     = null;
                    string code     = null;
                    string designer = null;

                    // Write the files
                    try
                    {
                        CodeTemplateGenerator.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), "reloadframe", ScriptHelper.GetScript(
                                                   "parent.frames['webparttree'].location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Tree.aspx") + "?webpartid=" + wi.WebPartID + "');" +
                                                   "location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Frameset.aspx") + "?webpartid=" + wi.WebPartID + "')"
                                                   ));

            pageTitleTabs[1, 0]             = HTMLHelper.HTMLEncode(wi.WebPartDisplayName);
            CurrentMaster.Title.Breadcrumbs = pageTitleTabs;

            ShowChangesSaved();
            plcTable.Visible = false;

            tr.Commit();
        }
    }