/// <summary> /// Saves form definition. Updates database column if both original and changed info is passed and the change requires database update. /// </summary> /// <param name="oldFieldInfo">Form field info prior to the change</param> /// <param name="updatedFieldInfo">Form field info after the change has been made.</param> /// <returns>Error message if an error occurred</returns> protected string SaveFormDefinition(FormFieldInfo oldFieldInfo = null, FormFieldInfo updatedFieldInfo = null) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm")) { if (RequestHelper.IsCallback()) { return(GetString("formbuilder.missingeditpermission")); } RedirectToAccessDenied("cms.form", "EditForm"); } DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if ((FormInfo != null) && (dci != null)) { RaiseBeforeDefinitionUpdate(); // Raise event for field change using (var h = DataDefinitionItemEvents.ChangeItem.StartEvent(dci, oldFieldInfo, updatedFieldInfo)) { // Update database column of the changed field if (IsDatabaseChangeRequired(oldFieldInfo, updatedFieldInfo)) { // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { TableManager tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); UpdateDatabaseColumn(dci, oldFieldInfo, updatedFieldInfo, tm, dci.ClassTableName); // Commit the transaction tr.Commit(); } } // Update form definition dci.ClassFormDefinition = FormInfo.GetXmlDefinition(); // Save the class data DataClassInfoProvider.SetDataClassInfo(dci); h.FinishEvent(); } ClearHashtables(); RaiseAfterDefinitionUpdate(); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); return(string.Empty); } return(GetString("FormBuilder.ErrorSavingForm")); }
/// <summary> /// Delete attribute button clicked. /// </summary> protected void btnDeleteItem_Click(Object sender, EventArgs e) { DataClassInfo dci = null; bool updateInherited = false; // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { if (Mode == FieldEditorModeEnum.BizFormDefinition) { // Check 'EditForm' permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToAccessDenied("cms.form", "EditForm"); } } // Raise on before definition update event if (OnBeforeDefinitionUpdate != null) { OnBeforeDefinitionUpdate(this, EventArgs.Empty); } string errorMessage = null; string newSelectedValue = null; string deletedItemPreffix = null; // Clear settings controlSettings.Settings = new Hashtable(); controlSettings.BasicForm.Mode = FormModeEnum.Insert; TableManager tm = null; switch (mMode) { // Do nothing for WebPart case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Get the DataClass dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci == null) { ShowError(GetString("FieldEditor.ClassNotFound")); return; } tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); } break; } // Load current xml form definition LoadFormDefinition(); if (!String.IsNullOrEmpty(SelectedItemName) && !IsNewItemEdited) { switch (SelectedItemType) { case FieldEditorSelectedItemEnum.Field: { FormFieldInfo ffiSelected = FormInfo.GetFormField(SelectedItemName); deletedItemPreffix = fieldPreffix; if (ffiSelected != null) { // Do not allow deleting of the primary key except for external fields if (ffiSelected.PrimaryKey && !ffiSelected.External) { if (!DevelopmentMode) { ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK")); return; } // Check if at least one primary key stays if (FormInfo.GetFields(true, true, false, true).Count() < 2) { ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK")); return; } } // Check if at least two fields stay in document type definition if ((Mode == FieldEditorModeEnum.ClassFormDefinition) && (FormInfo.GetFields(true, true, true, false, false).Count() < 3) && !ffiSelected.IsDummyField) { ShowError(GetString("TemplateDesigner.ErrorCannotDeleteAllCustomFields")); return; } // Do not allow deleting of the system field if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode) { ShowError(GetString("TemplateDesigner.ErrorCannotDeleteSystemField")); return; } // Remove specific field from xml form definition FormInfo.RemoveFormField(SelectedItemName); // Get updated definition FormDefinition = FormInfo.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: errorMessage = UpdateWebPartProperties(); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // If document type is edited AND field that should be removed is FILE if (IsDocumentType && (mMode == FieldEditorModeEnum.ClassFormDefinition) && !String.IsNullOrEmpty(ClassName) && (ffiSelected.DataType == FieldDataType.File)) { DocumentHelper.DeleteDocumentAttachments(ClassName, ffiSelected.Name, null); } // If bizform is edited AND field that should be removed is FILE if ((mMode == FieldEditorModeEnum.BizFormDefinition) && !String.IsNullOrEmpty(ClassName) && (ffiSelected.FieldType == FormFieldControlTypeEnum.UploadControl)) { BizFormInfoProvider.DeleteBizFormFiles(ClassName, ffiSelected.Name, SiteContext.CurrentSiteID); } // Update xml definition if (dci != null) { dci.ClassFormDefinition = FormDefinition; if (!ffiSelected.IsDummyField) { try { if (!ffiSelected.External) { // Remove corresponding column from table tm.DropTableColumn(dci.ClassTableName, SelectedItemName); // Update xml schema dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName); } } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); errorMessage = ex.Message; } } // Deleted field is used as ClassNodeNameSource -> remove node name source if (dci.ClassNodeNameSource == SelectedItemName) { dci.ClassNodeNameSource = String.Empty; } // Update changes in database try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } // Clean search settings dci.ClassSearchSettings = SearchHelper.CleanSearchSettings(dci); // Save the data class DataClassInfoProvider.SetDataClassInfo(dci); updateInherited = true; // Update alternative forms of form class RemoveFieldFromAlternativeForms(dci); } } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); errorMessage = ex.Message; } // Refresh views and queries only if changes to DB were made if (!ffiSelected.External) { // Generate default view SqlGenerator.GenerateDefaultView(dci, mMode == FieldEditorModeEnum.BizFormDefinition ? SiteContext.CurrentSiteName : null); QueryInfoProvider.ClearDefaultQueries(dci, true, true); // Updates custom views if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition)) { errorMessage = RefreshViews(tm, dci); } } } // Clear hashtables and search settings ClearHashtables(); } break; } } } break; case FieldEditorSelectedItemEnum.Category: deletedItemPreffix = categPreffix; // Remove specific category from xml form definition FormInfo.RemoveFormCategory(SelectedItemName); // Get updated form definition FormDefinition = FormInfo.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: errorMessage = UpdateWebPartProperties(); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Standard classes { // Update xml definition if (dci != null) { dci.ClassFormDefinition = FormDefinition; // Update changes in database try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } // Save the data class DataClassInfoProvider.SetDataClassInfo(dci); updateInherited = true; RemoveFieldFromAlternativeForms(dci); } } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); errorMessage = ex.Message; } } } break; } break; } if (!String.IsNullOrEmpty(errorMessage)) { ShowError("[ FieldEditor.btnDeleteItem_Click() ]: " + errorMessage); } } else { // "delete" new item from the list IsNewItemEdited = false; } // Raise on after definition update event if (OnAfterDefinitionUpdate != null) { OnAfterDefinitionUpdate(this, EventArgs.Empty); } // Raise on after item delete if (AfterItemDeleted != null) { AfterItemDeleted(this, new FieldEditorEventArgs(SelectedItemName, SelectedItemType, lstAttributes.SelectedIndex)); } // Commit the transaction tr.Commit(); // Set new selected value ListItem deletedItem = lstAttributes.Items.FindByValue(deletedItemPreffix + SelectedItemName); int deletedItemIndex = lstAttributes.Items.IndexOf(deletedItem); if (deletedItemIndex > 0) { var item = lstAttributes.Items[deletedItemIndex - 1]; if (item != null) { newSelectedValue = item.Value; } } // Reload data Reload(newSelectedValue); } // Update inherited classes with new fields if necessary if (updateInherited) { FormHelper.UpdateInheritedClasses(dci); } }
/// <summary> /// Save selected field. /// </summary> private bool SaveSelectedField() { DataClassInfo dci = null; bool updateInherited = false; // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { // FormFieldInfo structure with data from updated form FormFieldInfo ffiUpdated = null; // FormCategoryInfo structure with data from updated form FormCategoryInfo fciUpdated = null; // For some types of forms initialize table manager string tableName = null; TableManager tm = null; if (IsMainForm) { switch (mMode) { // Do nothing for WebPart case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Fill ClassInfo structure with data from database dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci != null) { // Set table name tableName = dci.ClassTableName; tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); } else { ShowError(GetString("fieldeditor.notablename")); return false; } } break; } } // Load current XML form definition if (!LoadFormDefinition()) { // Form definition was not loaded return false; } string error = null; switch (SelectedItemType) { case FieldEditorSelectedItemEnum.Field: // Fill FormFieldInfo structure with original data ffi = FormInfo.GetFormField(SelectedItemName); // Fill FormFieldInfo structure with updated form data ffiUpdated = FillFormFieldInfoStructure(ffi); try { error = UpdateFormField(tm, tableName, ffiUpdated); } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); // User friendly message for not null setting of column if (!IsNewItemEdited && ffi.AllowEmpty && !ffiUpdated.AllowEmpty) { ShowError(GetString("FieldEditor.ColumnNotAcceptNull"), ex.Message); } else { ShowError(GetString("general.saveerror"), ex.Message); } return false; } break; case FieldEditorSelectedItemEnum.Category: // Fill FormCategoryInfo structure with original data fci = FormInfo.GetFormCategory(SelectedItemName); // Initialize new FormCategoryInfo structure fciUpdated = new FormCategoryInfo(); error = UpdateFormCategory(fciUpdated); break; } if (!String.IsNullOrEmpty(error)) { ShowError(error); return false; } // Make changes in database if (SelectedItemType != 0) { // Get updated definition FormDefinition = FormInfo.GetXmlDefinition(); if (IsMainForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: error = UpdateWebPartProperties(); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: error = UpdateDependencies(dci, tm, ffiUpdated, out updateInherited); break; } } if (!String.IsNullOrEmpty(error)) { ShowError("[FieldEditor.SaveSelectedField()]: " + error); return false; } } // All done and new item, fire OnFieldCreated event RaiseOnFieldCreated(ffiUpdated); // Reload field/category switch (SelectedItemType) { case FieldEditorSelectedItemEnum.Category: Reload(categPreffix + fciUpdated.CategoryName); break; case FieldEditorSelectedItemEnum.Field: Reload(fieldPreffix + ffiUpdated.Name); break; } // Commit the transaction tr.Commit(); } // Update inherited classes with new fields if (updateInherited) { FormHelper.UpdateInheritedClasses(dci); } return true; }
/// <summary> /// Saves data of edited user from TextBoxes into DB. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { UserPrivilegeLevelEnum privilegeLevel = (UserPrivilegeLevelEnum)drpPrivilege.Value.ToInteger(0); // Check "modify" permission if (!CurrentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } string result = ValidateGlobalAndDeskAdmin(userId); var isExternal = chkIsExternal.Checked; // Find whether user name is valid (external users are not checked as their user names can contain various special characters) if (result == String.Empty) { if (!isExternal && !ucUserName.IsValid()) { result = ucUserName.ValidationError; } } String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); // Store the old display name var oldDisplayName = ui.Generalized.ObjectDisplayName; if ((result == String.Empty) && (ui != null)) { // If site prefixed allowed - ad site prefix if ((SiteID != 0) && UserInfoProvider.UserNameSitePrefixEnabled(SiteContext.CurrentSiteName)) { if (!UserInfoProvider.IsSitePrefixedUser(userName)) { userName = UserInfoProvider.EnsureSitePrefixUserName(userName, SiteContext.CurrentSite); } } // Validation for site prefixed users if (!UserInfoProvider.IsUserNamePrefixUnique(userName, ui.UserID)) { ShowError(GetString("Administration-User_New.siteprefixeduserexists")); return; } // Ensure same password password = ui.GetValue("UserPassword").ToString(); // Test for unique username UserInfo uiTest = UserInfoProvider.GetUserInfo(userName); if ((uiTest == null) || (uiTest.UserID == userId)) { if (ui == null) { ui = new UserInfo(); } bool globAdmin = ui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin); bool editor = ui.SiteIndependentPrivilegeLevel == UserPrivilegeLevelEnum.Editor; // Email format validation if (!txtEmail.IsValid()) { ShowError(GetString("Administration-User_New.WrongEmailFormat")); return; } bool oldGlobal = ui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin); bool oldEditor = ui.SiteIndependentPrivilegeLevel == UserPrivilegeLevelEnum.Editor; // Define domain variable string domains = null; // Get all user sites var userSites = UserInfoProvider.GetUserSites(userId).Column("SiteDomainName"); if (userSites.Count > 0) { foreach (var userSite in userSites) { domains += ValidationHelper.GetString(userSite["SiteDomainName"], string.Empty) + ";"; } // Remove ";" at the end if (domains != null) { domains = domains.Remove(domains.Length - 1); } } else { DataSet siteDs = SiteInfoProvider.GetSites().Columns("SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(siteDs)) { // Create list of available site domains domains = TextHelper.Join(";", DataHelper.GetStringValues(siteDs.Tables[0], "SiteDomainName")); } } // Check limitations for Global administrator if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && ((privilegeLevel == UserPrivilegeLevelEnum.GlobalAdmin) || (privilegeLevel == UserPrivilegeLevelEnum.Admin)) && !oldGlobal) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Administrators, ObjectActionEnum.Insert, globAdmin)) { ShowError(GetString("License.MaxItemsReachedGlobal")); return; } } // Check limitations for editors if ((privilegeLevel == UserPrivilegeLevelEnum.Editor) && !oldEditor && userSites.Count > 0) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, ObjectActionEnum.Insert, editor)) { ShowError(GetString("License.MaxItemsReachedEditor")); return; } } // Check whether email is unique if it is required string email = txtEmail.Text.Trim(); if (!UserInfoProvider.IsEmailUnique(email, ui)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set properties ui.Email = email; ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFullName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = txtMiddleName.Text.Trim(); ui.UserName = userName; UserInfoProvider.SetEnabled(ui, CheckBoxEnabled.Checked); ui.UserIsHidden = chkIsHidden.Checked; ui.IsExternal = isExternal; ui.UserIsDomain = chkIsDomain.Checked; ui.SetValue("UserPassword", password); ui.UserID = userId; ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim(); ui.UserMFRequired = chkIsMFRequired.Checked; var isCurrentUserGlobalAdmin = CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin); // Global admin can set anything if (isCurrentUserGlobalAdmin // Other users can set only editor and non privileges || ((privilegeLevel != UserPrivilegeLevelEnum.Admin) && (privilegeLevel != UserPrivilegeLevelEnum.GlobalAdmin)) // Admin can manage his own privilege || ((privilegeLevel == UserPrivilegeLevelEnum.Admin) && (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && (CurrentUser.UserID == ui.UserID)))) { ui.SiteIndependentPrivilegeLevel = privilegeLevel; } LoadUserLogon(ui); // Set values of cultures. string culture = ValidationHelper.GetString(cultureSelector.Value, ""); ui.PreferredCultureCode = culture; if (lstUICulture.SelectedValue == "0") { ui.PreferredUICultureCode = ""; } else { // Set preferred UI culture CultureInfo ci = CultureInfoProvider.GetCultureInfo(ValidationHelper.GetInteger(lstUICulture.SelectedValue, 0)); ui.PreferredUICultureCode = ci.CultureCode; } // Refresh page breadcrumbs if display name changed if (ui.Generalized.ObjectDisplayName != oldDisplayName) { ScriptHelper.RefreshTabHeader(Page, ui.FullName); } using (CMSActionContext context = new CMSActionContext()) { // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that an update search task will be created but NOT executed when updating the user context.EnableSmartSearchIndexer = false; } try { using (var transaction = new CMSLateBoundTransaction()) { // Update the user UserInfoProvider.SetUserInfo(ui); if (isCurrentUserGlobalAdmin) { UserMacroIdentityHelper.SetMacroIdentity(ui, drpMacroIdentity.Value.ToInteger(0)); } transaction.Commit(); } } catch (Exception ex) { EventLogProvider.LogException("Users", "SAVE", ex); ShowError(GetString("general.errorsaving")); return; } // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that current user is not logged out if he changes his user name if (AuthenticationMode.IsFormsAuthentication()) { FormsAuthentication.SetAuthCookie(ui.UserName, false); // Update current user MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true); // Reset current user CurrentUser = null; } } } ShowChangesSaved(); } else { // If user exists ShowError(GetString("Administration-User_New.UserExists")); } } else { ShowError(result); } if ((ui.UserInvalidLogOnAttempts == 0) && (ui.UserAccountLockReason != UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached))) { btnResetLogonAttempts.Enabled = false; } LoadPasswordExpiration(ui); }
/// <summary> /// Delete attribute button clicked. /// </summary> protected void btnDeleteItem_Click(Object sender, ImageClickEventArgs e) { // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { if (Mode == FieldEditorModeEnum.BizFormDefinition) { // Check 'EditForm' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToAccessDenied("cms.form", "EditForm"); } } // Raise on before definition update event if (OnBeforeDefinitionUpdate != null) { OnBeforeDefinitionUpdate(this, EventArgs.Empty); } FormFieldInfo ffiSelected = null; DataClassInfo dci = null; WebPartInfo wpi = null; string errorMessage = null; string newSelectedValue = null; string deletedItemPreffix = null; // Clear settings simpleMode.Settings = new Hashtable(); controlSettings.Settings = new Hashtable(); TableManager tm = null; switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Get the web part { wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); if (wpi == null) { errorMessage = GetString("FieldEditor.WebpartNotFound"); return; } } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Get the DataClass dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci == null) { errorMessage = GetString("FieldEditor.ClassNotFound"); return; } tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); } break; } // Load current xml form definition LoadFormDefinition(); if ((!string.IsNullOrEmpty(SelectedItemName)) && (!IsNewItemEdited)) { if (SelectedItemType == FieldEditorSelectedItemEnum.Field) { ffiSelected = fi.GetFormField(SelectedItemName); deletedItemPreffix = fieldPreffix; if (ffiSelected != null) { // Do not allow deleting of the primary key except for external fields if (ffiSelected.PrimaryKey && !ffiSelected.External) { if (!DevelopmentMode) { ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK")); return; } else { // Check if at least one primary key stays if (fi.GetFields(true, true, false, true).Count() < 2) { ShowError(GetString("TemplateDesigner.ErrorCannotDeletePK")); return; } } } // Check if at least two fields stay in document type definition if ((Mode == FieldEditorModeEnum.ClassFormDefinition) && (fi.GetFields(true, true, true).Count() < 3)) { ShowError(GetString("TemplateDesigner.ErrorCannotDeleteAllCustomFields")); return; } // Do not allow deleting of the system field if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode) { ShowError(GetString("TemplateDesigner.ErrorCannotDeleteSystemField")); return; } // Remove specific field from xml form definition fi.RemoveFormField(SelectedItemName); // Get updated definition FormDefinition = fi.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Web part properties { wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { errorMessage = ex.Message; } } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // If document type is edited AND field that should be removed is FILE if ((mMode == FieldEditorModeEnum.ClassFormDefinition) && (!string.IsNullOrEmpty(ClassName)) && (ffiSelected.DataType == FormFieldDataTypeEnum.File)) { DocumentHelper.DeleteDocumentAttachments(ClassName, ffiSelected.Name, null); } // If bizform is edited AND field that should be removed is FILE if ((mMode == FieldEditorModeEnum.BizFormDefinition) && (!string.IsNullOrEmpty(ClassName)) && (ffiSelected.FieldType == FormFieldControlTypeEnum.UploadControl)) { BizFormInfoProvider.DeleteBizFormFiles(ClassName, ffiSelected.Name, CMSContext.CurrentSiteID); } // Update xml definition dci.ClassFormDefinition = FormDefinition; try { if (!ffiSelected.External) { // Remove corresponding column from table tm.DropTableColumn(dci.ClassTableName, SelectedItemName); // Update xml schema dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName); } } catch (Exception ex) { errorMessage = ex.Message; } // Deleted field is used as ClassNodeNameSource -> remove node name source if (dci.ClassNodeNameSource == SelectedItemName) { dci.ClassNodeNameSource = ""; } // Update changes in database try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } // Save the data class DataClassInfoProvider.SetDataClass(dci); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); // Update alternative forms var altforms = AlternativeFormInfoProvider.GetAlternativeForms("FormClassID=" + dci.ClassID, null); foreach (AlternativeFormInfo afi in altforms) { afi.ClearDefinition(fi.GetColumnNames()); AlternativeFormInfoProvider.SetAlternativeFormInfo(afi); } } } catch (Exception ex) { errorMessage = ex.Message; } // Refresh views and queries only if changes to DB were made if (!ffiSelected.External) { // Generate default view if (mMode == FieldEditorModeEnum.BizFormDefinition) { SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName); } else { SqlGenerator.GenerateDefaultView(dci, null); } // Regenerate queries SqlGenerator.GenerateDefaultQueries(dci, true, true); // Updates custom views if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition)) { try { tm.RefreshCustomViews(dci.ClassTableName); string lowClassName = dci.ClassName.ToLowerCSafe(); if (lowClassName == "cms.document" || lowClassName == "cms.tree") { tm.RefreshDocumentViews(); } } catch (Exception ex) { errorMessage = ResHelper.GetString("fieldeditor.refreshingviewsfailed"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Field Editor", "EXCEPTION", ex); } } } // Clear hashtables ClearHashtables(); } break; } } } else if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { deletedItemPreffix = categPreffix; // Remove specific category from xml form definition fi.RemoveFormCategory(SelectedItemName); // Get updated form definition FormDefinition = fi.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Web part { wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { errorMessage = ex.Message; } } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Standard classes { // Update xml definition dci.ClassFormDefinition = FormDefinition; // Update changes in database try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } // Save the data class DataClassInfoProvider.SetDataClass(dci); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); } } catch (Exception ex) { errorMessage = ex.Message; } } break; } } if (!string.IsNullOrEmpty(errorMessage)) { ShowError("[ FieldEditor.btnDeleteItem_Click() ]: " + errorMessage); } } else { // "delete" new item from the list IsNewItemEdited = false; } // Set new selected value ListItem deletedItem = lstAttributes.Items.FindByValue(deletedItemPreffix + SelectedItemName); int deletedItemIndex = lstAttributes.Items.IndexOf(deletedItem); if ((deletedItemIndex > 0) && (lstAttributes.Items[deletedItemIndex - 1] != null)) { newSelectedValue = lstAttributes.Items[deletedItemIndex - 1].Value; } // Reload data Reload(newSelectedValue); // Raise on after definition update event if (OnAfterDefinitionUpdate != null) { OnAfterDefinitionUpdate(this, EventArgs.Empty); } // Commit the transaction tr.Commit(); } }
/// <summary> /// Save selected field. /// </summary> private void SaveSelectedField() { // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { // FormFieldInfo structure with data from updated form FormFieldInfo ffiUpdated = null; // FormCategoryInfo structure with data from updated form FormCategoryInfo fciUpdated = null; // Determines whether it is a new attribute (or attribute to update) bool isNewItem = false; string errorMessage = null; DataClassInfo dci = null; WebPartInfo wpi = null; // Variables for changes in DB tables string tableName = null; string oldColumnName = null; string newColumnName = null; string newColumnSize = null; string newColumnType = null; string newColumnDefaultValue = null; // No default value bool newColumnAllowNull = true; TableManager tm = null; if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Fill WebPartInfo structure with data from database wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Fill ClassInfo structure with data from database dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { // Set table name tableName = dci.ClassTableName; tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); } else { ShowError(GetString("fieldeditor.notablename")); return; } } break; } } // Load current xml form definition LoadFormDefinition(); if (SelectedItemType == FieldEditorSelectedItemEnum.Field) { // Fill FormFieldInfo structure with original data ffi = fi.GetFormField(SelectedItemName); // Fill FormFieldInfo structure with updated form data ffiUpdated = FillFormFieldInfoStructure(ffi); // Determine whether it is a new attribute or not isNewItem = (ffi == null); // Check if the attribute name already exists if (isNewItem || (ffi.Name.ToLowerCSafe() != ffiUpdated.Name.ToLowerCSafe())) { columnNames = fi.GetColumnNames(); if (columnNames != null) { foreach (string colName in columnNames) { // If name already exists if (ffiUpdated.Name.ToLowerCSafe() == colName.ToLowerCSafe()) { ShowError(GetString("TemplateDesigner.ErrorExistingColumnName")); return; } } } // Check column name duplicity in JOINed tables if (!IsSystemFieldSelected) { // Check whether current column already exists in 'View_CMS_Tree_Joined' if (IsDocumentType && DocumentHelper.ColumnExistsInSystemTable(ffiUpdated.Name)) { ShowError(GetString("TemplateDesigner.ErrorExistingColumnInJoinedTable")); return; } // Check whether current column is unique in tables used to create views - applied only for system tables if ((Mode == FieldEditorModeEnum.SystemTable) && FormHelper.ColumnExistsInView(mClassName, ffiUpdated.Name)) { ShowError(GetString("TemplateDesigner.ErrorExistingColumnInJoinedTable")); return; } } } // New node if (isNewItem) { ffiUpdated.PrimaryKey = IsPrimaryField; newColumnName = ffiUpdated.Name; newColumnAllowNull = ffiUpdated.AllowEmpty; // Set implicit default value if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue))) { if (!DevelopmentMode) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: case FormFieldDataTypeEnum.Decimal: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = "0"; break; case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.DocumentAttachments: newColumnDefaultValue = ""; break; case FormFieldDataTypeEnum.DateTime: newColumnDefaultValue = new DateTime(1970, 1, 1, 0, 0, 0).ToString(); break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: // 32 digits, empty Guid newColumnDefaultValue = Guid.Empty.ToString(); break; case FormFieldDataTypeEnum.Binary: newColumnDefaultValue = null; break; } } } // Check if default value is in required format else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue)) { // If default value is macro, don't try to ensure the type if (!ffiUpdated.IsMacro) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: try { int i = Int32.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = i.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger"); } break; case FormFieldDataTypeEnum.LongInteger: try { long longInt = long.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = longInt.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger"); } break; case FormFieldDataTypeEnum.Decimal: if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue)) { newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue); } else { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble"); } break; case FormFieldDataTypeEnum.DateTime: if ((ffiUpdated.DefaultValue.ToLowerCSafe() == DateTimePicker.DATE_TODAY.ToLowerCSafe()) || (ffiUpdated.DefaultValue.ToLowerCSafe() == DateTimePicker.TIME_NOW.ToLowerCSafe())) { newColumnDefaultValue = ffiUpdated.DefaultValue; } else { try { DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = dat.ToString(); } catch { newColumnDefaultValue = DateTime.Now.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime"); } } break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: try { Guid g = new Guid(ffiUpdated.DefaultValue); newColumnDefaultValue = g.ToString(); } catch { newColumnDefaultValue = Guid.Empty.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid"); } break; case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = ffiUpdated.DefaultValue; break; } } } // Set column type and size LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize); if (string.IsNullOrEmpty(errorMessage)) { if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Add new column to specified table try { string newDBDefaultValue = null; // Check if it is not a macro if (ffiUpdated.IsMacro) { newDBDefaultValue = newColumnDefaultValue; } else { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Decimal: newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue); break; case FormFieldDataTypeEnum.DateTime: newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue); break; default: newDBDefaultValue = newColumnDefaultValue; break; } } if (!ffiUpdated.External) { if (DevelopmentMode) { tm.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue, false); } else { tm.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); } // Recreate the table PK constraint if (IsPrimaryField) { int pos = 0; var pkFields = fi.GetFields(true, true, true, true); string[] primaryKeys = new string[pkFields.Count() + 1]; foreach (FormFieldInfo pk in pkFields) { if (pk != null) { primaryKeys[pos++] = "[" + pk.Name + "]"; } } primaryKeys[pos] = "[" + newColumnName + "]"; tm.RecreatePKConstraint(tableName, primaryKeys); } } } catch (Exception ex) { ShowError(GetString("general.saveerror"), ex.Message, null); return; } break; } } } // Some error has occurred else { ShowError(errorMessage); return; } } // Existing node else { // Get info whether it is a primary key or system field ffiUpdated.PrimaryKey = ffi.PrimaryKey; // If attribute is a primary key if (ffi.PrimaryKey) { // Check if the attribute type is integer number if (ffiUpdated.DataType != FormFieldDataTypeEnum.Integer) { errorMessage += GetString("TemplateDesigner.ErrorPKNotInteger") + " "; } // Check if allow empty is disabled if (ffiUpdated.AllowEmpty) { errorMessage += GetString("TemplateDesigner.ErrorPKAllowsNulls") + " "; } // Check that the field type is label string labelControlName = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); if ((ffiUpdated.FieldType != FormFieldControlTypeEnum.LabelControl) && ((ffiUpdated.FieldType != FormFieldControlTypeEnum.CustomUserControl) && (ffiUpdated.Settings["controlname"].ToString().ToLowerCSafe() != labelControlName))) { errorMessage += GetString("TemplateDesigner.ErrorPKisNotLabel") + " "; } // Some error has occurred if (!string.IsNullOrEmpty(errorMessage)) { ShowError(GetString("TemplateDesigner.ErrorPKThisIsPK") + " " + errorMessage); return; } } // If table column update is needed if (((ffi.PrimaryKey) && (ffi.Name != ffiUpdated.Name)) || ((!ffi.PrimaryKey) && ((ffi.Name != ffiUpdated.Name) || (ffi.DataType != ffiUpdated.DataType) || (ffi.AllowEmpty != ffiUpdated.AllowEmpty) || (ffi.Size != ffiUpdated.Size) || ((ffi.DefaultValue != ffiUpdated.DefaultValue) || (ffiUpdated.DataType == FormFieldDataTypeEnum.Decimal))) ) ) { // Set variables needed for changes in DB oldColumnName = ffi.Name; newColumnName = ffiUpdated.Name; newColumnAllowNull = ffiUpdated.AllowEmpty; // Set implicit default value if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue))) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: case FormFieldDataTypeEnum.Decimal: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = "0"; break; case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: newColumnDefaultValue = ""; break; case FormFieldDataTypeEnum.DateTime: newColumnDefaultValue = DateTime.Now.ToString(); break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: // 32 digits, empty Guid newColumnDefaultValue = Guid.Empty.ToString(); break; case FormFieldDataTypeEnum.Binary: newColumnDefaultValue = null; break; } } // Check if default value is in required format else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue)) { // If default value is macro, don't try to ensure the type if (!ffiUpdated.IsMacro) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: try { int i = Int32.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = i.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger"); } break; case FormFieldDataTypeEnum.LongInteger: try { long longInt = long.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = longInt.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger"); } break; case FormFieldDataTypeEnum.Decimal: if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue)) { newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue); } else { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble"); } break; case FormFieldDataTypeEnum.DateTime: if ((ffiUpdated.DefaultValue.ToLowerCSafe() == DateTimePicker.DATE_TODAY.ToLowerCSafe()) || (ffiUpdated.DefaultValue.ToLowerCSafe() == DateTimePicker.TIME_NOW.ToLowerCSafe())) { newColumnDefaultValue = ffiUpdated.DefaultValue; } else { try { DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = dat.ToString(); } catch { newColumnDefaultValue = DateTime.Now.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime"); } } break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: try { Guid g = new Guid(ffiUpdated.DefaultValue); newColumnDefaultValue = g.ToString(); } catch { newColumnDefaultValue = Guid.Empty.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid"); } break; case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = ffiUpdated.DefaultValue; break; } } } // Set column type and size LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize); if (string.IsNullOrEmpty(errorMessage)) { if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: try { string newDBDefaultValue = null; // Check if it is not a macro if (ffiUpdated.IsMacro) { newDBDefaultValue = newColumnDefaultValue; } else { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Decimal: newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue); break; case FormFieldDataTypeEnum.DateTime: newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue); break; default: newDBDefaultValue = newColumnDefaultValue; break; } } if (ffiUpdated.External) { if (!ffi.External) { // Drop old column from table tm.DropTableColumn(tableName, ffi.Name); } } else { if (ffi.External) { // Add table column tm.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); } else { // Change table column tm.AlterTableColumn(tableName, oldColumnName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); if (OnFieldNameChanged != null) { OnFieldNameChanged(this, oldColumnName, newColumnName); } } } } catch (Exception ex) { // User friendly message for not null setting of column if (ffi.AllowEmpty && !newColumnAllowNull) { ShowError(GetString("FieldEditor.ColumnNotAcceptNull"), ex.Message, null); } else { ShowError(GetString("general.saveerror"), ex.Message, null); } return; } break; } } } // Some error has occurred else { ShowError(errorMessage); return; } } // End update needed } // End existing node // Insert new field if (isNewItem) { InsertFormItem(ffiUpdated); // Hide field for alternative forms that require it dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { var altforms = AlternativeFormInfoProvider.GetAlternativeForms("FormClassID=" + dci.ClassID, null); foreach (AlternativeFormInfo afi in altforms.Where<AlternativeFormInfo>(x => x.FormHideNewParentFields)) { afi.HideField(ffiUpdated); AlternativeFormInfoProvider.SetAlternativeFormInfo(afi); } } } // Update current field else { fi.UpdateFormField(ffi.Name, ffiUpdated); } } else if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { // Fill FormCategoryInfo structure with original data fci = fi.GetFormCategory(SelectedItemName); // Determine whether it is a new attribute or not isNewItem = (fci == null); // Fill FormCategoryInfo structure with updated form data fciUpdated = new FormCategoryInfo(); fciUpdated.CategoryCaption = categoryEdit.Value.Replace("'", ""); fciUpdated.CategoryCollapsible = categoryEdit.Collapsible; fciUpdated.CategoryCollapsedByDefault = categoryEdit.CollapsedByDefault; fciUpdated.VisibleMacro = categoryEdit.VisibleMacro; fciUpdated.Visible = categoryEdit.CategoryVisible; // Check if the category caption is empty if (string.IsNullOrEmpty(fciUpdated.CategoryCaption)) { ShowError(GetString("TemplateDesigner.ErrorCategoryNameEmpty")); return; } // Use codenamed category caption for name attribute fciUpdated.CategoryName = IsAlternativeForm ? fci.CategoryName : ValidationHelper.GetCodeName(fciUpdated.CategoryCaption); // Get form category names if ((isNewItem || fciUpdated.CategoryName != fci.CategoryName) && fi.GetCategoryNames().Exists(x => x == fciUpdated.CategoryName)) { ShowError(GetString("TemplateDesigner.ErrorExistingCategoryName")); return; } if (isNewItem) { // Insert new category InsertFormItem(fciUpdated); } else { // Update current fi.UpdateFormCategory(fci.CategoryName, fciUpdated); } } // Make changes in database if (SelectedItemType != 0) { // Get updated definition FormDefinition = fi.GetXmlDefinition(); string error = null; if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: if (wpi != null) { // Update xml definition wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { error = ex.Message; } } else { error = GetString("FieldEditor.WebpartNotFound"); } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: if (dci != null) { // Update xml definition dci.ClassFormDefinition = FormDefinition; // Update xml schema dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName); // When updating existing field if (ffi != null) { // Update ClassNodeNameSource field if (dci.ClassNodeNameSource == ffi.Name) { dci.ClassNodeNameSource = ffiUpdated.Name; } } // Update changes in DB try { // Save the data class DataClassInfoProvider.SetDataClass(dci); // Generate the class code - Temporarily disabled //GenerateCode(true); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); } catch (Exception ex) { error = ex.Message; } bool fieldType = (SelectedItemType == FieldEditorSelectedItemEnum.Field); if (fieldType) { // Generate default view if (mMode == FieldEditorModeEnum.BizFormDefinition) { SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName); } else { SqlGenerator.GenerateDefaultView(dci, null); } // Regenerate queries SqlGenerator.GenerateDefaultQueries(dci, true, true); } // Updates custom views if (((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))) { // Refresh views only if needed bool refreshViews = (fci == null); if ((ffi != null) && (ffiUpdated != null)) { refreshViews = false; if (ffi.Name != ffiUpdated.Name) { refreshViews = true; } if (ffi.DataType != ffiUpdated.DataType) { refreshViews = true; } if (ffi.Size != ffiUpdated.Size) { refreshViews = true; } if (ffi.AllowEmpty != ffiUpdated.AllowEmpty) { refreshViews = true; } if (ffi.DefaultValue != ffiUpdated.DefaultValue) { refreshViews = true; } } if (refreshViews) { try { tm.RefreshCustomViews(dci.ClassTableName); string lowClassName = dci.ClassName.ToLowerCSafe(); if (lowClassName == "cms.document" || lowClassName == "cms.tree") { tm.RefreshDocumentViews(); } } catch (Exception ex) { error = ResHelper.GetString("fieldeditor.refreshingviewsfailed"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Field Editor", "EXCEPTION", ex); } } } } else { error = GetString("FieldEditor.ClassNotFound"); } break; } } if (!string.IsNullOrEmpty(error)) { ShowError("[FieldEditor.SaveSelectedField()]: " + error); return; } IsNewItemEdited = false; if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { Reload(categPreffix + fciUpdated.CategoryName); } else if (SelectedItemType == FieldEditorSelectedItemEnum.Field) { Reload(fieldPreffix + ffiUpdated.Name); } ShowChangesSaved(); } // All done and new item, fire OnFieldCreated event if (isNewItem && (ffiUpdated != null)) { RaiseOnFieldCreated(ffiUpdated); } // Commit the transaction tr.Commit(); } }
/// <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> /// Saves new user's data into DB. /// </summary> /// <returns>Returns ID of created user</returns> protected int SaveNewUser() { UserInfo ui = new UserInfo(); // Load default values FormHelper.LoadDefaultValues("cms.user", ui); string emailAddress = txtEmailAddress.Text.Trim(); ui.PreferredCultureCode = ""; ui.Email = emailAddress; ui.FirstName = ""; ui.FullName = txtFullName.Text; ui.LastName = ""; ui.MiddleName = ""; ui.UserName = userName; ui.Enabled = chkEnabled.Checked; ui.IsExternal = false; // Set privilege level, global admin may set all levels, rest only editor UserPrivilegeLevelEnum privilegeLevel = (UserPrivilegeLevelEnum)drpPrivilegeLevel.Value.ToInteger(0); var isCurrentUserGlobalAdmin = CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin); if (isCurrentUserGlobalAdmin || (privilegeLevel == UserPrivilegeLevelEnum.None) || (privilegeLevel == UserPrivilegeLevelEnum.Editor)) { ui.SiteIndependentPrivilegeLevel = privilegeLevel; } bool assignUserToSite = chkAssignToSite.Checked && AllowAssignToWebsite; // Check license limitations if (SiteID > 0 || assignUserToSite) { string errorMessage = String.Empty; UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } } // Check whether email is unique if it is required string siteName = SiteName; if (assignUserToSite) { siteName = SiteContext.CurrentSiteName; } if (!UserInfoProvider.IsEmailUnique(emailAddress, siteName, 0)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return(-1); } if (!error) { using (var transaction = new CMSLateBoundTransaction()) { // Set password and save object UserInfoProvider.SetPassword(ui, passStrength.Text); if (isCurrentUserGlobalAdmin) { UserMacroIdentityHelper.SetMacroIdentity(ui, drpMacroIdentity.Value.ToInteger(0)); } // Add user to current site if ((SiteID > 0) || assignUserToSite) { UserInfoProvider.AddUserToSite(ui.UserName, siteName); } transaction.Commit(); } return(ui.UserID); } return(-1); }
/// <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; }
/// <summary> /// Saves form definition. Updates database column if both original and changed info is passed and the change requires database update. /// </summary> /// <param name="oldFieldInfo">Form field info prior to the change</param> /// <param name="updatedFieldInfo">Form field info after the change has been made.</param> /// <returns>Error message if an error occurred</returns> protected string SaveFormDefinition(FormFieldInfo oldFieldInfo = null, FormFieldInfo updatedFieldInfo = null) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm")) { if (RequestHelper.IsCallback()) { return GetString("formbuilder.missingeditpermission"); } RedirectToAccessDenied("cms.form", "EditForm"); } DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if ((FormInfo != null) && (dci != null)) { // Update database column of the changed field if (IsDatabaseChangeRequired(oldFieldInfo, updatedFieldInfo)) { // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { TableManager tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); string error = UpdateDatabaseColumn(oldFieldInfo, updatedFieldInfo, tm, dci.ClassTableName); if (!String.IsNullOrEmpty(error)) { return error; } // Commit the transaction tr.Commit(); } } // Update form definition dci.ClassFormDefinition = FormInfo.GetXmlDefinition(); // Save the class data DataClassInfoProvider.SetDataClassInfo(dci); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); return string.Empty; } else { return GetString("FormBuilder.ErrorSavingForm"); } }
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(); } } }
/// <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); }