Exemplo n.º 1
0
        public static ModelAddState Add(UserGroupInfo model)
        {
            int           num = UserGroup.ExistsUserGroup(model.GroupName, model.TableName);
            ModelAddState result;

            if (num > 0)
            {
                result = (ModelAddState)num;
            }
            else
            {
                string tableName = "dbo." + model.TableName;
                int    num2      = BizBase.dbo.InsertModel <UserGroupInfo>(model);
                if (num2 > 0)
                {
                    try
                    {
                        TableManager.CreateTable(tableName, "AutoID");
                        TableManager.AddTableColumn(tableName, "UserID", "INT", false, "0");
                        UserGroup.AddDefaultField(num2);
                        CacheUtils.Del("JsonLeeCMS_CacheForGetUserGroup");
                        result = ModelAddState.Success;
                        return(result);
                    }
                    catch
                    {
                        result = ModelAddState.CreateTableError;
                        return(result);
                    }
                }
                CacheUtils.Del("JsonLeeCMS_CacheForGetUserGroup");
                result = ModelAddState.Error;
            }
            return(result);
        }
Exemplo n.º 2
0
        public static ModelAddState Add(ProductModelInfo model)
        {
            int           num = ProductModel.ExistsModel(model.ModelName, model.TableName);
            ModelAddState result;

            if (num > 0)
            {
                result = (ModelAddState)num;
            }
            else
            {
                string tableName = "dbo." + model.TableName;
                int    num2      = BizBase.dbo.InsertModel <ProductModelInfo>(model);
                if (num2 > 0)
                {
                    try
                    {
                        TableManager.CreateTable(tableName, "AutoID");
                        TableManager.AddTableColumn(tableName, "ProID", "INT", false, "0");
                        ProductModel.AddDefaultField(num2);
                        CacheUtils.Del("JsonLeeCMS_CacheForPROMODEL");
                        result = ModelAddState.Success;
                        return(result);
                    }
                    catch
                    {
                        result = ModelAddState.CreateTableError;
                        return(result);
                    }
                }
                CacheUtils.Del("JsonLeeCMS_CacheForPROMODEL");
                result = ModelAddState.Error;
            }
            return(result);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Adds two new columns (AttendeeOrderId, AttendeePaymentCompleted) to the table Events_Attendee
 /// </summary>
 public static void AddAttendeeTableColumns()
 {
     const string className = "cms.eventattendee";
     const string tableName = "Events_Attendee";
     var dc = DataClassInfoProvider.GetDataClassInfo(className);
     if (dc != null)
     {
         // Add new table columns        
         var tm = new TableManager("CMSConnectionString"); 
         tm.AddTableColumn(tableName, COLUMN_ATTENDEE_ORDERID, "int", true, null);
         tm.AddTableColumn(tableName, COLUMN_ATTENDEE_PAYMENTCOMPLETED, "bit", true, null);
         
         // Update XML schema
         dc.ClassXmlSchema = tm.GetXmlSchema(tableName);
         DataClassInfoProvider.SetDataClassInfo(dc);
         
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Adds two new columns (AttendeeOrderId, AttendeePaymentCompleted) to the table Events_Attendee
        /// </summary>
        public static void AddAttendeeTableColumns()
        {
            const string className = "cms.eventattendee";
            const string tableName = "Events_Attendee";
            var          dc        = DataClassInfoProvider.GetDataClassInfo(className);

            if (dc != null)
            {
                // Add new table columns
                var tm = new TableManager("CMSConnectionString");
                tm.AddTableColumn(tableName, COLUMN_ATTENDEE_ORDERID, "int", true, null);
                tm.AddTableColumn(tableName, COLUMN_ATTENDEE_PAYMENTCOMPLETED, "bit", true, null);

                // Update XML schema
                dc.ClassXmlSchema = tm.GetXmlSchema(tableName);
                DataClassInfoProvider.SetDataClassInfo(dc);
            }
        }
Exemplo n.º 5
0
        public static FieldAddState Add(ProductFieldInfo field)
        {
            ProductModelInfo dataById = ProductModel.GetDataById(field.ModelID);
            FieldAddState    result;

            if (dataById == null)
            {
                result = FieldAddState.ModelNotExists;
            }
            else
            {
                int value = BizBase.dbo.GetValue <int>(string.Concat(new object[]
                {
                    "SELECT COUNT(*) FROM shop_ProductField WHERE ModelID=",
                    field.ModelID,
                    " AND FieldName='",
                    field.FieldName,
                    "'"
                }));
                if (value > 0)
                {
                    result = FieldAddState.FieldNameExists;
                }
                else
                {
                    if (BizBase.dbo.InsertModel <ProductFieldInfo>(field) > 0)
                    {
                        try
                        {
                            string text = field.DataType;
                            if (string.Compare(text, "nvarchar", true) == 0)
                            {
                                object obj = text;
                                text = string.Concat(new object[]
                                {
                                    obj,
                                    "(",
                                    field.DataLength,
                                    ")"
                                });
                            }
                            TableManager.AddTableColumn(dataById.TableName, field.FieldName, text, true, field.DefaultValue);
                        }
                        catch
                        {
                            result = FieldAddState.CreateColumnError;
                            return(result);
                        }
                    }
                    CacheUtils.Del("JsonLeeCMS_CacheForGetUserGroup");
                    result = FieldAddState.Success;
                }
            }
            return(result);
        }
    /// <summary>
    /// Updates database representation of given form field
    /// </summary>
    /// <param name="oldFieldInfo">Form field prior to the change</param>
    /// <param name="updatedFieldInfo">Form field after the change has been made.</param>
    /// <param name="tm">Table manager allowing the database changes.</param>
    /// <param name="tableName">Name of the table to be changed.</param>
    /// <returns>Possible error message</returns>
    protected string UpdateDatabaseColumn(FormFieldInfo oldFieldInfo, FormFieldInfo updatedFieldInfo, TableManager tm, string tableName)
    {
        if (updatedFieldInfo.External)
        {
            if (!oldFieldInfo.External)
            {
                tm.DropTableColumn(tableName, oldFieldInfo.Name);
            }
        }
        else
        {
            // Validate the default value
            string errorMessage;
            string newDBDefaultValue = GetDefaultValueInDBCulture(updatedFieldInfo, out errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                return(errorMessage);
            }

            // Set column type and size
            string newColumnType = DataTypeManager.GetSqlType(updatedFieldInfo.DataType, updatedFieldInfo.Size, updatedFieldInfo.Precision);
            string oldColumnName = oldFieldInfo.Name;
            string newColumnName = updatedFieldInfo.Name;

            if (oldFieldInfo.External)
            {
                tm.AddTableColumn(tableName, newColumnName, newColumnType, updatedFieldInfo.AllowEmpty, newDBDefaultValue);
            }
            else
            {
                // Change table column
                tm.AlterTableColumn(tableName, oldColumnName, newColumnName, newColumnType, updatedFieldInfo.AllowEmpty, newDBDefaultValue);
            }
        }

        return(null);
    }
    /// <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);
        }
    }
    private string CreateDatabaseColumn(TableManager tm, string tableName, FormFieldInfo updatedFieldInfo)
    {
        updatedFieldInfo.PrimaryKey = IsPrimaryField;

        string errorMessage = null;

        if (IsMainForm && !updatedFieldInfo.IsDummyField && !updatedFieldInfo.IsExtraField)
        {
            // Validate the default value
            string newDBDefaultValue = GetDefaultValueInDBCulture(updatedFieldInfo, out errorMessage, !DevelopmentMode);

            if (String.IsNullOrEmpty(errorMessage))
            {
                switch (mMode)
                {
                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:

                        // Add new column to specified table
                        if (!updatedFieldInfo.External && (tm != null))
                        {
                            // Set column type and size
                            string newColumnType = DataTypeManager.GetSqlType(updatedFieldInfo.DataType, updatedFieldInfo.Size, updatedFieldInfo.Precision);

                            tm.AddTableColumn(tableName, updatedFieldInfo.Name, newColumnType, updatedFieldInfo.AllowEmpty, newDBDefaultValue, !DevelopmentMode);

                            // Recreate the table PK constraint
                            if (IsPrimaryField)
                            {
                                // Existing primary keys
                                var pkFields = FormInfo.GetFields(true, true, true, true);

                                // Include the new field in the collection
                                pkFields.Add(updatedFieldInfo);

                                var primaryKeys = pkFields.Select(pk => String.Format("[{0}]", pk.Name));

                                tm.RecreatePKConstraint(tableName, primaryKeys.ToArray());
                            }
                        }
                        break;

                }
            }
        }

        return errorMessage;
    }
    /// <summary>
    /// Adds form field info to the form to the specified position.
    /// </summary>
    /// <param name="ffi">Form field info which will be added</param>
    /// <param name="category">Category name</param>
    /// <param name="position">Field position in the category</param>
    private string AddField(FormFieldInfo ffi, string category, int position)
    {
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
        {
            RedirectToAccessDenied("cms.form", "EditForm");
        }

        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        if (dci != null)
        {
            // Ensure the transaction
            using (var tr = new CMSLateBoundTransaction())
            {
                string tableName  = dci.ClassTableName;
                string columnType = DataTypeManager.GetSqlType(ffi.DataType, ffi.Size, ffi.Precision);

                TableManager tm = new TableManager(dci.ClassConnectionString);
                tr.BeginTransaction();

                // Add new column
                tm.AddTableColumn(tableName, ffi.Name, columnType, true, null);

                // Add field to form
                mFormInfo.AddFormItem(ffi);
                if (!String.IsNullOrEmpty(category) || position >= 0)
                {
                    mFormInfo.MoveFormFieldToPositionInCategory(ffi.Name, category, position);
                }

                // Update form definition
                dci.ClassFormDefinition = mFormInfo.GetXmlDefinition();

                // Update class schema
                dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

                try
                {
                    // Save the class data
                    DataClassInfoProvider.SetDataClassInfo(dci);
                }
                catch (Exception)
                {
                    return(GetString("FormBuilder.ErrorSavingForm"));
                }

                // Generate default view
                SqlGenerator.GenerateDefaultView(dci, SiteContext.CurrentSiteName);
                QueryInfoProvider.ClearDefaultQueries(dci, true, true);

                // Hide field for alternative forms that require it
                string where = "FormClassID=" + dci.ClassID;
                where        = SqlHelper.AddWhereCondition(where, "FormHideNewParentFields=1");

                var altforms = AlternativeFormInfoProvider.GetAlternativeForms(where, null);
                foreach (AlternativeFormInfo afi in altforms)
                {
                    afi.HideField(ffi);
                    AlternativeFormInfoProvider.SetAlternativeFormInfo(afi);
                }


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

            ClearHashtables();

            // Update inherited classes with new fields
            FormHelper.UpdateInheritedClasses(dci);
        }
        else
        {
            return(GetString("FormBuilder.ErrorSavingForm"));
        }

        return(string.Empty);
    }
    /// <summary>
    /// Adds form field info to the form to the specified position.
    /// </summary>
    /// <param name="ffi">Form field info which will be added</param>
    /// <param name="category">Category name</param>
    /// <param name="position">Field position in the category</param>
    private string AddField(FormFieldInfo ffi, string category, int position)
    {
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
        {
            RedirectToAccessDenied("cms.form", "EditForm");
        }

        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);
        if (dci != null)
        {
            // Ensure the transaction
            using (var tr = new CMSLateBoundTransaction())
            {
                string columnType = DataTypeManager.GetSqlType(ffi.DataType, ffi.Size, ffi.Precision);

                TableManager tm = new TableManager(dci.ClassConnectionString);
                tr.BeginTransaction();

                // Add new column
                tm.AddTableColumn(dci.ClassTableName, ffi.Name, columnType, true, null);

                // Add field to form
                FormInfo.AddFormItem(ffi);
                if (!String.IsNullOrEmpty(category) || position >= 0)
                {
                    FormInfo.MoveFormFieldToPositionInCategory(ffi.Name, category, position);
                }

                // Update form definition
                dci.ClassFormDefinition = FormInfo.GetXmlDefinition();

                // Update class schema
                dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

                try
                {
                    // Save the class data
                    DataClassInfoProvider.SetDataClassInfo(dci);
                }
                catch (Exception)
                {
                    return GetString("FormBuilder.ErrorSavingForm");
                }

                // Generate default view
                SqlGenerator.GenerateDefaultView(dci, SiteContext.CurrentSiteName);
                QueryInfoProvider.ClearDefaultQueries(dci, true, true);

                // Hide field for alternative forms that require it
                HideFieldInAlternativeForms(ffi, dci);

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

            ClearHashtables();

            // Update inherited classes with new fields
            FormHelper.UpdateInheritedClasses(dci);
        }
        else
        {
            return GetString("FormBuilder.ErrorSavingForm");
        }

        return string.Empty;
    }
Exemplo n.º 11
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);
        }
    }
Exemplo n.º 12
0
        private void EnsureCmsUserAzureCustomField()
        {
            var cmsUserDataClass = DataClassInfoProvider.GetDataClassInfo("cms.user");

            if (cmsUserDataClass == null)
            {
                return;
            }

            var formInfo = new FormInfo(cmsUserDataClass.ClassFormDefinition);

            if (formInfo.FieldExists("AzureADUsername"))
            {
                EventLogProvider.LogInformation("AzureADAuthentication", "Skip Create Field", "AzureADUsername");
                return;
            }

            // Create "AzureADUsername" field if it doesn't exist
            EventLogProvider.LogInformation("AzureADAuthentication", "Create Field", "AzureADUsername");

            var azureAdUsernameTextField = new FormFieldInfo
            {
                Name         = "AzureADUsername",
                DataType     = "text",
                Size         = 200,
                Precision    = -1,
                AllowEmpty   = true,
                DefaultValue = string.Empty,
                System       = false,
                FieldType    = FormFieldControlTypeEnum.TextBoxControl,
                Visible      = true,
                Caption      = "Azure AD Username",
                Enabled      = true
            };

            using (var tr = new CMSLateBoundTransaction())
            {
                var tm = new TableManager(cmsUserDataClass.ClassConnectionString);
                tr.BeginTransaction();

                var newFieldHandler = (AbstractAdvancedHandler)null;
                try
                {
                    newFieldHandler =
                        DataDefinitionItemEvents.AddItem.StartEvent(cmsUserDataClass, azureAdUsernameTextField);

                    var sqlType = DataTypeManager.GetSqlType(azureAdUsernameTextField.DataType,
                                                             azureAdUsernameTextField.Size, azureAdUsernameTextField.Precision);
                    tm.AddTableColumn(cmsUserDataClass.ClassTableName, azureAdUsernameTextField.Name, sqlType,
                                      azureAdUsernameTextField.AllowEmpty, azureAdUsernameTextField.DefaultValue);

                    formInfo.AddFormItem(azureAdUsernameTextField);

                    cmsUserDataClass.ClassFormDefinition = formInfo.GetXmlDefinition();
                    cmsUserDataClass.ClassXmlSchema      = tm.GetXmlSchema(cmsUserDataClass.ClassTableName);
                    DataClassInfoProvider.SetDataClassInfo(cmsUserDataClass);
                    FormHelper.UpdateInheritedClasses(cmsUserDataClass);

                    QueryInfoProvider.ClearDefaultQueries(cmsUserDataClass, true, true);
                    newFieldHandler.FinishEvent();

                    tr.Commit();

                    ClearHashtables("cms.user");
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("AzureADAuthentication", "Create Field", ex);
                }
                finally
                {
                    newFieldHandler?.Dispose();
                }
            }
        }
Exemplo n.º 13
0
    /// <summary>
    /// Adds form field info to the form to the specified position.
    /// </summary>
    /// <param name="ffi">Form field info which will be added</param>
    /// <param name="category">Category name</param>
    /// <param name="position">Field position in the category</param>
    private string AddField(FormFieldInfo ffi, string category, int position)
    {
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
        {
            RedirectToAccessDenied("cms.form", "EditForm");
        }

        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        if (dci != null)
        {
            RaiseBeforeDefinitionUpdate();

            // Ensure the transaction
            using (var tr = new CMSLateBoundTransaction())
            {
                // Raise event for field addition
                using (var h = DataDefinitionItemEvents.AddItem.StartEvent(dci, ffi))
                {
                    string columnType = DataTypeManager.GetSqlType(ffi.DataType, ffi.Size, ffi.Precision);

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    tr.BeginTransaction();

                    // Add new column
                    tm.AddTableColumn(dci.ClassTableName, ffi.Name, columnType, true, null);

                    // Add field to form
                    FormInfo.AddFormItem(ffi);
                    if (!String.IsNullOrEmpty(category) || position >= 0)
                    {
                        FormInfo.MoveFormFieldToPositionInCategory(ffi.Name, category, position);
                    }

                    // Update form definition
                    dci.ClassFormDefinition = FormInfo.GetXmlDefinition();

                    // Update class schema
                    dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

                    try
                    {
                        // Save the class data
                        DataClassInfoProvider.SetDataClassInfo(dci);
                    }
                    catch (Exception)
                    {
                        return(GetString("FormBuilder.ErrorSavingForm"));
                    }

                    h.FinishEvent();
                }

                QueryInfoProvider.ClearDefaultQueries(dci, true, true);

                // Hide field for alternative forms that require it
                FormHelper.HideFieldInAlternativeForms(ffi, dci);

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

            ClearHashtables();

            RaiseAfterDefinitionUpdate();

            // Update inherited classes with new fields
            FormHelper.UpdateInheritedClasses(dci);
        }
        else
        {
            return(GetString("FormBuilder.ErrorSavingForm"));
        }

        return(string.Empty);
    }
Exemplo n.º 14
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        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).
                              IsIdentificator(txtFormName.Text, GetString("BizForm_Edit.ErrorFormNameInIdentificatorFormat")).
                              IsIdentificator(txtTableName.Text, GetString("BizForm_Edit.ErrorFormTableNameInIdentificatorFormat")).Result;

        if (String.IsNullOrEmpty(errorMessage))
        {
            string formCodeName = txtFormName.Text.Trim();

            // Form name must be unique
            BizFormInfo testObj = BizFormInfoProvider.GetBizFormInfo(formCodeName, CMSContext.CurrentSiteName);

            // If formName value is unique...
            if (testObj == null)
            {
                string primaryKey      = formCodeName + "ID";
                string formDisplayName = txtFormDisplayName.Text.Trim();
                string className       = bizFormNamespace + "." + formCodeName;
                // Table name is combined from prefix ('BizForm_<sitename>_') and custom table name
                string tableName = FormTablePrefix + txtTableName.Text.Trim();

                if (!BizFormInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.BizForms, VersionActionEnum.Insert))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("LicenseVersion.BizForm");
                }

                if (!lblError.Visible)
                {
                    try
                    {
                        // Create new table in DB
                        TableManager.CreateTable(tableName, primaryKey);
                    }
                    catch (Exception ex)
                    {
                        errorMessage = ex.Message;

                        // Table with the same name already exists
                        lblError.Visible = true;
                        lblError.Text    = string.Format(GetString("bizform_edit.errortableexists"), tableName);
                    }

                    if (String.IsNullOrEmpty(errorMessage))
                    {
                        // Change table owner
                        try
                        {
                            string owner = SqlHelperClass.GetDBSchema(CMSContext.CurrentSiteName);
                            if ((!String.IsNullOrEmpty(owner)) && (owner.ToLower() != "dbo"))
                            {
                                TableManager.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
                            TableManager.AddTableColumn(tableName, "FormInserted", "datetime", false, defaultDateTime);
                            TableManager.AddTableColumn(tableName, "FormUpdated", "datetime", false, defaultDateTime);
                        }
                        catch (Exception ex)
                        {
                            errorMessage = ex.Message;

                            // Column wasnt added successfuly
                            lblError.Visible = true;
                            lblError.Text    = errorMessage;

                            // Delete created table
                            TableManager.DropTable(tableName);
                        }
                    }

                    if (String.IsNullOrEmpty(errorMessage))
                    {
                        dci = BizFormInfoProvider.CreateBizFormDataClass(className, formDisplayName, tableName, primaryKey);

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

                                DataClassInfoProvider.SetDataClass(dci);
                            }
                        }
                        catch (Exception ex)
                        {
                            errorMessage = ex.Message;

                            // Class with the same name already exists
                            lblError.Visible = true;
                            lblError.Text    = errorMessage;

                            // Delete created table
                            TableManager.DropTable(tableName);
                        }
                    }

                    if (String.IsNullOrEmpty(errorMessage))
                    {
                        // Create new bizform
                        bizFormObj = new BizFormInfo();
                        bizFormObj.FormDisplayName             = formDisplayName;
                        bizFormObj.FormName                    = formCodeName;
                        bizFormObj.FormClassID                 = dci.ClassID;
                        bizFormObj.FormSiteID                  = CMSContext.CurrentSiteID;
                        bizFormObj.FormEmailAttachUploadedDocs = true;
                        bizFormObj.FormItems                   = 0;
                        bizFormObj.FormClearAfterSave          = false;
                        bizFormObj.FormLogActivity             = true;

                        try
                        {
                            // Create new bizform
                            BizFormInfoProvider.SetBizFormInfo(bizFormObj);

                            // Generate basic queries
                            SqlGenerator.GenerateQuery(className, "selectall", SqlOperationTypeEnum.SelectAll, false);
                            SqlGenerator.GenerateQuery(className, "delete", SqlOperationTypeEnum.DeleteQuery, false);
                            SqlGenerator.GenerateQuery(className, "insert", SqlOperationTypeEnum.InsertQuery, true);
                            SqlGenerator.GenerateQuery(className, "update", SqlOperationTypeEnum.UpdateQuery, false);
                            SqlGenerator.GenerateQuery(className, "select", SqlOperationTypeEnum.SelectQuery, false);
                        }
                        catch (Exception ex)
                        {
                            errorMessage = ex.Message;

                            lblError.Visible = true;
                            lblError.Text    = errorMessage;

                            // Delete created class (includes deleting its table)
                            if (dci != null)
                            {
                                using (CMSActionContext context = new CMSActionContext())
                                {
                                    // Disable logging of tasks
                                    context.DisableLogging();

                                    DataClassInfoProvider.DeleteDataClass(dci);
                                }
                            }
                        }

                        if (String.IsNullOrEmpty(errorMessage))
                        {
                            // Redirect to edit dialog
                            URLHelper.Redirect(string.Format("BizForm_Frameset.aspx?formId={0}&newform=1", bizFormObj.FormID));
                        }
                    }
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = GetString("BizForm_Edit.FormNameExists");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }