/// <summary> /// Runs the update procedure. /// </summary> public static void Update() { if (DatabaseHelper.IsDatabaseAvailable && SystemContext.IsCMSRunningAsMainApplication) { try { string version = SettingsKeyInfoProvider.GetValue("CMSDataVersion"); switch (version.ToLowerCSafe()) { case "9.0": using (var context = new CMSActionContext()) { context.LogLicenseWarnings = false; UpgradeApplication(Upgrade90To100, "10.0", "Upgrade_90_100.zip"); } break; } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "UPGRADE", ex); } } }
void UniSelector_OnItemsSelected(object sender, EventArgs e) { try { int processId = ValidationHelper.GetInteger(ucSelector.Value, 0); AutomationManager manager = AutomationManager.GetInstance(CurrentUser); var infoObj = CMSObjectHelper.GetObjectById(listElem.ObjectType, listElem.ObjectID); using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; manager.StartProcess(infoObj, processId); } } catch (ProcessRecurrenceException ex) { ShowError(ex.Message); } catch (Exception ex) { LogAndShowError("Automation", "STARTPROCESS", ex); } listElem.UniGrid.ReloadData(); pnlUpdate.Update(); }
protected void btnCheckOut_Click(object sender, EventArgs e) { // Ensure version before check-out using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; // Save first if (!SaveData()) { return; } } try { SiteManagerFunctions.CheckOutWebPartLayout(layoutId); } catch (Exception ex) { lblError.Text = GetString("WebPartLayout.ErrorCheckout") + ": " + ex.Message; lblError.Visible = true; return; } URLHelper.Redirect(URLHelper.AddParameterToUrl(URLHelper.Url.AbsoluteUri, "saved", "1")); }
void UniSelector_OnItemsSelected(object sender, EventArgs e) { try { int contactId = ValidationHelper.GetInteger(ucSelector.Value, 0); AutomationManager manager = AutomationManager.GetInstance(CurrentUser); var infoObj = ContactInfoProvider.GetContactInfo(contactId); if (WorkflowStepInfoProvider.CanUserStartAutomationProcess(CurrentUser, SiteInfoProvider.GetSiteName(infoObj.ContactSiteID))) { using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; manager.StartProcess(infoObj, ProcessID); } } } catch (ProcessRecurrenceException ex) { ShowError(ex.Message); } catch (Exception ex) { LogAndShowError("Automation", "STARTPROCESS", ex); } listContacts.ReloadData(); pnlUpdate.Update(); }
protected void Page_Load(object sender, EventArgs e) { IssueInfo issue = EditedObject as IssueInfo; if (issue == null) { RedirectToAccessDenied(GetString("general.invalidparameters")); } if(!issue.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(issue.TypeInfo.ModuleName, "AuthorIssues"); } Guid subscriberGuid = QueryHelper.GetGuid("subscriberguid", Guid.Empty); SubscriberInfo subscriber = SubscriberInfoProvider.GetSubscriberInfo(subscriberGuid, SiteContext.CurrentSiteID); using (var context = new CMSActionContext()) { // Switch culture to the site culture, so the e-mail isn't rendered in the editor's culture string culture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName); context.Culture = CultureHelper.GetCultureInfo(culture); string htmlPage = NewsletterHelper.GetPreviewHTML(issue, subscriber); Response.Clear(); Response.Write(htmlPage); } RequestHelper.EndResponse(); }
/// <summary> /// Check out. /// </summary> protected void btnCheckOut_Click(object sender, EventArgs e) { // Ensure version before check-out using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; SetCurrentLayout(false, true); } try { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wpi != null) { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); if (wpli != null) { SiteManagerFunctions.CheckOutWebPartLayout(wpli.WebPartLayoutID); } } } catch (Exception ex) { this.lblError.Text = GetString("WebPartLayout.ErrorCheckout") + ": " + ex.Message; this.lblError.Visible = true; return; } SetCheckPanel(null); }
/// <summary> /// Runs the update procedure. /// </summary> public static void Update() { if (DatabaseHelper.IsDatabaseAvailable && SystemContext.IsCMSRunningAsMainApplication) { try { string version = SettingsKeyInfoProvider.GetValue("CMSDataVersion"); switch (version.ToLowerInvariant()) { case "12.0": using (var context = new CMSActionContext()) { context.LogLicenseWarnings = false; UpgradeApplication(Upgrade120To130, "13.0", "Upgrade_120_130.zip"); } break; } } catch (Exception ex) { Service.Resolve <IEventLogService>().LogException(EventLogSource, "UPGRADE", ex); } } }
void UniSelector_OnItemsSelected(object sender, EventArgs e) { try { int processId = ValidationHelper.GetInteger(ucSelector.Value, 0); AutomationManager manager = AutomationManager.GetInstance(CurrentUser); var infoObj = ProviderHelper.GetInfoById(listElem.ObjectType, listElem.ObjectID); using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; manager.StartProcess(infoObj, processId); } } catch (ProcessRecurrenceException ex) { ShowError(ex.Message); } catch (Exception ex) { LogAndShowError("Automation", "STARTPROCESS", ex); } listElem.UniGrid.ReloadData(); pnlUpdate.Update(); }
/// <summary> /// Runs the update procedure. /// </summary> public static void Update() { if (DatabaseHelper.IsDatabaseAvailable) { try { string version = SettingsKeyInfoProvider.GetValue("CMSDataVersion"); switch (version.ToLowerCSafe()) { case "8.1": using (var context = new CMSActionContext()) { context.LogLicenseWarnings = false; UpgradeApplication(Upgrade81To82, "8.2", "Upgrade_81_82.zip"); } break; } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "UPGRADE", ex); } } }
protected void Page_Load(object sender, EventArgs e) { IssueInfo issue = EditedObject as IssueInfo; if (issue == null) { RedirectToAccessDenied(GetString("general.invalidparameters")); } if (!issue.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(issue.TypeInfo.ModuleName, "AuthorIssues"); } Guid subscriberGuid = QueryHelper.GetGuid("subscriberguid", Guid.Empty); SubscriberInfo subscriber = SubscriberInfoProvider.GetSubscriberInfo(subscriberGuid, SiteContext.CurrentSiteID); using (var context = new CMSActionContext()) { // Switch culture to the site culture, so the e-mail isn't rendered in the editor's culture string culture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName); context.Culture = CultureHelper.GetCultureInfo(culture); string htmlPage = NewsletterHelper.GetPreviewHTML(issue, subscriber); Response.Clear(); Response.Write(htmlPage); } RequestHelper.EndResponse(); }
/// <summary> /// Click event - updates new values. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Params</param> protected void nameElem_Click(object sender, EventArgs e) { // Check 'EditForm' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToCMSDeskAccessDenied("cms.form", "EditForm"); } // Code name validation string err = new Validator().IsIdentificator(nameElem.CodeName, GetString("general.erroridentificatorformat")).Result; if (err != String.Empty) { lblError.Visible = true; lblError.Text = err; lblInfo.Visible = false; return; } // Validate form id AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(altFormId); EditedObject = afi; if (afi == null) { return; } // Checking for duplicate items DataSet ds = AlternativeFormInfoProvider.GetAlternativeForms("FormName='" + SqlHelperClass.GetSafeQueryString(nameElem.CodeName, false) + "' AND FormClassID=" + afi.FormClassID, null); if (!DataHelper.DataSourceIsEmpty(ds)) { if (!((ds.Tables.Count == 1) && (ds.Tables[0].Rows.Count == 1) && ( ValidationHelper.GetInteger(ds.Tables[0].Rows[0]["FormID"], 0) == altFormId))) { lblError.Visible = true; lblError.Text = GetString("general.codenameexists"); lblInfo.Visible = false; return; } } afi.FormDisplayName = nameElem.DisplayName; afi.FormName = nameElem.CodeName; AlternativeFormInfoProvider.SetAlternativeFormInfo(afi); // Required to log staging task, alternative form is not binded to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization BizFormInfo bfi = BizFormInfoProvider.GetBizFormInfo(formId); SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } URLHelper.Redirect("AlternativeForms_Edit_General.aspx?altformid=" + altFormId + "&formid=" + formId + "&saved=1"); }
private static void UpgradeApplication(Func <bool> versionSpecificMethod, string newVersion, string packageName) { // Increase the timeout for upgrade request due to expensive operations like macro signing and conversion (needed for large DBs) HttpContext.Current.Server.ScriptTimeout = 14400; EventLogProvider.LogInformation(EVENT_LOG_INFO, "Upgrade - Start"); // Set the path to the upgrade package (this has to be done here, not in the Import method, because it's an async procedure without HttpContext) mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/" + packageName); mWebsitePath = HttpContext.Current.Server.MapPath("~/"); using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; UpdateClasses(); UpdateAlternativeForms(); } // Update all views var dtm = new TableManager(null); dtm.RefreshDocumentViews(); RefreshCustomViews(dtm); // Set data version SettingsKeyInfoProvider.SetValue("CMSDataVersion", newVersion); SettingsKeyInfoProvider.SetValue("CMSDBVersion", newVersion); // Clear hashtables ModuleManager.ClearHashtables(); // Clear the cache CacheHelper.ClearCache(null, true); // Drop the routes CMSDocumentRouteHelper.DropAllRoutes(); // Init the Mimetype helper (required for the Import) MimeTypeHelper.LoadMimeTypes(); // Call version specific operations if (versionSpecificMethod != null) { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; versionSpecificMethod.Invoke(); } } UpgradeImportPackage(); }
private void UniSelector_OnItemsSelected(object sender, EventArgs e) { var contacts = ValidationHelper.GetString(ucSelector.Value, null); if (String.IsNullOrEmpty(contacts) || !WorkflowStepInfoProvider.CanUserStartAutomationProcess(CurrentUser, CurrentSiteName)) { return; } var contactIds = contacts.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(i => ValidationHelper.GetInteger(i, 0)); var manager = AutomationManager.GetInstance(CurrentUser); var processId = UIContext.ObjectID; var warningBuilder = new StringBuilder(); using (CMSActionContext context = new CMSActionContext { AllowAsyncActions = false }) { try { foreach (var contactId in contactIds) { var contact = ContactInfo.Provider.Get(contactId); try { manager.StartProcess(contact, processId); } catch (ProcessRecurrenceException ex) { warningBuilder.AppendFormat("<div>{0}</div>", ex.Message); } } } catch (Exception ex) { LogAndShowError("Automation", "STARTPROCESS", ex); return; } } var warning = warningBuilder.ToString(); if (!String.IsNullOrEmpty(warning)) { ShowWarning(String.Format(GetString("sf.automation.error"), ""), warning); } else { ShowConfirmation(GetString("ma.process.startedselected")); } // Reload grid listContacts.ReloadData(); pnlUpdate.Update(); // Reset selector ucSelector.Value = null; }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <returns>Whether node is already published</returns> private bool Publish(TreeNode node, WorkflowManager wm) { string pathCulture = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); WorkflowStepInfo currentStep = wm.GetStepInfo(node); bool alreadyPublished = (currentStep == null) || currentStep.StepIsPublished; if (!alreadyPublished) { using (CMSActionContext ctx = new CMSActionContext() { LogEvents = false }) { // Remove possible checkout if (node.DocumentCheckedOutByUserID > 0) { TreeProvider.ClearCheckoutInformation(node); node.Update(); } } // Publish document currentStep = wm.PublishDocument(node, null); } // Document is already published, check if still under workflow if (alreadyPublished && (currentStep != null) && currentStep.StepIsPublished) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { DocumentHelper.ClearWorkflowInformation(node); VersionManager vm = VersionManager.GetInstance(node.TreeProvider); vm.RemoveWorkflow(node); } } // Document already published if (alreadyPublished) { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), pathCulture)); } else if ((currentStep == null) || !currentStep.StepIsPublished) { AddError(string.Format(ResHelper.GetString("content.PublishWasApproved"), pathCulture)); return(true); } else { // Add log record AddLog(pathCulture); } return(false); }
protected void altFormFieldEditor_OnAfterSave(object sender, EventArgs e) { // Required to log staging task, alternative form is not bound to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } }
/// <summary> /// Recursivelly select or deselect all child elements. /// </summary> /// <param name="select">Determines the type of action</param> /// <param name="parentId">ID of the parent UIElement</param> /// <param name="excludeRoot">Indicates whether to exclude root element from selection/deselection</param> private void SelectDeselectAll(bool select, int parentId, bool excludeRoot) { // Check manage permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.UIPersonalization", CMSAdminControl.PERMISSION_MODIFY)) { RedirectToAccessDenied("CMS.UIPersonalization", CMSAdminControl.PERMISSION_MODIFY); } // Get the children and select them string where = (ModuleID > 0) ? String.Format(@"(ElementResourceID = {0} OR EXISTS (SELECT ElementID FROM CMS_UIElement AS x WHERE x.ElementIDPath like CMS_UIElement.ElementIDPath+ '%' AND x.ElementResourceID = {0})) AND ElementIDPath LIKE (SELECT TOP 1 ElementIDPath FROM CMS_UIElement WHERE ElementID = {1}) + '%' ", ModuleID, parentId) : "ElementIDPath LIKE (SELECT TOP 1 ElementIDPath FROM CMS_UIElement WHERE ElementID = " + parentId + ") + '%' "; if (excludeRoot) { where += " AND NOT ElementID = " + parentId; } if (!String.IsNullOrEmpty(GroupPreffix)) { where += " AND ElementName NOT LIKE '" + SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(GroupPreffix)) + "%'"; } using (CMSActionContext context = new CMSActionContext()) { // Many updates caused deadlocks with CMS_Role table, disable touch parent of the role context.TouchParent = false; DataSet ds = UIElementInfoProvider.GetUIElements(where, null, 0, "ElementID"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { int id = ValidationHelper.GetInteger(dr["ElementID"], 0); if (select) { RoleUIElementInfoProvider.AddRoleUIElementInfo(RoleID, id); } else { RoleUIElementInfoProvider.DeleteRoleUIElementInfo(RoleID, id); } } } // Explicitly touch the role only once var role = RoleInfoProvider.GetRoleInfo(RoleID); if (role != null) { role.Update(); } } }
private void GenerateCodes(object parameter) { try { // Construct cache for code uniqueness check var existingCodes = GetExistingCodes(); BaseInfo coupon = null; using (var context = new CMSActionContext()) { // Do not touch parent for all codes context.TouchParent = false; context.LogEvents = false; var logMessage = GetString("com.couponcode.generated"); // Create generator var generator = new RandomCodeGenerator(new CodeUniquenessChecker(existingCodes), pattern, prefix); for (var i = 0; i < count; i++) { // Get new code var code = generator.GenerateCode(); var couponConfig = GetCouponConfig(code); coupon = Discount.CreateCoupon(couponConfig); // Log that coupon was created AddLog(string.Format(logMessage, HTMLHelper.HTMLEncode(code))); } } // Touch parent (one for all) coupon?.Generalized.TouchParent(); // Log information that coupons were generated var logData = new EventLogData(EventTypeEnum.Information, "Discounts", "GENERATECOUPONCODES") { EventDescription = $"{count} coupon codes for discount '{Discount.DiscountDisplayName}' successfully generated.", UserID = CurrentUser.UserID, UserName = CurrentUser.UserName, SiteID = SiteContext.CurrentSiteID }; Service.Resolve <IEventLogService>().LogEvent(logData); } catch (Exception ex) { CurrentError = GetString("com.couponcode.generateerror"); Service.Resolve <IEventLogService>().LogException("Discounts", "GENERATECOUPONCODES", ex); } }
private static void UpgradeApplication(Func <bool> versionSpecificMethod, string newVersion, string packageName) { // Increase the timeout for upgrade request due to expensive operations like macro signing and conversion (needed for large DBs) HttpContext.Current.Server.ScriptTimeout = 14400; // CI can't be enabled during (and after) upgrade because repository won't be consistent with actual data on the database SettingsKeyInfoProvider.SetGlobalValue("CMSEnableCI", false); EventLogProvider.LogInformation(EventLogSource, "START"); // Set the path to the upgrade package (this has to be done here, not in the Import method, because it's an async procedure without HttpContext) mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/" + packageName); mWebsitePath = HttpContext.Current.Server.MapPath("~/"); // Update class form and alt.form definitions var classFormDefinitionUpdateHelper = new ClassFormDefinitionUpdateHelper(EventLogSource); classFormDefinitionUpdateHelper.UpdateClassFormDefinitions(); // Set data version SettingsKeyInfoProvider.SetGlobalValue("CMSDataVersion", newVersion); SettingsKeyInfoProvider.SetGlobalValue("CMSDBVersion", newVersion); // Clear hashtables ModuleManager.ClearHashtables(); // Clear the cache CacheHelper.ClearCache(null, true); // Drop the routes CMSDocumentRouteHelper.DropAllRoutes(); // Call version specific operations if (versionSpecificMethod != null) { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; versionSpecificMethod.Invoke(); } } // Import upgrade package with webparts, widgets... UpgradeImportPackage(); RefreshMacroSignatures(); EventLogProvider.LogInformation(EventLogSource, "FINISH"); }
void nameElem_Click(object sender, EventArgs e) { // Check 'EditForm' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToCMSDeskAccessDenied("cms.form", "EditForm"); } // Code name validation string err = new Validator().IsIdentificator(nameElem.CodeName, GetString("general.erroridentificatorformat")).Result; if (err != String.Empty) { lblError.Visible = true; lblError.Text = err; return; } // Checking for duplicate items DataSet ds = AlternativeFormInfoProvider.GetAlternativeForms("FormName='" + nameElem.CodeName + "' AND FormClassID=" + classId, null); if (!DataHelper.DataSourceIsEmpty(ds)) { lblError.Visible = true; lblError.Text = GetString("general.codenameexists"); return; } // Create new info object AlternativeFormInfo afi = new AlternativeFormInfo(); afi.FormID = 0; afi.FormGUID = Guid.NewGuid(); afi.FormClassID = classId; afi.FormName = nameElem.CodeName; afi.FormDisplayName = nameElem.DisplayName; AlternativeFormInfoProvider.SetAlternativeFormInfo(afi); // Required to log staging task, alternative form is not binded to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } URLHelper.Redirect("AlternativeForms_Frameset.aspx?formid=" + formId.ToString() + "&altformid=" + afi.FormID + "&saved=1"); }
protected void altFormEdit_OnAfterSave(object sender, EventArgs e) { // Required to log staging task, alternative form is not bound to bizform as a child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization int formId = QueryHelper.GetInteger("formid", 0); BizFormInfo bfi = BizFormInfoProvider.GetBizFormInfo(formId); SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } }
void layoutElem_OnAfterSave(object sender, EventArgs e) { // Required to log staging task, alternative form is not binded to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization int formId = QueryHelper.GetInteger("formid", 0); BizFormInfo bfi = BizFormInfoProvider.GetBizFormInfo(formId); SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } }
private void GenerateCodes(object parameter) { try { // Construct cache for code uniqueness check var existingCodes = GetExistingCodes(); BaseInfo coupon = null; using (CMSActionContext context = new CMSActionContext()) { // Do not touch parent for all codes context.TouchParent = false; context.LogEvents = false; // Create generator var generator = new RandomCodeGenerator(pattern, prefix); // Use cache for checking code uniqueness generator.CodeChecker = code => !existingCodes.Contains(code); for (int i = 0; i < count; i++) { // Get new code string code = generator.GenerateCode(); coupon = Discount.CreateCoupon(code, numberOfUses); // Log that coupon was created AddLog(string.Format(GetString("com.couponcode.generated"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(code)))); } } // Touch parent (one for all) if (coupon != null) { coupon.Generalized.TouchParent(); } // Log information that coupons were generated EventLogProvider.LogEvent(EventType.INFORMATION, "Discounts", "GENERATECOUPONCODES", string.Format("{0} coupon codes for discount '{1}' successfully generated.", count, Discount.DiscountDisplayName), userId: CurrentUser.UserID, userName: CurrentUser.UserName, siteId: SiteContext.CurrentSiteID ); } catch (Exception ex) { CurrentError = GetString("com.couponcode.generateerror"); EventLogProvider.LogException("Discounts", "GENERATECOUPONCODES", ex); } }
void Process_OnItemsSelected(object sender, EventArgs e) { try { int processId = ValidationHelper.GetInteger(processSelector.Value, 0); AutomationManager manager = AutomationManager.GetInstance(CurrentUser); ContactGroupContactListInfo listInfo = new ContactGroupContactListInfo(); var contacts = listInfo.Generalized.GetData(null, GetWhereCondition(), null, 0, "ContactID", false); if (!DataHelper.DataSourceIsEmpty(contacts)) { string error = null; using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; foreach (DataRow row in contacts.Tables[0].Rows) { // Get contact int contactId = ValidationHelper.GetInteger(row[0], 0); var contact = ContactInfoProvider.GetContactInfo(contactId); try { // Start process manager.StartProcess(contact, processId); } catch (ProcessRecurrenceException ex) { error += ex.Message + "<br />"; } } } if (string.IsNullOrEmpty(error)) { ShowConfirmation(GetString("ma.process.started")); } else { ShowError(GetString("ma.process.error"), error, null); } } } catch (Exception ex) { LogAndShowError("Automation", "STARTPROCESS", ex); } gridElem.ReloadData(); pnlUpdate.Update(); }
protected void altFormEdit_OnAfterSave(object sender, EventArgs e) { // Required to log staging task, alternative form is not bound to bizform as a child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } URLHelper.Redirect("AlternativeForms_Frameset.aspx?formid=" + bfi.FormID + "&altformid=" + ((AlternativeFormInfo)EditedObject).FormID + "&saved=1"); }
/// <summary> /// Procedures which automatically imports the upgrade export package with all WebParts, Widgets, Reports and TimeZones. /// </summary> private static void UpgradeImportPackage() { // Import try { RequestStockHelper.Remove("CurrentDomain", true); var importSettings = new SiteImportSettings(MembershipContext.AuthenticatedUser) { DefaultProcessObjectType = ProcessObjectEnum.All, SourceFilePath = mUpgradePackagePath, WebsitePath = mWebsitePath }; using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; ImportProvider.ImportObjectsData(importSettings); // Regenerate time zones TimeZoneInfoProvider.GenerateTimeZoneRules(); // Delete the files for separable modules which are not install and therefore not needed DeleteWebPartsOfUninstalledModules(); ImportMetaFiles(Path.Combine(mWebsitePath, "App_Data\\CMSTemp\\Upgrade")); } } catch (Exception ex) { EventLogProvider.LogException(EVENT_LOG_INFO, "Upgrade", ex); } finally { try { RefreshMacroSignatures(); EventLogProvider.LogInformation(EVENT_LOG_INFO, "Upgrade - Finish"); } catch (Exception ex) { EventLogProvider.LogException(EVENT_LOG_INFO, "Upgrade", ex); } } }
/// <summary> /// Recursivelly select or deselect all child elements. /// </summary> /// <param name="select">Determines the type of action</param> /// <param name="parentId">ID of the parent UIElement</param> /// <param name="excludeRoot">Indicates whether to exclude root element from selection/deselection</param> private void SelectDeselectAll(bool select, int parentId, bool excludeRoot) { // Check manage permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.UIPersonalization", CMSAdminControl.PERMISSION_MODIFY)) { RedirectToAccessDenied("CMS.UIPersonalization", CMSAdminControl.PERMISSION_MODIFY); } // Get the children and select them (do not use module as filter if all elements should be visible) string where = ((ModuleID > 0) && !ShowAllElementsFromModuleSection) ? String.Format(@"(ElementResourceID = {0} OR EXISTS (SELECT ElementID FROM CMS_UIElement AS x WHERE x.ElementIDPath LIKE CMS_UIElement.ElementIDPath+ '%' AND x.ElementResourceID = {0})) AND ElementIDPath LIKE (SELECT TOP 1 ElementIDPath FROM CMS_UIElement WHERE ElementID = {1}) + '%' ", ModuleID, parentId) : "ElementIDPath LIKE (SELECT TOP 1 ElementIDPath FROM CMS_UIElement WHERE ElementID = " + parentId + ") + '%' "; if (excludeRoot) { where += " AND NOT ElementID = " + parentId; } if (!String.IsNullOrEmpty(GroupPreffix)) { where += " AND ElementName NOT LIKE '" + SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(GroupPreffix)) + "%'"; } using (CMSActionContext context = new CMSActionContext()) { // Many updates caused deadlocks with CMS_Role table, disable touch parent of the role context.TouchParent = false; var elementIds = UIElementInfoProvider.GetUIElements() .Where(where) .Columns("ElementID") .GetListResult <int>(); foreach (var id in elementIds) { if (select) { RoleUIElementInfoProvider.AddRoleUIElementInfo(RoleID, id); } else { RoleUIElementInfoProvider.DeleteRoleUIElementInfo(RoleID, id); } } // Explicitly touch the role only once RoleInfoProvider.GetRoleInfo(RoleID) ?.Update(); } }
private void listElem_OnDelete(object sender, object actionArgument) { // Check 'EditForm' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToCMSDeskAccessDenied("cms.form", "EditForm"); } AlternativeFormInfoProvider.DeleteAlternativeFormInfo(ValidationHelper.GetInteger(actionArgument, 0)); // Required to log staging task, alternative form is not bound to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } }
void listElem_OnDelete(object sender, object actionArgument) { // Check 'EditForm' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToCMSDeskAccessDenied("cms.form", "EditForm"); } AlternativeFormInfoProvider.DeleteAlternativeFormInfo(ValidationHelper.GetInteger(actionArgument, 0)); // Required to log staging task, alternative form is not binded to bizform as child using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; // Log synchronization SynchronizationHelper.LogObjectChange(bfi, TaskTypeEnum.UpdateObject); } }
/// <summary> /// Refreshes macro signatures in all object which can contain macros. /// </summary> private static void RefreshMacroSignatures() { // Get object types var objectTypes = new List <string> { TransformationInfo.OBJECT_TYPE, UIElementInfo.OBJECT_TYPE, FormUserControlInfo.OBJECT_TYPE, SettingsKeyInfo.OBJECT_TYPE, AlternativeFormInfo.OBJECT_TYPE, DataClassInfo.OBJECT_TYPE, DataClassInfo.OBJECT_TYPE_SYSTEMTABLE, DataClassInfo.OBJECT_TYPE_CUSTOMTABLE, DataClassInfo.OBJECT_TYPE_DOCUMENTTYPE, PageTemplateInfo.OBJECT_TYPE, LayoutInfo.OBJECT_TYPE, CssStylesheetInfo.OBJECT_TYPE, WorkflowActionInfo.OBJECT_TYPE, }; foreach (string type in objectTypes) { try { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; var infos = new InfoObjectCollection(type); foreach (var info in infos) { MacroSecurityProcessor.RefreshSecurityParameters(info, "administrator", true); } } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "REFRESHMACROSIGNATURES", ex, 0, "Type: " + type); } } }
/// <summary> /// Refreshes macro signatures in all object which can contain macros. /// </summary> private static void RefreshMacroSignatures() { // Get object types var objectTypes = new List <string> { TransformationInfo.OBJECT_TYPE, UIElementInfo.OBJECT_TYPE, FormUserControlInfo.OBJECT_TYPE, SettingsKeyInfo.OBJECT_TYPE, AlternativeFormInfo.OBJECT_TYPE, DataClassInfo.OBJECT_TYPE, // Process all data classes just through general object type to avoid duplicities PageTemplateInfo.OBJECT_TYPE, LayoutInfo.OBJECT_TYPE, CssStylesheetInfo.OBJECT_TYPE, WorkflowActionInfo.OBJECT_TYPE, }; var adminIdentityOption = MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser); foreach (string type in objectTypes) { try { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; var infos = new InfoObjectCollection(type); foreach (var info in infos) { MacroSecurityProcessor.RefreshSecurityParameters(info, adminIdentityOption, true); } } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "REFRESHMACROSIGNATURES", ex, 0, "Type: " + type); } } }
/// <summary> /// Resets invalid logon attempts for current user. /// </summary> private static void ResetCurrentUserInvalidLogonAttempts() { var currentUser = GetUserForAuthentication(); if (currentUser != null) { // Disable logging using (CMSActionContext context = new CMSActionContext()) { context.LogSynchronization = false; context.LogExport = false; context.LogEvents = false; // Reset invalid logon attempts currentUser.UserInvalidLogOnAttempts = 0; // Update current user UserInfoProvider.SetUserInfo(currentUser); } } }
/// <summary> /// Destroys object (without creating new version for recycle bin). Called when the "DestroyObject" button is pressed. /// Expects the CreateVersionedObject method to be run first. /// </summary> private bool DestroyObject() { // Get the css stylesheet CssStylesheetInfo destroyStylesheet = CssStylesheetInfoProvider.GetCssStylesheetInfo("MyNewVersionedStylesheet"); if (destroyStylesheet != null) { // Destroy the object (in action context with disabled creating of new versions for recycle bin) using (CMSActionContext context = new CMSActionContext()) { // Disable creating of new versions context.CreateVersion = false; // Destroy the css stylesheet CssStylesheetInfoProvider.DeleteCssStylesheetInfo(destroyStylesheet); return(true); } } return(false); }
private void CheckOut() { // Ensure version before check-out using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; // Validate and save the transformation if (ValidateAndSave()) { return; } } try { SiteManagerFunctions.CheckOutTransformation(transformationId); URLHelper.Redirect(URLHelper.AddParameterToUrl(URLHelper.Url.AbsoluteUri, "saved", "1")); } catch (Exception ex) { ShowError(string.Concat(GetString("Transformation.ErrorCheckout"), ": ", ex.Message)); } }
/// <summary> /// Runs the update procedure. /// </summary> public static void Update() { if (DatabaseHelper.IsDatabaseAvailable) { try { string version = SettingsKeyInfoProvider.GetStringValue("CMSDataVersion"); switch (version.ToLowerCSafe()) { case "7.0": using (var context = new CMSActionContext()) { context.LogLicenseWarnings = false; UpgradeApplication(Upgrade70To80, "8.0", "Upgrade_70_80.zip"); } break; } } catch { } } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void uniGrid_OnAction(string actionName, object actionArgument) { string templateId = actionArgument.ToString(); switch (actionName.ToLower()) { // Edit the template case "edit": URLHelper.Redirect("NewsletterTemplate_Edit.aspx?templateid=" + templateId); break; // Delete the template case "delete": // Check 'Manage templates' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.newsletter", "managetemplates")) { RedirectToCMSDeskAccessDenied("cms.newsletter", "managetemplates"); } // Check if the template is used in a newsletter string where = string.Format("(NewsletterTemplateID={0}) OR (NewsletterSubscriptionTemplateID={0}) OR (NewsletterUnsubscriptionTemplateID={0}) OR (NewsletterOptInTemplateID={0})", templateId); DataSet newsByEmailtempl = NewsletterProvider.GetNewsletters(where, null, 1, "NewsletterID"); if (DataHelper.DataSourceIsEmpty(newsByEmailtempl)) { // Check if the template is used in an issue DataSet newsletterIssues = IssueProvider.GetIssues("IssueTemplateID = " + templateId, null, 1, "IssueID"); if (DataHelper.DataSourceIsEmpty(newsletterIssues)) { // Delete EmailTemplate object from database EmailTemplateProvider.DeleteEmailTemplate(ValidationHelper.GetInteger(templateId, 0)); } else { ShowError(GetString("NewsletterTemplate_List.TemplateInUseByNewsletterIssue")); } } else { ShowError(GetString("NewsletterTemplate_List.TemplateInUseByNewsletter")); } break; // Clone the template case "clone": if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.newsletter", "managetemplates")) { RedirectToCMSDeskAccessDenied("cms.newsletter", "managetemplates"); } int tmpId = ValidationHelper.GetInteger(templateId, 0); EmailTemplate oldet = EmailTemplateProvider.GetEmailTemplate(tmpId); if (oldet != null) { EmailTemplate et = new EmailTemplate(); et.TemplateBody = oldet.TemplateBody; et.TemplateDisplayName = oldet.TemplateDisplayName; et.TemplateSubject = oldet.TemplateSubject; et.TemplateFooter = oldet.TemplateFooter; et.TemplateHeader = oldet.TemplateHeader; et.TemplateID = 0; et.TemplateName = oldet.TemplateName; et.TemplateSiteID = oldet.TemplateSiteID; et.TemplateStylesheetText = oldet.TemplateStylesheetText; et.TemplateType = oldet.TemplateType; string templateName = et.TemplateName; string templateDisplayName = et.TemplateDisplayName; while (EmailTemplateProvider.GetEmailTemplate(templateName, et.TemplateSiteID) != null) { templateName = Increment(templateName, "_", ""); templateDisplayName = Increment(templateDisplayName, "(", ")"); } et.TemplateName = templateName; et.TemplateDisplayName = templateDisplayName; // Get new ID using (CMSActionContext context = new CMSActionContext()) { // Disable versioning to prevent creating new version on first set context.CreateVersion = false; EmailTemplateProvider.SetEmailTemplate(et); } List<Guid> convTable = new List<Guid>(); try { MetaFileInfoProvider.CopyMetaFiles(tmpId, et.TemplateID, NewsletterObjectType.NEWSLETTERTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE, convTable); } catch (Exception e) { ShowError(e.Message); EmailTemplateProvider.DeleteEmailTemplate(et); return; } for (int i = 0; i < convTable.Count; i += 2) { et.TemplateBody = et.TemplateBody.Replace(convTable[i].ToString(), convTable[i + 1].ToString()); } EmailTemplateProvider.SetEmailTemplate(et); } break; } }
/// <summary> /// Procedures which automatically imports the upgrade export package with all WebParts, Widgets, Reports and TimeZones. /// </summary> private static void UpgradeImportPackage() { // Import try { RequestStockHelper.Remove("CurrentDomain", true); var importSettings = new SiteImportSettings(MembershipContext.AuthenticatedUser) { DefaultProcessObjectType = ProcessObjectEnum.All, SourceFilePath = mUpgradePackagePath, WebsitePath = mWebsitePath }; using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; ImportProvider.ImportObjectsData(importSettings); // Regenerate time zones TimeZoneInfoProvider.GenerateTimeZoneRules(); // Delete the files for separable modules which are not install and therefore not needed DeleteWebPartsOfUninstalledModules(); ImportMetaFiles(Path.Combine(mWebsitePath, "App_Data\\CMSTemp\\Upgrade")); } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "IMPORT", ex); } }
/// <summary> /// Handles the action event. /// </summary> /// <param name="cmdName">Command name</param> /// <param name="cmdValue">Command value</param> public void HandleAction(string cmdName, string cmdValue) { string action = cmdName.ToLower(); // Check action security and redirect if user not authorized CheckActionAndRedirect(action); GeneralizedInfo infoObj = null; int objectId = 0; switch (action) { case "#delete": case "#destroyobject": { // Delete the object objectId = ValidationHelper.GetInteger(cmdValue, 0); if (objectId > 0) { infoObj = CMSObjectHelper.GetReadOnlyObject(ObjectType); infoObj = BaseAbstractInfoProvider.GetInfoById(infoObj.TypeInfo.OriginalObjectType, objectId); if (infoObj != null) { switch (action) { case "#delete": // Check the dependencies AbstractProvider providerObj = infoObj.TypeInfo.ProviderObject; if (providerObj.CheckObjectDependencies(objectId)) { lblError.Visible = true; lblError.Text = GetString("ecommerce.deletedisabledwithoutenable"); return; } // Delete the object infoObj.DeleteObject(); break; case "#destroyobject": if (CMSContext.CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, infoObj.ObjectType, CMSContext.CurrentSiteName)) { using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; Action ac = GridActions.GetAction("#delete"); if (ac != null) { HandleAction("#delete", cmdValue); } else { ac = GridActions.GetAction("delete"); if (ac != null) { RaiseAction("delete", cmdValue); } else { lblError.Visible = true; lblError.Text = GetString("objectversioning.destroyobject.nodeleteaction"); return; } } } } break; } } } } break; default: RaiseAction(cmdName, cmdValue); break; } }
/// <summary> /// Handles the action event. /// </summary> /// <param name="cmdName">Command name</param> /// <param name="cmdValue">Command value</param> public void HandleAction(string cmdName, string cmdValue) { string action = cmdName.ToLowerCSafe(); // Check action security and redirect if user not authorized CheckActionAndRedirect(action); switch (action) { case "#delete": case "#destroyobject": case "#moveup": case "#movedown": { // Delete the object int objectId = ValidationHelper.GetInteger(cmdValue, 0); if (objectId > 0) { BaseInfo infoObj = ModuleManager.GetReadOnlyObject(ObjectType); string objectType = infoObj.TypeInfo.Inherited ? infoObj.TypeInfo.OriginalObjectType : infoObj.TypeInfo.ObjectType; infoObj = BaseAbstractInfoProvider.GetInfoById(objectType, objectId); if (infoObj != null) { switch (action) { case "#delete": if (infoObj.CheckPermissions(PermissionsEnum.Delete, SiteContext.CurrentSiteName, CurrentUser)) { try { // Delete the object infoObj.Delete(); } catch (CheckDependenciesException) { // Check the dependencies a display message List<string> names = infoObj.Generalized.GetDependenciesNames(); if ((names != null) && (names.Count > 0)) { string description = null; if (names.Count > 0) { // Encode and localize names StringBuilder sb = new StringBuilder(); names.ForEach(item => sb.Append("<br />", HTMLHelper.HTMLEncode(ResHelper.LocalizeString(item)))); description = GetString(objectType.Replace(".", "_") + ".objectlist|unigrid.objectlist") + sb; } ShowError(GetString("unigrid.deletedisabledwithoutenable"), description); return; } } // Raid for additional actions RaiseAction(cmdName, cmdValue); } break; case "#destroyobject": if (MembershipContext.AuthenticatedUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, infoObj.TypeInfo.ObjectType, SiteContext.CurrentSiteName)) { using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; Action ac = GridActions.GetAction("#delete"); if (ac != null) { HandleAction("#delete", cmdValue); } else { ac = GridActions.GetAction("delete"); if (ac != null) { RaiseAction("delete", cmdValue); } else { ShowError(GetString("objectversioning.destroyobject.nodeleteaction")); return; } } } } break; case "#moveup": if (infoObj.CheckPermissions(PermissionsEnum.Modify, SiteContext.CurrentSiteName, CurrentUser)) { infoObj.Generalized.MoveObjectUp(); } break; case "#movedown": if (infoObj.CheckPermissions(PermissionsEnum.Modify, SiteContext.CurrentSiteName, CurrentUser)) { infoObj.Generalized.MoveObjectDown(); } break; } } } } break; default: RaiseAction(cmdName, cmdValue); break; } }
/// <summary> /// Delete attribute button clicked. /// </summary> protected void btnDeleteItem_Click(Object sender, System.Web.UI.ImageClickEventArgs e) { 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(); // 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 (!this.DevelopmentMode) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK"; return; } else { // Check if at least one primary key stays if (fi.GetFields(true, true, false, true).Length < 2) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK"; return; } } } // Check if at least two fields stay in document type definition if ((this.Mode == FieldEditorModeEnum.ClassFormDefinition) && (fi.GetFields(true, true, true).Length < 3)) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteAllCustomFields"; return; } // Do not allow deleting of the system field if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteSystemField"; return; } // Remove specifield field from xml form definition fi.RemoveFormField(SelectedItemName); // Get updated definition FormDefinition = fi.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Web part properties { wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); if (wpi != null) { wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { errorMessage = ex.Message; } } else { errorMessage = GetString("FieldEditor.WebpartNotFound"); } } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Standard classes dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { // 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 TableManager.DropTableColumn(dci.ClassTableName, SelectedItemName); // Update xml schema dci.ClassXmlSchema = TableManager.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); } } catch (Exception ex) { errorMessage = ex.Message; } // Refresh views and quries 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 { TableManager.RefreshCustomViews(dci.ClassTableName); string lowClassName = dci.ClassName.ToLower(); if (lowClassName == "cms.document" || lowClassName == "cms.tree") { TableManager.RefreshDocumentViews(); } } catch (Exception ex) { errorMessage = ResHelper.GetString("fieldeditor.refreshingviewsfailed"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Field Editor", "EXCEPTION", ex); } } } // Clear hashtables ClearHashtables(); } else { errorMessage = GetString("FieldEditor.ClassNotFound"); } } break; } } } else if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { deletedItemPreffix = categPreffix; // Remove specifield category from xml form definition fi.RemoveFormCategory(SelectedItemName); // Get updated form definition FormDefinition = fi.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); if (wpi != null) { wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { errorMessage = ex.Message; } } else { errorMessage = GetString("FieldEditor.WebpartNotFound"); } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { // 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; } } else { errorMessage = GetString("FieldEditor.ClassNotFound"); } break; } } if (!string.IsNullOrEmpty(errorMessage)) { lblError.Visible = true; lblError.Text = "[ 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); } }
/// <summary> /// Called when source field selected index changed. /// </summary> protected void documentSource_OnSourceFieldChanged(object sender, EventArgs e) { if (mMode == FieldEditorModeEnum.ClassFormDefinition) { string errorMessage = null; DataClassInfo dci = DataClassInfoProvider.GetDataClass(ClassName); if (dci != null) { // Set document name source field if (string.IsNullOrEmpty(documentSource.SourceFieldValue)) { // Use extra field dci.ClassNodeNameSource = ""; } else { // Use specified name dci.ClassNodeNameSource = documentSource.SourceFieldValue; } // Set document alias source field if (string.IsNullOrEmpty(documentSource.SourceAliasFieldValue)) { // Use extra field dci.ClassNodeAliasSource = ""; } else { // Use specified name dci.ClassNodeAliasSource = documentSource.SourceAliasFieldValue; } try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } DataClassInfoProvider.SetDataClass(dci); } lblError.Visible = false; lblInfo.Visible = true; lblInfo.ResourceString = "TemplateDesigner.SourceFieldSaved"; } catch (Exception ex) { errorMessage = ex.Message; } } else { errorMessage = GetString("FieldEditor.ClassNotFound"); } if (!string.IsNullOrEmpty(errorMessage)) { lblError.Visible = true; lblError.Text = "[ FieldEditor.drpSourceField_SelectedIndexChanged() ]: " + errorMessage; } } }
/// <summary> /// Initializes the custom table /// </summary> /// <param name="dci">DataClassInfo of the custom table</param> /// <param name="fi">Form info</param> /// <param name="tm">Table manager</param> private void InitCustomTable(DataClassInfo dci, FormInfo fi, TableManager tm) { // Created by if (chkItemCreatedBy.Checked && !fi.FieldExists("ItemCreatedBy")) { FormFieldInfo ffi = new FormFieldInfo(); // Fill FormInfo object ffi.Name = "ItemCreatedBy"; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Created by"); ffi.DataType = FieldDataType.Integer; ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty); ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); ffi.PrimaryKey = false; ffi.System = true; ffi.Visible = false; ffi.Size = 0; ffi.AllowEmpty = true; fi.AddFormItem(ffi); } // Created when if (chkItemCreatedWhen.Checked && !fi.FieldExists("ItemCreatedWhen")) { FormFieldInfo ffi = new FormFieldInfo(); // Fill FormInfo object ffi.Name = "ItemCreatedWhen"; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Created when"); ffi.DataType = FieldDataType.DateTime; ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty); ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); ffi.PrimaryKey = false; ffi.System = true; ffi.Visible = false; ffi.Size = 0; ffi.AllowEmpty = true; fi.AddFormItem(ffi); } // Modified by if (chkItemModifiedBy.Checked && !fi.FieldExists("ItemModifiedBy")) { FormFieldInfo ffi = new FormFieldInfo(); // Fill FormInfo object ffi.Name = "ItemModifiedBy"; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Modified by"); ffi.DataType = FieldDataType.Integer; ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty); ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); ffi.PrimaryKey = false; ffi.System = true; ffi.Visible = false; ffi.Size = 0; ffi.AllowEmpty = true; fi.AddFormItem(ffi); } // Modified when if (chkItemModifiedWhen.Checked && !fi.FieldExists("ItemModifiedWhen")) { FormFieldInfo ffi = new FormFieldInfo(); // Fill FormInfo object ffi.Name = "ItemModifiedWhen"; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Modified when"); ffi.DataType = FieldDataType.DateTime; ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty); ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); ffi.PrimaryKey = false; ffi.System = true; ffi.Visible = false; ffi.Size = 0; ffi.AllowEmpty = true; fi.AddFormItem(ffi); } // Item order if (chkItemOrder.Checked && !fi.FieldExists("ItemOrder")) { FormFieldInfo ffi = new FormFieldInfo(); // Fill FormInfo object ffi.Name = "ItemOrder"; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Order"); ffi.DataType = FieldDataType.Integer; ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, string.Empty); ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe(); ffi.PrimaryKey = false; ffi.System = true; ffi.Visible = false; ffi.Size = 0; ffi.AllowEmpty = true; fi.AddFormItem(ffi); } // GUID if (chkItemGUID.Checked && !fi.FieldExists("ItemGUID")) { var ffiGuid = CreateGuidField(); fi.AddFormItem(ffiGuid); } // Update table structure - columns could be added bool old = TableManager.UpdateSystemFields; TableManager.UpdateSystemFields = true; string schema = fi.GetXmlDefinition(); tm.UpdateTableByDefinition(dci.ClassTableName, schema); TableManager.UpdateSystemFields = old; // Update xml schema and form definition dci.ClassFormDefinition = schema; dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName); using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); } }
/// <summary> /// Creates default transformations for the classid. /// </summary> /// <param name="classId">Class id</param> /// <param name="isDocument">Indicates if transformations for document should be created</param> private void CreateDefaultTransformations(int classId, bool isDocument) { using (CMSActionContext context = new CMSActionContext()) { // Disable logging of tasks context.DisableLogging(); // Create default transformation TransformationInfo ti = new TransformationInfo(); string classFormDefinition = DataClassInfoProvider.GetDataClassInfo(ClassName).ClassFormDefinition; ti.TransformationName = ValidationHelper.GetCodeName(GetString("TransformationName.Default")); ti.TransformationFullName = ClassName + "." + ti.TransformationName; ti.TransformationCode = TransformationInfoProvider.GenerateTransformationCode(classFormDefinition, TransformationTypeEnum.Ascx, ClassName); ti.TransformationType = TransformationTypeEnum.Ascx; ti.TransformationClassID = classId; // Set default transformation in DB TransformationInfoProvider.SetTransformation(ti); // Create preview transformation which has the same transformation code ti = ti.Clone(true); ti.TransformationName = ValidationHelper.GetCodeName(GetString("TransformationName.Preview")); ti.TransformationFullName = ClassName + "." + ti.TransformationName; // Set default transformation in DB TransformationInfoProvider.SetTransformation(ti); // Test if class is standard document type if (isDocument) { // Create RSS transformation ti = ti.Clone(true); ti.TransformationName = ValidationHelper.GetCodeName(GetString("TransformationName.RSS")); ti.TransformationFullName = ClassName + "." + ti.TransformationName; ti.TransformationCode = TransformationInfoProvider.GenerateTransformationCode(classFormDefinition, TransformationTypeEnum.Ascx, ClassName, DefaultTransformationTypeEnum.RSS); // Set RSS transformation in DB TransformationInfoProvider.SetTransformation(ti); // Create Atom transformation ti = ti.Clone(true); ti.TransformationName = ValidationHelper.GetCodeName(GetString("TransformationName.Atom")); ti.TransformationFullName = ClassName + "." + ti.TransformationName; ti.TransformationCode = TransformationInfoProvider.GenerateTransformationCode(classFormDefinition, TransformationTypeEnum.Ascx, ClassName, DefaultTransformationTypeEnum.Atom); // Set Atom transformation in DB TransformationInfoProvider.SetTransformation(ti); } } }
/// <summary> /// Processes the step 5 of the wizard /// </summary> private void ProcessStep6(WizardNavigationEventArgs e) { // Actions after next button click var dci = DataClassInfoProvider.GetDataClassInfo(ClassName); int classId = dci.ClassID; bool isCustomTable = dci.ClassIsCustomTable; bool licenseCheck = true; string selectedSite = ValidationHelper.GetString(usSites.Value, String.Empty); if (selectedSite == "0") { selectedSite = ""; } string[] sites = selectedSite.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string site in sites) { int siteId = ValidationHelper.GetInteger(site, 0); SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { if (isCustomTable) { if (!CustomTableItemProvider.LicenseVersionCheck(si.DomainName, ObjectActionEnum.Insert)) { pnlMessages6.Visible = true; pnlMessages6.ShowError(GetString("LicenseVersion.CustomTables")); e.Cancel = true; licenseCheck = false; } } if (licenseCheck) { ClassSiteInfoProvider.AddClassToSite(classId, siteId); // Clear custom tables count if (isCustomTable) { CustomTableItemProvider.ClearLicensesCount(); } } } } // If is moving to the new step if (licenseCheck) { // Create default transformations switch (Mode) { case NewClassWizardModeEnum.DocumentType: if (!SomeStepsOmitted) { CreateDefaultTransformations(classId, true); } else { // Apply on if new document type was created lblTableCreated.Visible = false; } break; case NewClassWizardModeEnum.CustomTable: CreateDefaultTransformations(classId, false); break; } } else { PrepareStep5(); return; } // Save default search settings if (((Mode == NewClassWizardModeEnum.DocumentType) && (dci.ClassIsCoupledClass)) || (Mode == NewClassWizardModeEnum.CustomTable)) { dci.ClassSearchEnabled = true; dci.ClassSearchSettings = SearchHelper.GetDefaultSearchSettings(dci); SearchHelper.SetDefaultClassSearchColumns(dci); dci.Generalized.SetObject(); } DisablePreviousStepsViewStates(6); EnableNextStepViewState(6); PrepareStep7(); // Explicitly log the synchronization with all changes using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; SynchronizationHelper.LogObjectUpdate(dci); } }
/// <summary> /// Processes the step 4 of the wizard /// </summary> private void ProcessStep4(WizardNavigationEventArgs e) { // Actions after next button click var dci = DataClassInfoProvider.GetDataClassInfo(ClassName); dci.ClassNodeNameSource = lstFields.SelectedValue; // Update node name source in DB using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); } // Prepare next step (5) // Disable previous steps' viewstates DisablePreviousStepsViewStates(e.CurrentStepIndex); // Enable next step's viewstate EnableNextStepViewState(e.CurrentStepIndex); PrepareStep5(); }
/// <summary> /// Processes the step 3 of the wizard /// </summary> private void ProcessStep3(WizardNavigationEventArgs e) { // Actions after next button click var dci = DataClassInfoProvider.GetDataClassInfo(ClassName); // Ensure actual form info FormHelper.ClearFormInfos(true); // Get and load form definition var fi = FormHelper.GetFormInfo(dci.ClassName, false); if (fi.GetFields(true, true).Count() < 2) { e.Cancel = true; FieldEditor.ShowError(GetString("DocumentType_New_Step3.TableMustHaveCustomField")); } else { // Different behavior by mode switch (Mode) { case NewClassWizardModeEnum.DocumentType: { TableManager tm = new TableManager(null); // Create new view if doesn't exist string viewName = SqlHelper.GetViewName(dci.ClassTableName, null); // Create view for document types if (!tm.ViewExists(viewName)) { tm.CreateView(viewName, SqlGenerator.GetSqlQuery(ClassName, SqlOperationTypeEnum.SelectView, null)); } // If new document type is created prepare next step otherwise skip steps 4, 5 and 6 // Disable previous steps' viewstates DisablePreviousStepsViewStates(e.CurrentStepIndex); // Enable next step's viewstate EnableNextStepViewState(e.CurrentStepIndex); // Add implicit value to the list lstFields.Items.Add(new ListItem(GetString("DocumentType_New_Step4.ImplicitDocumentName"), "")); // Get all fields List<FormFieldInfo> ffiFields = fi.GetFields(true, true); if (ffiFields != null) { bool selected = false; // Add all text fields' names to the list except primary-key field foreach (FormFieldInfo ffi in ffiFields) { if (!ffi.PrimaryKey && !ffi.AllowEmpty && ((ffi.DataType == FieldDataType.Text) || (ffi.DataType == FieldDataType.LongText))) { lstFields.Items.Add(new ListItem(ffi.Name, ffi.Name)); // Select the first text field if (!selected) { string controlName = ValidationHelper.GetString(ffi.Settings["controlname"], null); // Preselect only textbox if (CMSString.Compare(controlName, Enum.GetName(typeof (FormFieldControlTypeEnum), FormFieldControlTypeEnum.TextBoxControl), StringComparison.InvariantCultureIgnoreCase) == 0) { lstFields.SelectedValue = ffi.Name; selected = true; } } } } } lblSelectField.Text = GetString("DocumentType_New_Step4.DocumentName"); wzdStep4.Title = GetString("DocumentType_New_Step4.Title"); ucHeader.Description = GetString("DocumentType_New_Step4.Description"); } break; case NewClassWizardModeEnum.Class: { // Update class in DB using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); } // Remember that some steps were omitted SomeStepsOmitted = true; // Prepare next step (7) - skip steps 4, 5 and 6 // Disable previous steps' viewstates DisablePreviousStepsViewStates(5); // Enable next step's viewstate EnableNextStepViewState(5); PrepareStep7(); // Go to the step 7 (indexed from 0) wzdNewDocType.ActiveStepIndex = 6; } break; case NewClassWizardModeEnum.CustomTable: { // Update class in DB using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); } // Remember that some steps were omitted, SomeStepsOmitted = true; // Prepare next step (6) - skip steps 4, 5 // Disable previous steps' viewstates DisablePreviousStepsViewStates(4); // Enable next step's viewstate EnableNextStepViewState(4); PrepareStep6(); // Go to the step 6 (indexed from 0) wzdNewDocType.ActiveStepIndex = 5; } break; } } }
/// <summary> /// Processes the step 2 of the wizard /// </summary> private void ProcessStep2(WizardNavigationEventArgs e) { var dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci != null) { var tm = new TableManager(null); using (var tr = new CMSTransactionScope()) { // New document type has custom attributes -> no wizard steps will be omitted if (radCustom.Checked) { // Actions after next button click bool fromExisting = (Mode == NewClassWizardModeEnum.CustomTable) && radExistingTable.Checked; string tableName = (fromExisting) ? drpExistingTables.SelectedValue : txtTableName.Text.Trim(); // Validate checkboxes first string tableNameError = new Validator() .NotEmpty(tableName, GetString("DocumentType_New.ErrorEmptyTableName")) .IsIdentifier(tableName, GetString("class.ErrorIdentifier")) .Result; string primaryKeyNameEmpty = new Validator().NotEmpty(txtPKName.Text.Trim(), GetString("DocumentType_New.ErrorEmptyPKName")).Result; bool columnExists = DocumentHelper.ColumnExistsInDocumentView(txtPKName.Text.Trim()); // Textboxes are filled correctly if ((tableNameError == "") && (primaryKeyNameEmpty == "") && (!columnExists)) { try { bool tableExists = tm.TableExists(tableName); if (fromExisting) { // Custom table from existing table - validate the table name if (!tableExists) { e.Cancel = true; // Table with the same name already exists ShowError(GetString("customtable.newwizard.tablenotexists")); } // Check primary key List<string> primaryKeys = tm.GetPrimaryKeyColumns(tableName); if ((primaryKeys == null) || (primaryKeys.Count != 1)) { e.Cancel = true; ShowError(GetString("customtable.newwizard.musthaveprimarykey")); } else if (!IsIdentityColumn(tableName, primaryKeys.First())) { e.Cancel = true; ShowError(GetString("customtable.newwizard.mustbeidentitypk")); } } else if (tableExists) { // Check if given table name already exists in database e.Cancel = true; ShowError(GetString("sysdev.class_edit_gen.tablenameunique")); } else if (Mode == NewClassWizardModeEnum.Class) { // Standard class in development mode tm.CreateTable(tableName, txtPKName.Text.Trim(), !chbIsMNTable.Checked); } else { tm.CreateTable(tableName, txtPKName.Text.Trim()); } } catch (Exception ex) { // No movement to the next step e.Cancel = true; // Show error message if something caused unhandled exception ShowError(ex.Message); } if ((pnlMessages2.ErrorLabel.Text == "") && !e.Cancel) { // Change table owner try { string owner = ""; // Get site related DB object owner setting when creating new wizard and global otherwise switch (Mode) { case NewClassWizardModeEnum.DocumentType: case NewClassWizardModeEnum.Class: case NewClassWizardModeEnum.CustomTable: owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName); break; } if ((owner != "") && (owner.ToLowerCSafe() != "dbo")) { tm.ChangeDBObjectOwner(tableName, owner); tableName = SqlHelper.GetSafeOwner(owner) + "." + tableName; } } catch { // Suppress error } FormInfo fi; if (fromExisting) { // From existing DB table dci.ClassXmlSchema = tm.GetXmlSchema(tableName); string formDef = FormHelper.GetXmlFormDefinitionFromXmlSchema(dci.ClassXmlSchema, false); fi = new FormInfo(formDef); } else { // Create empty form info fi = CreateEmptyFormInfo(); dci.ClassXmlSchema = tm.GetXmlSchema(tableName); } dci.ClassTableName = tableName; dci.ClassFormDefinition = fi.GetXmlDefinition(); dci.ClassIsCoupledClass = true; dci.ClassInheritsFromClassID = ValidationHelper.GetInteger(selInherits.Value, 0); // Update class in DB using (var context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); UpdateInheritedClass(dci); } if (Mode == NewClassWizardModeEnum.CustomTable) { try { InitCustomTable(dci, fi, tm); } catch (Exception ex) { // Do not move to next step. e.Cancel = true; EventLogProvider.LogException("NewClassWizard", "CREATE", ex); string message = null; if (ex is MissingSQLTypeException) { var missingSqlType = (MissingSQLTypeException) ex; message = String.Format(GetString("customtable.sqltypenotsupported"), missingSqlType.UnsupportedType, missingSqlType.ColumnName, missingSqlType.RecommendedType); } else { message = ex.Message; } pnlMessages2.ShowError(message); pnlMessages2.Visible = true; } } if (!e.Cancel) { // Remember that no steps were omitted SomeStepsOmitted = false; // Prepare next step (3) // Disable previous steps' viewstates DisablePreviousStepsViewStates(e.CurrentStepIndex); // Enable next step's viewstate EnableNextStepViewState(e.CurrentStepIndex); // Set field editor class name FieldEditor.ClassName = ClassName; // Fill field editor in the next step FieldEditor.Reload(null); wzdStep3.Title = GetString("general.fields"); // Set new step header based on the development mode setting switch (Mode) { case NewClassWizardModeEnum.DocumentType: ucHeader.Description = GetString("DocumentType_New_Step3.Description"); break; case NewClassWizardModeEnum.Class: ucHeader.Description = GetString("sysdev.class_new_Step3.Description"); break; case NewClassWizardModeEnum.CustomTable: ucHeader.Description = GetString("customtable.newwizzard.Step3Description"); break; } } } } // Some textboxes are not filled correctly else { // Prepare current step (2) // No movement to the next step e.Cancel = true; // Show errors if (!String.IsNullOrEmpty(tableNameError)) { lblTableNameError.Text = tableNameError; lblTableNameError.Visible = true; } else { lblTableNameError.Visible = false; } if (!String.IsNullOrEmpty(primaryKeyNameEmpty)) { lblPKNameError.Visible = true; lblPKNameError.Text = primaryKeyNameEmpty; } else { lblPKNameError.Visible = false; } if (columnExists) { pnlMessages2.ShowError(GetString("DocumentType_New_Step2.ErrorColumnExists")); pnlMessages2.Visible = true; } wzdStep2.Title = GetString("DocumentType_New_Step2.Title"); // Reset the header switch (Mode) { case NewClassWizardModeEnum.DocumentType: ucHeader.Description = GetString("DocumentType_New_Step2.Description"); break; case NewClassWizardModeEnum.Class: ucHeader.Description = GetString("sysdev.class_new_Step2.Description"); break; case NewClassWizardModeEnum.CustomTable: ucHeader.Description = GetString("customtable.newwizzard.Step2Description"); break; } } } // New document type is only the container -> some wizard steps will be omitted else { // Actions after next button click dci.ClassIsCoupledClass = false; // Update class in DB using (CMSActionContext context = new CMSActionContext()) { // Disable logging into event log context.LogEvents = false; DataClassInfoProvider.SetDataClassInfo(dci); } // Remember that some steps were omitted SomeStepsOmitted = true; IsContainer = true; // Prepare next step (5) - skip steps 3 and 4 // Disable previous steps' viewstates DisablePreviousStepsViewStates(3); // Enable next step's viewstate EnableNextStepViewState(3); PrepareStep5(); // Go to the step 5 (indexed from 0) wzdNewDocType.ActiveStepIndex = 4; } // Create new icon if the wizard is used to create new document type if (Mode == NewClassWizardModeEnum.DocumentType) { // Setup icon class for new doc. type string iconClass = (SomeStepsOmitted) ? DEFAULT_CLASS_ICON : DEFAULT_COUPLED_CLASS_ICON; dci.SetValue("ClassIconClass", iconClass); } if (!e.Cancel) { tr.Commit(); } } } }
/// <summary> /// Refreshes the security parameters in macros for all the objects of the specified object types. /// Signs all the macros with the current user if the old salt is not specified. /// </summary> /// <param name="objectTypes">Object types</param> /// <param name="oldSalt">Old salt </param> /// <param name="newSalt">New salt</param> private void RefreshSecurityParams(IEnumerable<string> objectTypes, string oldSalt, string newSalt) { var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked; var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked; processedObjects.Clear(); using (CMSActionContext context = new CMSActionContext()) { context.LogEvents = false; context.LogSynchronization = false; foreach (var objectType in objectTypes) { var objectTypeResourceKey = TypeHelper.GetObjectTypeResourceKey(objectType); var niceObjectType = GetString(objectTypeResourceKey); if (niceObjectType == objectTypeResourceKey) { if (objectType.StartsWithCSafe("bizformitem.bizform.", true)) { DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(objectType.Substring("bizformitem.".Length)); if (dci != null) { niceObjectType = "on-line form " + dci.ClassDisplayName; } } else { niceObjectType = objectType; } } LogContext.AppendLine(string.Format(GetString("macros.refreshsecurityparams.processing"), niceObjectType)); try { var infos = new InfoObjectCollection(objectType); foreach (var info in infos) { try { bool refreshed = false; if (oldSaltSpecified) { refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true); } else { if (chkRefreshAll.Checked && newSaltSpecified) { // Do not check integrity, but use new salt refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true, newSalt); } else { // Do not check integrity, sign everything with current user refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true); } } if (refreshed) { var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName)); processedObjects.Add(niceObjectType, objectName); } } catch (Exception ex) { string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.TypeInfo.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message; EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message); } } } catch (Exception e) { LogContext.AppendLine(e.Message); EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", e); } } } EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", GetProcessedObjectsForEventLog()); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (!BizFormInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.BizForms, ObjectActionEnum.Insert)) { ShowError(GetString("LicenseVersion.BizForm")); return; } DataClassInfo dci = null; BizFormInfo bizFormObj = null; string errorMessage = new Validator().NotEmpty(txtFormDisplayName.Text, rfvFormDisplayName.ErrorMessage). NotEmpty(txtFormName.Text, rfvFormName.ErrorMessage). NotEmpty(txtTableName.Text, rfvTableName.ErrorMessage). IsIdentifier(txtFormName.Text, GetString("bizform_edit.errorformnameinidentifierformat")). IsIdentifier(txtTableName.Text, GetString("BizForm_Edit.ErrorFormTableNameInIdentifierFormat")).Result; if (String.IsNullOrEmpty(errorMessage)) { using (var tr = new CMSTransactionScope()) { // Prepare the values string formDisplayName = txtFormDisplayName.Text.Trim(); bizFormObj = new BizFormInfo(); bizFormObj.FormDisplayName = formDisplayName; bizFormObj.FormName = txtFormName.Text.Trim(); bizFormObj.FormSiteID = SiteContext.CurrentSiteID; bizFormObj.FormEmailAttachUploadedDocs = true; bizFormObj.FormItems = 0; bizFormObj.FormClearAfterSave = false; bizFormObj.FormLogActivity = true; // Ensure the code name bizFormObj.Generalized.EnsureCodeName(); // Table name is combined from prefix ('BizForm_<sitename>_') and custom table name string safeFormName = ValidationHelper.GetIdentifier(bizFormObj.FormName); bizFormObj.FormName = safeFormName; string className = bizFormNamespace + "." + safeFormName; // Generate the table name string tableName = txtTableName.Text.Trim(); if (String.IsNullOrEmpty(tableName) || (tableName == InfoHelper.CODENAME_AUTOMATIC)) { tableName = safeFormName; } tableName = FormTablePrefix + tableName; TableManager tm = new TableManager(null); // TableName wont be longer than 60 letters and will be unique if (tableName.Length > 60) { int x = 1; while (tm.TableExists(tableName.Substring(0, 59) + x.ToString())) { x++; } tableName = tableName.Substring(0, 59) + x.ToString(); } // If first letter of safeFormName is digit, add "PK" to beginning string primaryKey = BizFormInfoProvider.GenerateFormPrimaryKeyName(bizFormObj.FormName); try { // Create new table in DB tm.CreateTable(tableName, primaryKey); } catch (Exception ex) { errorMessage = ex.Message; // Table with the same name already exists ShowError(string.Format(GetString("bizform_edit.errortableexists"), tableName)); return; } // Change table owner try { string owner = SqlHelper.GetDBSchema(SiteContext.CurrentSiteName); if ((!String.IsNullOrEmpty(owner)) && (owner.ToLowerCSafe() != "dbo")) { tm.ChangeDBObjectOwner(tableName, owner); tableName = owner + "." + tableName; } } catch (Exception ex) { EventLogProvider.LogException("BIZFORM_NEW", "E", ex); } // Convert default datetime to string in english format string defaultDateTime = DateTime.Now.ToString(CultureHelper.EnglishCulture.DateTimeFormat); try { // Add FormInserted and FormUpdated columns to the table tm.AddTableColumn(tableName, "FormInserted", "datetime", false, defaultDateTime); tm.AddTableColumn(tableName, "FormUpdated", "datetime", false, defaultDateTime); } catch (Exception ex) { errorMessage = ex.Message; // Column wasn't added successfully ShowError(errorMessage); return; } // Create the BizForm class dci = BizFormInfoProvider.CreateBizFormDataClass(className, formDisplayName, tableName, primaryKey); try { // Create new bizform dataclass using (CMSActionContext context = new CMSActionContext()) { // Disable logging of tasks context.DisableLogging(); // Set default search settings dci.ClassSearchEnabled = true; DataClassInfoProvider.SetDataClassInfo(dci); // Create default search settings dci.ClassSearchSettings = SearchHelper.GetDefaultSearchSettings(dci); dci.ClassSearchCreationDateColumn = "FormInserted"; DataClassInfoProvider.SetDataClassInfo(dci); } } catch (Exception ex) { errorMessage = ex.Message; // Class with the same name already exists ShowError(errorMessage); return; } // Create new bizform bizFormObj.FormClassID = dci.ClassID; try { // Create new bizform BizFormInfoProvider.SetBizFormInfo(bizFormObj); } catch (Exception ex) { errorMessage = ex.Message; ShowError(errorMessage); return; } tr.Commit(); if (String.IsNullOrEmpty(errorMessage)) { // Redirect to Form builder tab string url = UIContextHelper.GetElementUrl("CMS.Form", "Forms.Properties", false, bizFormObj.FormID); url = URLHelper.AddParameterToUrl(url, "tabname", "Forms.FormBuldier"); URLHelper.Redirect(url); } } } else { ShowError(errorMessage); } }
/// <summary> /// Clones the given report (including attachment files). /// </summary> /// <param name="reportId">Report id</param> protected void Clone(int reportId) { // Check 'Modify' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.reporting", "Modify")) { RedirectToAccessDenied("cms.reporting", "Modify"); } // Try to get report info ReportInfo oldri = ReportInfoProvider.GetReportInfo(reportId); if (oldri == null) { return; } DataSet graph_ds = ReportGraphInfoProvider.GetGraphs(reportId); DataSet table_ds = ReportTableInfoProvider.GetTables(reportId); DataSet value_ds = ReportValueInfoProvider.GetValues(reportId); // Duplicate report info object ReportInfo ri = new ReportInfo(oldri, false); ri.ReportID = 0; ri.ReportGUID = Guid.NewGuid(); // Duplicate report info string reportName = ri.ReportName; string oldReportName = ri.ReportName; string reportDispName = ri.ReportDisplayName; while (ReportInfoProvider.GetReportInfo(reportName) != null) { reportName = Increment(reportName, "_", "", 100); reportDispName = Increment(reportDispName, "(", ")", 450); } ri.ReportName = reportName; ri.ReportDisplayName = reportDispName; // Used to eliminate version from create object task using (CMSActionContext context = new CMSActionContext()) { context.CreateVersion = false; ReportInfoProvider.SetReportInfo(ri); } string name; // Duplicate graph data if (!DataHelper.DataSourceIsEmpty(graph_ds)) { foreach (DataRow dr in graph_ds.Tables[0].Rows) { // Duplicate the graph ReportGraphInfo rgi = new ReportGraphInfo(dr); rgi.GraphID = 0; rgi.GraphGUID = Guid.NewGuid(); rgi.GraphReportID = ri.ReportID; name = rgi.GraphName; // Replace layout based on HTML or regular graph type ri.ReportLayout = ReplaceMacro(ri.ReportLayout, rgi.GraphIsHtml ? REP_HTMLGRAPH_MACRO : REP_GRAPH_MACRO, rgi.GraphName, name, oldReportName, reportName); rgi.GraphName = name; ReportGraphInfoProvider.SetReportGraphInfo(rgi); } } // Duplicate table data if (!DataHelper.DataSourceIsEmpty(table_ds)) { foreach (DataRow dr in table_ds.Tables[0].Rows) { // Duplicate the table ReportTableInfo rti = new ReportTableInfo(dr); rti.TableID = 0; rti.TableGUID = Guid.NewGuid(); rti.TableReportID = ri.ReportID; name = rti.TableName; ri.ReportLayout = ReplaceMacro(ri.ReportLayout, REP_TABLE_MACRO, rti.TableName, name, oldReportName, reportName); rti.TableName = name; ReportTableInfoProvider.SetReportTableInfo(rti); } } // Duplicate value data if (!DataHelper.DataSourceIsEmpty(value_ds)) { foreach (DataRow dr in value_ds.Tables[0].Rows) { // Duplicate the value ReportValueInfo rvi = new ReportValueInfo(dr); rvi.ValueID = 0; rvi.ValueGUID = Guid.NewGuid(); rvi.ValueReportID = ri.ReportID; name = rvi.ValueName; ri.ReportLayout = ReplaceMacro(ri.ReportLayout, REP_VALUE_MACRO, rvi.ValueName, name, oldReportName, reportName); rvi.ValueName = name; ReportValueInfoProvider.SetReportValueInfo(rvi); } } List<Guid> convTable = new List<Guid>(); try { MetaFileInfoProvider.CopyMetaFiles(reportId, ri.ReportID, ReportingObjectType.REPORT, MetaFileInfoProvider.OBJECT_CATEGORY_LAYOUT, convTable); } catch (Exception e) { lblError.Visible = true; lblError.Text = e.Message; ReportInfoProvider.DeleteReportInfo(ri); return; } for (int i = 0; i < convTable.Count; i += 2) { Guid oldGuid = convTable[i]; Guid newGuid = convTable[i + 1]; ri.ReportLayout = ri.ReportLayout.Replace(oldGuid.ToString(), newGuid.ToString()); } ReportInfoProvider.SetReportInfo(ri); // Refresh tree ltlScript.Text += "<script type=\"text/javascript\">"; ltlScript.Text += @"if (parent.frames['reportcategorytree']) { parent.frames['reportcategorytree'].location.href = 'ReportCategory_tree.aspx?reportid=" + ri.ReportID + @"'; } if (parent.parent.frames['reportcategorytree']) { parent.parent.frames['reportcategorytree'].location.href = 'ReportCategory_tree.aspx?reportid=" + ri.ReportID + @"'; } this.location.href = 'Report_Edit.aspx?reportId=" + Convert.ToString(ri.ReportID) + @"&saved=1&categoryID=" + categoryId + @"' </script>"; }
/// <summary> /// Called when source field selected index changed. /// </summary> protected void documentSource_OnSourceFieldChanged(object sender, EventArgs e) { if (mMode == FieldEditorModeEnum.ClassFormDefinition) { string errorMessage = null; DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci != null) { // Set document name source field dci.ClassNodeNameSource = string.IsNullOrEmpty(documentSource.SourceFieldValue) ? "" : documentSource.SourceFieldValue; // Set document alias source field dci.ClassNodeAliasSource = string.IsNullOrEmpty(documentSource.SourceAliasFieldValue) ? "" : documentSource.SourceAliasFieldValue; try { using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } DataClassInfoProvider.SetDataClassInfo(dci); } ShowConfirmation(GetString("TemplateDesigner.SourceFieldSaved")); WebControl control = sender as WebControl; if (control != null && (control.ID == "drpSourceAliasField")) { ShowConfirmation(GetString("TemplateDesigner.SourceAliasFieldSaved")); } } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); errorMessage = ex.Message; } } else { errorMessage = GetString("FieldEditor.ClassNotFound"); } if (!string.IsNullOrEmpty(errorMessage)) { ShowError("[ FieldEditor.drpSourceField_SelectedIndexChanged() ]: " + errorMessage); } } }
/// <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> /// 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); // Find whether user name is valid if (result == String.Empty) { if (!ucUserName.IsValid()) { result = ucUserName.ValidationError; } } String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); if (result == String.Empty) { // Finds whether required fields are not empty result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } // 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.IsGlobalAdministrator; bool editor = ui.IsEditorInternal; // Email format validation string email = txtEmail.Text.Trim(); if ((email != string.Empty) && (!ValidationHelper.IsEmail(email))) { ShowError(GetString("Administration-User_New.WrongEmailFormat")); return; } bool oldGlobal = ui.IsGlobalAdministrator; bool oldEditor = ui.IsEditorInternal; // Define domain variable string domains = null; // Get all user sites DataTable ds = UserInfoProvider.GetUserSites(userId, null, null, 0, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Rows) { domains += ValidationHelper.GetString(dr["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.IsGlobalAdministrator && ((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) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, ObjectActionEnum.Insert, editor)) { ShowError(GetString("License.MaxItemsReachedEditor")); return; } } // Check whether email is unique if it is required 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; ui.Enabled = CheckBoxEnabled.Checked; ui.UserIsHidden = chkIsHidden.Checked; ui.IsExternal = chkIsExternal.Checked; ui.UserIsDomain = chkIsDomain.Checked; ui.SetValue("UserPassword", password); ui.UserID = userId; ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim(); ui.UserMFRequired = chkIsMFRequired.Checked; // Global admin can set anything if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) // 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.SetPrivilegeLevel(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; } // Update the user UserInfoProvider.SetUserInfo(ui); // 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 (RequestHelper.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> /// Saves the form definition and refreshes the form. /// </summary> protected void SaveFormDefinition() { // Update form definition FormDefinition = fi.GetXmlDefinition(); switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Save xml string to CMS_WebPart table WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); if (wpi != null) { wpi.WebPartProperties = FormDefinition; WebPartInfoProvider.SetWebPartInfo(wpi); } else { lblError.Visible = true; lblError.Text = "[FieldEditor.UpdateFormDefinition]: " + GetString("FieldEditor.WebpartNotFound"); } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Save xml string to CMS_Class table DataClassInfo dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { dci.ClassFormDefinition = FormDefinition; using (CMSActionContext context = new CMSActionContext()) { // Do not log synchronization for BizForm if (mMode == FieldEditorModeEnum.BizFormDefinition) { context.DisableLogging(); } // Save the class data DataClassInfoProvider.SetDataClass(dci); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); } } else { lblError.Visible = true; lblError.Text = "[FieldEditor.UpdateFormDefinition]: " + GetString("FieldEditor.ClassNotFound"); } break; } // Reload attibute list LoadAttributesList(lstAttributes.SelectedValue); }
/// <summary> /// Check URL query string for authentication parameter and authenticate user. /// </summary> private static void CheckAuthenticationGUID() { // Check for authentication token if (QueryHelper.Contains("authenticationGuid") && SettingsKeyProvider.GetBoolValue("CMSAutomaticallySignInUser")) { UserInfo ui = null; if (!CMSContext.IsAuthenticated()) { // Get authentication token Guid authGuid = QueryHelper.GetGuid("authenticationGuid", Guid.Empty); if (authGuid != Guid.Empty) { // Get users with found authentication token DataSet ds = UserInfoProvider.GetFullUsers("UserAuthenticationGUID = '" + authGuid + "'", null, 1, null); if (!DataHelper.DataSourceIsEmpty(ds)) { // Authenticate user ui = new UserInfo(ds.Tables[0].Rows[0]); CMSContext.AuthenticateUser(ui.UserName, false, false); } } } else { // Get current user info ui = CMSContext.CurrentUser; } // Remove authentication GUID if ((ui != null) && (ui.UserAuthenticationGUID != Guid.Empty)) { using (CMSActionContext context = new CMSActionContext()) { context.DisableAll(); context.CreateSearchTask = false; ui.UserAuthenticationGUID = Guid.Empty; ui.Generalized.SetObject(); } } // Redirect to URL without authentication token URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, "authenticationGuid")); } }
/// <summary> /// Refreshes the security parameters in macros for all the objects of the specified object types. /// Signs all the macros with the current user if the old salt is not specified. /// </summary> /// <param name="objectTypes">Object types</param> /// <param name="oldSalt">Old salt </param> /// <param name="newSalt">New salt</param> private void RefreshSecurityParams(IEnumerable<string> objectTypes, string oldSalt, string newSalt) { var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked; var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked; processedObjects.Clear(); using (var context = new CMSActionContext()) { context.LogEvents = false; context.LogSynchronization = false; foreach (var objectType in objectTypes) { var niceObjectType = GetNiceObjectTypeName(objectType); AddLog(string.Format(GetString("macros.refreshsecurityparams.processing"), niceObjectType)); try { var infos = new InfoObjectCollection(objectType); // Skip object types derived from general data class object type to avoid duplicities if ((infos.TypeInfo.OriginalObjectType == DataClassInfo.OBJECT_TYPE) && (infos.TypeInfo.ObjectType != DataClassInfo.OBJECT_TYPE)) { continue; } foreach (var info in infos) { try { bool refreshed; if (oldSaltSpecified) { refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true); } else { if (chkRefreshAll.Checked && newSaltSpecified) { // Do not check integrity, but use new salt refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true, newSalt); } else { // Do not check integrity, sign everything with current user refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true); } } if (refreshed) { var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName)); processedObjects.Add(niceObjectType, objectName); } } catch (Exception ex) { string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.TypeInfo.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message; EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message); } } } catch (Exception e) { AddLog(e.Message); EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", e); } } } EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", GetProcessedObjectsForEventLog()); }
/// <summary> /// Actions handler. /// </summary> protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e) { switch (e.CommandName) { case "save": Save(); break; case "checkout": // Ensure version before check-out using (CMSActionContext context = new CMSActionContext()) { context.AllowAsyncActions = false; if (!Save()) { return; } } try { SiteManagerFunctions.CheckOutStylesheet(cssStylesheetId); } catch (Exception ex) { ShowInformation(string.Concat(GetString("CssStylesheet.ErrorCheckout"), ": ", ex.Message)); return; } string url = URLHelper.AddParameterToUrl(URLHelper.Url.AbsoluteUri, "saved", "1"); // In case of dialog mode use javascript redirection to ensure script are rendered correctly if (DialogMode) { ScriptHelper.RegisterStartupScript(this, typeof(string), "PageRedirect", "window.location.replace('" + url + "');", true); } else { URLHelper.Redirect(url); } break; case "checkin": try { SiteManagerFunctions.CheckInStylesheet(cssStylesheetId); } catch (Exception ex) { ShowError(string.Concat(GetString("CssStylesheet.ErrorCheckin"), ": ", ex.Message)); return; } URLHelper.Redirect(URLHelper.Url.AbsoluteUri); break; case "undocheckout": try { SiteManagerFunctions.UndoCheckOutStylesheet(cssStylesheetId); } catch (Exception ex) { ShowError(string.Concat(GetString("CssStylesheet.ErrorUndoCheckout"), ": ", ex.Message)); return; } URLHelper.Redirect(URLHelper.Url.AbsoluteUri); break; } }