/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(ArrayList elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.CategoryCaption + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.Caption + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return(sb.ToString()); }
/// <summary> /// Control ID validation. /// </summary> private void formElem_OnItemValidation(object sender, ref string errorMessage) { Control ctrl = (Control)sender; if (ctrl.ID.ToLowerCSafe() == "webpartcontrolid") { FormEngineUserControl ctrlTextbox = (FormEngineUserControl)ctrl; string newId = ValidationHelper.GetString(ctrlTextbox.Value, null); // Validate unique ID WebPartInstance existingPart = pti.GetWebPart(newId); if ((existingPart != null) && ((webPartInstance == null) || (existingPart.InstanceGUID != webPartInstance.InstanceGUID))) { // Error - duplicity IDs errorMessage = GetString("WebPartProperties.ErrorUniqueID"); } else { string uniqueId = WebPartZoneInstance.GetUniqueWebPartId(newId, pi.TemplateInstance); if (!uniqueId.EqualsCSafe(newId, true)) { // Check if there is already a widget with the same id in the page existingPart = pi.TemplateInstance.GetWebPart(newId); if ((existingPart != null) && existingPart.IsWidget) { // Error - the ID collide with another widget which is already in the page errorMessage = ResHelper.GetString("WidgetProperties.ErrorUniqueID"); } } } } }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> /// <param name="webPart">Source web part</param> private static void LoadDataRowFromWebPart(DataRow dr, WebPartInstance webPart) { foreach (DataColumn column in dr.Table.Columns) { try { object value = webPart.GetValue(column.ColumnName); // Convert value into default format if (value != null) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.MinValue, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } catch { } } }
/// <summary> /// PreInit event handler /// </summary> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); // Disable check save changes script DocumentManager.RegisterSaveChangesScript = false; // Check UI elements for web part zone var currentUser = MembershipContext.AuthenticatedUser; if (!currentUser.IsAuthorizedPerUIElement("CMS.Design", new string[] { "Design", "Design.WebPartZoneProperties" }, SiteContext.CurrentSiteName)) { RedirectToUIElementAccessDenied("CMS.Design", "Design;Design.WebPartZoneProperties"); } // When displaying an existing variant of a web part, get the variant mode for its original web part if ((variantId > 0) || (zoneVariantId > 0)) { PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId); if ((pti != null) && ((pti.TemplateInstance != null))) { // Get the original webpart and retrieve its variant mode WebPartInstance webpartInstance = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, 0); if (webpartInstance != null) { variantMode = webpartInstance.VariantMode; } } } }
/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(IEnumerable <IDataDefinitionItem> elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.GetPropertyValue(FormCategoryPropertyEnum.Caption, MacroContext.CurrentResolver) + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver) + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return(sb.ToString()); }
protected override void OnInit(EventArgs e) { base.OnInit(e); // Check permissions for web part properties UI CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!currentUser.IsAuthorizedPerUIElement("CMS.Content", "WebPartProperties.Code")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "WebPartProperties.Code"); } if (webpartId != "") { // Get page info pi = GetPageInfo(aliasPath, templateId); if (pi == null) { this.Visible = false; return; } pti = pi.PageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { // Get web part instance webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); if (webPart != null) { txtCode.Text = ValidationHelper.GetString(webPart.GetValue("WebPartCode"), ""); } } } }
/// <summary> /// Initializes menu. /// </summary> protected void InitalizeMenu() { if (webpartId != "") { // get pageinfo PageInfo pi = GetPageInfo(aliasPath, templateId); if (pi == null) { this.Visible = false; return; } PageTemplateInfo pti = pi.PageTemplateInfo; if (pti != null) { WebPartInfo wi = null; // Get web part WebPartInstance webPart = pti.GetWebPart(instanceGuid, webpartId); if (webPart != null) { wi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (ValidationHelper.GetString(webPart.GetValue("WebPartCode"), "").Trim() != "") { showCodeTab = true; } if (webPart.Bindings.Count > 0) { showBindingTab = true; } } else { wi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); } if (wi != null) { // Generate documentation link Literal ltr = new Literal(); PageTitle.RightPlaceHolder.Controls.Add(ltr); string docScript = "NewWindow('" + ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/WebPartDocumentationPage.aspx") + "?webpartid=" + ScriptHelper.GetString(wi.WebPartName, false) + "', 'WebPartPropertiesDocumentation', 800, 800); return false;"; ltr.Text = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td>"; ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\"><img src=\"" + ResolveUrl(GetImageUrl("CMSModules/CMS_PortalEngine/Documentation.png")) + "\" style=\"border-width: 0px;\"></a>"; ltr.Text += "</td>"; ltr.Text += "<td>"; ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\">" + GetString("WebPartPropertie.DocumentationLink") + "</a>"; ltr.Text += "</td></tr></table>"; PageTitle.TitleText = GetString("WebpartProperties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WebPartDisplayName)) + ")"; } } } CurrentUserInfo currentUser = CMSContext.CurrentUser; tabsElem.UrlTarget = "webpartpropertiescontent"; }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> /// <param name="webPart">Source web part</param> /// <param name="formInfo">Web part form info</param> private void LoadDataRowFromWebPart(DataRow dr, WebPartInstance webPart, FormInfo formInfo) { if (webPart != null) { foreach (DataColumn column in dr.Table.Columns) { try { var safeColumnName = column.ColumnName.ToLowerInvariant(); bool load = true; // switch by xml version switch (xmlVersion) { case 1: load = webPart.Properties.Contains(safeColumnName) || string.Equals("webpartcontrolid", safeColumnName, StringComparison.OrdinalIgnoreCase); break; // Version 0 default: // Load default value for Boolean type in old XML version if ((column.DataType == typeof(bool)) && !webPart.Properties.Contains(safeColumnName)) { FormFieldInfo ffi = formInfo.GetFormField(column.ColumnName); if (ffi != null) { webPart.SetValue(column.ColumnName, ffi.GetPropertyValue(FormFieldPropertyEnum.DefaultValue)); } } break; } if (load) { var value = webPart.GetValue(column.ColumnName); // Convert value into default format if ((value != null) && (ValidationHelper.GetString(value, String.Empty) != String.Empty)) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.MinValue, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } } catch (Exception ex) { EventLogProvider.LogException("WebPartProperties", "LOADDATAROW", ex); } } } }
protected override void OnPreInit(EventArgs e) { WebPartInstance webPart = null; // Check permissions for web part properties UI if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Design", "WebPartProperties.Layout")) { RedirectToUIElementAccessDenied("CMS.Design", "WebPartProperties.Layout"); } if (webpartId != "") { // Get pageinfo PageInfo pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi == null) { return; } // Get page template PageTemplateInfo pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } if (webPart != null) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); layoutCodeName = QueryHelper.GetString("layoutcodename", String.Empty); if (String.IsNullOrEmpty(layoutCodeName)) { // Get the current layout name layoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } if (wpi != null) { wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, layoutCodeName); if (wpli != null) { if ((layoutCodeName != "|default|") && (layoutCodeName != "|new|") && !QueryHelper.GetBoolean("tabmode", false)) { string url = UIContextHelper.GetElementUrl("CMS.Design", "Design.WebPartProperties.LayoutEdit", false, wpli.WebPartLayoutID); url = URLHelper.AppendQuery(url, RequestContext.CurrentQueryString); url = URLHelper.AddParameterToUrl(url, "tabmode", "1"); URLHelper.Redirect(url); } } } } base.OnPreInit(e); }
protected void Page_Load(object sender, EventArgs e) { // Check permissions for web part properties UI var currentUser = MembershipContext.AuthenticatedUser; if (!currentUser.IsAuthorizedPerUIElement("CMS.Design", "WebPartProperties.Layout")) { RedirectToUIElementAccessDenied("CMS.Design", "WebPartProperties.Layout"); } WebPartInstance webPart = null; if (webpartId != "") { // Get pageinfo PageInfo pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi != null) { // Get page template PageTemplateInfo pti = pi.UsedPageTemplateInfo; // Get web part if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } } // If the web part is not found, do not continue if (webPart != null) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wpi != null) { // Get the current layout name if (String.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } // Load the web part information if (LayoutCodeName != "") { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); SetEditedObject(wpli, null); } } } // Set page tabs InitTabs("webpartlayoutcontent"); SetTab(0, GetString("general.general"), "webpartproperties_layout.aspx" + RequestContext.CurrentQueryString, null); }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> /// <param name="webPart">Source web part</param> private void LoadDataRowFromWebPart(DataRow dr, WebPartInstance webPart, FormInfo fi) { foreach (DataColumn column in dr.Table.Columns) { try { bool load = true; // switch by xml version switch (xmlVersion) { case 1: load = webPart.Properties.Contains(column.ColumnName.ToLowerCSafe()) || column.ColumnName.EqualsCSafe("webpartcontrolid", true); break; // Version 0 default: // Load default value for Boolean type in old XML version if ((column.DataType == typeof(bool)) && !webPart.Properties.Contains(column.ColumnName.ToLowerCSafe())) { FormFieldInfo ffi = fi.GetFormField(column.ColumnName); if (ffi != null) { webPart.SetValue(column.ColumnName, ffi.DefaultValue); } } break; } if (load) { object value = webPart.GetValue(column.ColumnName); // Convert value into default format if ((value != null) && (ValidationHelper.GetString(value, String.Empty) != String.Empty)) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.MinValue, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } } catch { } } }
protected override void OnPreInit(EventArgs e) { WebPartInstance webPart = null; // Check permissions for web part properties UI if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Content", "WebPartProperties.Layout")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "WebPartProperties.Layout"); } if (webpartId != "") { // Get pageinfo PageInfo pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi == null) { return; } // Get page template PageTemplateInfo pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); } } if (webPart != null) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); layoutCodeName = QueryHelper.GetString("layoutcodename", String.Empty); if (String.IsNullOrEmpty(layoutCodeName)) { // Get the current layout name layoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } if (wpi != null) { wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, layoutCodeName); if (wpli != null) { if ((layoutCodeName != "|default|") && (layoutCodeName != "|new|")) { SetEditedObject(wpli, "WebPartProperties_layout_frameset_frameset.aspx"); } } } } base.OnPreInit(e); }
/// <summary> /// Initializes menu. /// </summary> protected void InitializeMenu() { if (webpartId != string.Empty) { // get pageinfo PageInfo pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi == null) { Visible = false; return; } PageTemplateInfo pti = pi.UsedPageTemplateInfo; if (pti != null) { // Get web part WebPartInstance webPart = pti.TemplateInstance.GetWebPart(instanceGuid, webpartId); // New webpart is loaded via WebPartID if ((webPart == null) && !isNew) { // Clone templateInstance to avoid caching of the temporary template instance loaded with CP/MVT variants var tempTemplateInstance = pti.TemplateInstance.Clone(); tempTemplateInstance.LoadVariants(false, VariantModeEnum.None); webPart = tempTemplateInstance.GetWebPart(instanceGuid, -1, 0); } WebPartInfo wi = (webPart != null) ? WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType) : WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wi != null) { type = (WebPartTypeEnum)wi.WebPartType; // Generate documentation link Literal ltr = new Literal(); string docScript = "NewWindow('" + ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/WebPartDocumentationPage.aspx") + "?webpartid=" + ScriptHelper.GetString(wi.WebPartName, false) + "', 'WebPartPropertiesDocumentation', 800, 800); return false;"; string tooltip = GetString("help.tooltip"); ltr.Text += String.Format ("<div class=\"action-button\"><a onclick=\"{0}\" href=\"#\"><span class=\"sr-only\">{1}</span><i class=\"icon-modal-question cms-icon-80\" title=\"{1}\" aria-hidden=\"true\"></i></a></div>", docScript, tooltip); pageTitle.RightPlaceHolder.Controls.Add(ltr); pageTitle.TitleText = GetString("WebpartProperties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WebPartDisplayName)) + ")"; } } } tabsElem.UrlTarget = "webpartpropertiescontent"; }
/// <summary> /// Control ID validation. /// </summary> private void formElem_OnItemValidation(object sender, ref string errorMessage) { Control ctrl = (Control)sender; if (string.Equals("webpartcontrolid", ctrl.ID, StringComparison.OrdinalIgnoreCase)) { FormEngineUserControl ctrlTextbox = (FormEngineUserControl)ctrl; // New web part control id string newControlId = ValidationHelper.GetString(ctrlTextbox.Value, null); // Load the web part variants if not loaded yet if ((PortalContext.MVTVariantsEnabled && !templateInstance.MVTVariantsLoaded) || (PortalContext.ContentPersonalizationEnabled && !templateInstance.ContentPersonalizationVariantsLoaded)) { templateInstance.LoadVariants(false, VariantModeEnum.None); } // Check control ID validity if (!ValidationHelper.IsIdentifier(newControlId)) { errorMessage = GetString("webpartproperties.controlid.allowedcharacters"); } // New or changed web part control id bool checkIdUniqueness = IsNewWebPart || IsNewVariant || (webPartInstance == null) || (webPartInstance.ControlID != newControlId); // Try to find a web part with the same web part control id amongst all the web parts and their variants if (checkIdUniqueness && (templateInstance.GetWebPart(newControlId, true) != null)) { // Error - duplicity IDs errorMessage = GetString("WebPartProperties.ErrorUniqueID"); } else { string uniqueId = GetUniqueWebPartId(newControlId); if (!string.Equals(uniqueId, newControlId, StringComparison.InvariantCultureIgnoreCase)) { // Check if there is already a widget with the same id in the page WebPartInstance foundWidget = pi.TemplateInstance.GetWebPart(newControlId); if ((foundWidget != null) && foundWidget.IsWidget) { // Error - the ID collide with another widget which is already in the page errorMessage = ResHelper.GetString("WidgetProperties.ErrorUniqueID"); } } } } }
/// <summary> /// Adds widget. /// </summary> private void AddWidget() { int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Add web part to the currently selected zone under currently selected page if ((widgetID > 0) && !String.IsNullOrEmpty(ZoneId)) { if (wi != null) { // Ensure layout zone flag if (QueryHelper.GetBoolean("layoutzone", false)) { WebPartZoneInstance zone = pti.EnsureZone(ZoneId); zone.LayoutZone = true; zone.WidgetZoneType = zoneType; // Ensure the layout zone flag in the original page template instance WebPartZoneInstance zoneInstance = templateInstance.GetZone(ZoneId); if (zoneInstance != null) { zoneInstance.LayoutZone = true; zone.WidgetZoneType = zoneType; } } // Add the widget WebPartInstance newWidget = templateInstance.AddWidget(ZoneId, widgetID); if (newWidget != null) { // Prepare the form info to get the default properties FormInfo fi = new FormInfo(wi.WidgetProperties); DataRow dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); newWidget.LoadProperties(dr); // Add webpart to user's last recently used CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName); widgetInstance = newWidget; } } } }
/// <summary> /// Control ID validation. /// </summary> protected void formElem_OnItemValidation(object sender, ref string errorMessage) { Control ctrl = (Control)sender; if (String.Compare(ctrl.ID, "widgetcontrolid", StringComparison.InvariantCultureIgnoreCase) == 0) { TextBox ctrlTextbox = (TextBox)ctrl; string newId = ctrlTextbox.Text; // Validate unique ID WebPartInstance existingPart = pti.GetWebPart(newId); if ((existingPart != null) && (existingPart != widgetInstance) && (existingPart.InstanceGUID != widgetInstance.InstanceGUID)) { // Error - duplicit IDs errorMessage = GetString("Widgets.Properties.ErrorUniqueID"); } } }
/// <summary> /// PreInit event handler /// </summary> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); // When displaying an existing variant of a web part, get the variant mode for its original web part if ((variantId > 0) || (zoneVariantId > 0)) { PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId); if ((pti != null) && ((pti.TemplateInstance != null))) { // Get the original webpart and retrieve its variant mode WebPartInstance webpartInstance = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, 0); if (webpartInstance != null) { variantMode = webpartInstance.VariantMode; } } } }
/// <summary> /// Control ID validation. /// </summary> protected void formElem_OnItemValidation(object sender, ref string errorMessage) { Control ctrl = (Control)sender; if (CMSString.Compare(ctrl.ID, "widgetcontrolid", true) == 0) { TextBox ctrlTextbox = (TextBox)ctrl; string newId = ctrlTextbox.Text; var pti = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo); // Validate unique ID WebPartInstance existingPart = pti.GetWebPart(newId); if ((existingPart != null) && (existingPart != mWidgetInstance) && (existingPart.InstanceGUID != mWidgetInstance.InstanceGUID)) { // Error - duplicated IDs errorMessage = GetString("Widgets.Properties.ErrorUniqueID"); } } }
/// <summary> /// OnInit /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); // Check permissions for web part properties UI CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!currentUser.IsAuthorizedPerUIElement("CMS.Content", "WebPartProperties.Code")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "WebPartProperties.Code"); } if (webpartId != "") { // Get page info pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi == null) { Visible = false; return; } pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { // Get web part instance webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); if (webPart != null) { txtCode.Text = ValidationHelper.GetString(webPart.GetValue("WebPartCode"), ""); } EditedObject = webPart; } } }
protected void Page_Load(object sender, EventArgs e) { // Check permissions for web part properties UI CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!currentUser.IsAuthorizedPerUIElement("CMS.Content", "WebPartProperties.Layout")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "WebPartProperties.Layout"); } // Check saved bool saved = false; if (QueryHelper.GetBoolean("saved", false)) { saved = true; lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); } // Init GUI mCheckOut = GetString("WebPartLayout.CheckOut"); mCheckIn = GetString("WebPartLayout.CheckIn"); mUndoCheckOut = GetString("WebPartLayout.DiscardCheckOut"); mSave = GetString("General.Save"); this.imgSave.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/Save.png"); this.imgCheckIn.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/checkin.png"); this.imgCheckOut.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/checkout.png"); this.imgUndoCheckOut.ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/undocheckout.png"); this.btnUndoCheckOut.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("General.ConfirmUndoCheckOut")) + ");"; if (webpartId != "") { // Get pageinfo pi = GetPageInfo(aliasPath, templateId); if (pi == null) { this.lblInfo.Text = GetString("WebPartProperties.WebPartNotFound"); this.pnlFormArea.Visible = false; return; } // Get page template pti = pi.PageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); } } // If the web part is not found, do not continue if (webPart == null) { this.lblInfo.Text = GetString("WebPartProperties.WebPartNotFound"); this.pnlFormArea.Visible = false; return; } else { if (String.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wpi != null) { // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { pnlMenu.Visible = false; pnlCheckOutInfo.Visible = false; if (LayoutCodeName != "") { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); if (wpli != null) { if ((LayoutCodeName != "|default|") && (LayoutCodeName != "|new|")) { SetEditedObject(wpli, "WebPartProperties_layout_frameset_frameset.aspx"); } pnlMenu.Visible = true; pnlCheckOutInfo.Visible = true; // Read-only code text area etaCode.ReadOnly = false; etaCSS.ReadOnly = false; // Set checkout panel SetCheckPanel(wpli); etaCode.Text = wpli.WebPartLayoutCode; etaCSS.Text = wpli.WebPartLayoutCSS; loaded = true; } } if (!loaded) { string fileName = webPartInfo.WebPartFileName; if (webPartInfo.WebPartParentID > 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(webPartInfo.WebPartParentID); if (pwpi != null) { fileName = pwpi.WebPartFileName; } } if (!fileName.StartsWith("~")) { fileName = "~/CMSWebparts/" + fileName; } // Check if filename exist if (!FileHelper.FileExists(fileName)) { lblError.Text = GetString("WebPartProperties.FileNotExist"); lblError.Visible = true; plcContent.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS etaCSS.Text = wpi.WebPartCSS; } } } } btnOnOK.Click += new EventHandler(btnOnOK_Click); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + this.hidRefresh.ClientID + "').value = refreshpage; } \n" + "function OnApplyButton(refreshpage) { SetRefresh(refreshpage); " + Page.ClientScript.GetPostBackEventReference(lnkSave, "") + "} \n" + "function OnOKButton(refreshpage) { SetRefresh(refreshpage); " + Page.ClientScript.GetPostBackEventReference(btnOnOK, "") + "} \n" )); if (saved && (LayoutCodeName == "|new|")) { // Refresh menu string query = URLHelper.Url.Query; query = URLHelper.AddParameterToUrl(query, "layoutcodename", webPart.GetValue("WebPartLayout").ToString()); query = URLHelper.AddParameterToUrl(query, "reload", "true"); string scriptText = ScriptHelper.GetScript(@"parent.frames['webpartpropertiesmenu'].location = 'webpartproperties_layout_menu.aspx" + query + "';"); ScriptHelper.RegisterStartupScript(this, typeof(string), "ReloadAfterNewLayout", scriptText); } if (!RequestHelper.IsPostBack()) { InitLayoutForm(); } this.plcCssLink.Visible = String.IsNullOrEmpty(etaCSS.Text.Trim()); this.lnkStyles.Visible = !String.IsNullOrEmpty(LayoutCodeName) && (LayoutCodeName != "|default|"); }
protected override void OnInit(EventArgs e) { // Do not check changes DocumentManager.RegisterSaveChangesScript = false; EditForm.OnBeforeSave += EditForm_OnBeforeSave; etaCode.Editor.Language = LanguageEnum.HTML; etaCSS.Editor.Language = LanguageEnum.CSS; wpli = CMSContext.EditedObject as WebPartLayoutInfo; layoutID = QueryHelper.GetInteger("layoutid", 0); isSiteManager = ((CMSContext.CurrentUser.IsGlobalAdministrator && layoutID != 0) || QueryHelper.GetBoolean("sitemanager", false)); isNew = (LayoutCodeName == "|new|"); isDefault = (LayoutCodeName == "|default|") || (!isSiteManager && string.IsNullOrEmpty(LayoutCodeName)); if ((wpli == null) && isSiteManager) { isNew = true; } if (wpli == null) { editMenuElem.ObjectManager.ObjectType = PredefinedObjectType.WEBPARTLAYOUT; } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "PreviewHierarchyPerformAction", ScriptHelper.GetScript("function actionPerformed(action) { if (action == 'saveandclose') { document.getElementById('" + hdnClose.ClientID + "').value = '1'; } " + editMenuElem.ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null) + "; }")); RegisterResizeHeaders(); currentUser = CMSContext.CurrentUser; // Get webpart instance (if edited in CMSDesk) if ((webpartId != "") && !isSiteManager) { // Get pageinfo pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("WebPartProperties.WebPartNotFound"), null, false); } // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); } } // If the web part is not found, try webpart ID if (webPart == null) { // Site manager wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wpi == null) { ShowError(GetString("WebPartProperties.WebPartNotFound"), null, null); startWithFullScreen = false; return; } } else { // CMS desk wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (string.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (wpi != null) { if (CMSObjectHelper.UseCheckinCheckout && (!isNew || isSiteManager)) { pnlFormArea.CssClass = "PreviewDefaultContentLarge"; } else { pnlFormArea.CssClass = "PreviewDefaultContent"; } // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { if (wpli != null) { editMenuElem.MenuPanel.Visible = true; // Read-only code text area etaCode.Editor.ReadOnly = false; loaded = true; } if (!loaded) { string fileName = webPartInfo.WebPartFileName; if (webPartInfo.WebPartParentID > 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(webPartInfo.WebPartParentID); if (pwpi != null) { fileName = pwpi.WebPartFileName; } } if (!fileName.StartsWithCSafe("~")) { fileName = "~/CMSWebparts/" + fileName; } // Check if filename exist if (!FileHelper.FileExists(fileName)) { ShowError(GetString("WebPartProperties.FileNotExist"), null, null); plcContent.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS etaCSS.Text = wpi.WebPartCSS; startWithFullScreen = false; } } } } if ((wpli == null) && isSiteManager) { pnlFormArea.CssClass += " NewPreviewContent"; var breadcrumbs = new string[2, 3]; breadcrumbs[0, 0] = GetString("WebParts.Layout"); breadcrumbs[0, 1] = ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Layout.aspx?webpartid=" + QueryHelper.GetInteger("webpartid", 0)); breadcrumbs[1, 0] = GetString("webparts_layout_newlayout"); editMenuElem.PageTitleBreadcrumbs = breadcrumbs; } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + hidRefresh.ClientID + @"').value = refreshpage; } function OnApplyButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('save');refreshPreview(); } function OnOKButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('saveandclose'); } ")); InitLayoutForm(); plcCssLink.Visible = string.IsNullOrEmpty(etaCSS.Text.Trim()); base.OnInit(e); }
/// <summary> /// Loads the web part form. /// </summary> protected void LoadForm() { // Load settings if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Indicates whether the new variant should be chosen when closing this dialog selectNewVariant = IsNewVariant; // Try to find the web part variant in the database and set its VariantID if (IsNewVariant) { Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable; if (varProperties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(varProperties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateID, variantName, true); // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } if (!String.IsNullOrEmpty(WebPartID)) { // Get the page info pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode); if (pi != null) { // Get template pti = pi.UsedPageTemplateInfo; // Get template instance templateInstance = pti.TemplateInstance; if (!IsNewWebPart) { // Standard zone webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebPartID); // If the web part not found, try to find it among the MVT/CP variants if (webPartInstance == null) { // MVT/CP variant templateInstance.LoadVariants(false, VariantModeEnum.None); webPartInstance = templateInstance.GetWebPart(InstanceGUID, -1, 0); // Set the VariantMode according to the selected web part/zone variant if ((webPartInstance != null) && (webPartInstance.ParentZone != null)) { VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode; } else { VariantMode = VariantModeEnum.None; } } else { // Ensure that the ZoneVariantID is not set when the web part was found in a regular zone ZoneVariantID = 0; } if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { webPartInstance = webPartInstance.FindVariant(VariantID); } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } if (webPartInstance == null) { UIContext.EditedObject = null; return; } } mainWebPartInstance = webPartInstance; // Keep xml version if (webPartInstance != null) { xmlVersion = webPartInstance.XMLVersion; // If data source ID set, edit the data source if (NestedWebPartID > 0) { webPartInstance = webPartInstance.NestedWebParts[NestedWebPartKey] ?? new WebPartInstance() { InstanceGUID = Guid.NewGuid() }; } } // Get the form info FormInfo fi = GetWebPartFormInfo(); // Get the form definition if (fi != null) { fi.ContextResolver.Settings.RelatedObject = templateInstance; form.AllowMacroEditing = ((WebPartTypeEnum)wpi.WebPartType != WebPartTypeEnum.Wireframe); // Get data row with required columns DataRow dr = fi.GetDataRow(); if (IsNewWebPart || (xmlVersion > 0)) { fi.LoadDefaultValues(dr); } // Load values from existing web part LoadDataRowFromWebPart(dr, webPartInstance, fi); // Set a unique WebPartControlID for the new variant if (IsNewVariant || IsNewWebPart) { // Set control ID string webPartControlId = ValidationHelper.GetCodeName(wpi.WebPartDisplayName); dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(webPartControlId, templateInstance); } // Init the form InitForm(form, dr, fi); AddExportLink(); } else { UIContext.EditedObject = null; } } } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); CurrentMaster.DisplaySiteSelectorPanel = true; if (webpartId != "") { // Get pageinfo pi = GetPageInfo(aliasPath, templateId, cultureCode); if (pi == null) { RedirectToInformation(GetString("WebPartProperties.WebPartNotFound")); return; } // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } bool hide = false; // If the web part is not found, do not continue // Redirect to information is in main window, just hide selector if (webPart == null) { hide = true; } else { webPartInfo = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (webPartInfo == null) { hide = true; } // Get the current layout name if (String.IsNullOrEmpty(LayoutCodeName)) { mLayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (hide) { pnlContent.Visible = false; return; } // Strings lblLayouts.Text = GetString("WebPartPropertise.LayoutList"); // Add default drop down items selectLayout.ShowDefaultItem = true; // Add new item if (CurrentUser.IsAuthorizedPerResource("CMS.Design", "EditCode")) { selectLayout.ShowNewItem = true; } // Set where condition selectLayout.WhereCondition = "WebPartLayoutWebPartID =" + webPartInfo.WebPartID; // Hide loader, it appears on wrong position because of small frame selectLayout.UniSelector.OnBeforeClientChanged = "if (window.Loader) { window.Loader.hide(); }"; // Load layouts if (!RequestHelper.IsPostBack() && (LayoutCodeName != "")) { selectLayout.Value = LayoutCodeName; } // Reload the content page if required if (!RequestHelper.IsPostBack() || QueryHelper.GetBoolean("reload", false)) { LoadContentPage(); } }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return false; } } // Save the data if ((CurrentPageInfo != null) && (templateInstance != null) && SaveForm(formCustom)) { ViewModeEnum viewMode = PortalContext.ViewMode; // Check manage permission for non-livesite version if (!viewMode.IsLiveSite() && (viewMode != ViewModeEnum.DashboardWidgets)) { if (CurrentUser.IsAuthorizedPerDocument(CurrentPageInfo.NodeID, CurrentPageInfo.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { DisplayError("general.modifynotallowed"); return false; } // Check design permissions if (PortalContext.IsDesignMode(viewMode, false) && !PortalContext.CurrentUserIsDesigner) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = templateInstance.ParentPageTemplate; if (PortalContext.IsDesignMode(viewMode) && SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName)); return false; } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = ZoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance widgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, templateInstance, null); } // Ensure handling of the currently edited object (if not exists -> redirect) UIContext.EditedObject = widgetInstance; widgetInstance.XMLVersion = 1; if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); // Check whether the editor widgets have been already customized if (CurrentPageInfo.DocumentTemplateInstance.WebPartZones.Count == 0) { // There are no customized editor widgets yet => copy the default editor widgets from the page template under the document (to enable customization) // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } bool isLayoutWidget = ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, templateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(wi.WidgetName); if (!string.IsNullOrEmpty(controlId)) { widgetInstance.ControlID = controlId; } else { DisplayError("Unable to generate unique widget id."); return false; } } // Allow set dashboard in design mode if ((ZoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { viewMode = ViewModeEnum.Design; PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes if ((viewMode.IsEdit(true) || viewMode.IsEditLive()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { if (DocumentManager.AllowSave) { // Store the editor widgets in the temporary interlayer PortalContext.SaveEditorWidgets(CurrentPageInfo.DocumentID, templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); } } else { // Save the changes CMSPortalManager.SaveTemplateChanges(CurrentPageInfo, templateInstance, ZoneType, viewMode, tree); } } else if ((viewMode.IsEdit()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; VariantHelper.SaveWebPartVariantChanges(widgetInstance, VariantID, 0, VariantMode, properties); // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Display info message ShowChangesSaved(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); } return true; } return false; }
/// <summary> /// Initializes menu. /// </summary> protected void InitalizeMenu() { string zoneId = QueryHelper.GetString("zoneid", string.Empty); string culture = QueryHelper.GetString("culture", CMSContext.PreferredCultureCode); Guid instanceGuid = QueryHelper.GetGuid("instanceguid", Guid.Empty); bool isNewWidget = QueryHelper.GetBoolean("isnew", false); WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.None; if (!String.IsNullOrEmpty(widgetId) || !String.IsNullOrEmpty(widgetName)) { WidgetInfo wi = null; // get pageinfo PageInfo pi = null; try { pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi == null) { Visible = false; return; } // Get template instance PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (templateInstance != null) { // Get zone type WebPartZoneInstance zoneInstance = templateInstance.GetZone(zoneId); if (zoneInstance != null) { zoneType = zoneInstance.WidgetZoneType; } // Get web part WebPartInstance widget = templateInstance.GetWebPart(instanceGuid, widgetId); if ((widget != null) && widget.IsWidget) { // WebPartType = codename, get widget by codename wi = WidgetInfoProvider.GetWidgetInfo(widget.WebPartType); } } // New widget if (isNewWidget) { int id = ValidationHelper.GetInteger(widgetId, 0); if (id > 0) { wi = WidgetInfoProvider.GetWidgetInfo(id); } else if (!String.IsNullOrEmpty(widgetName)) { wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } } // Get widget info from name if not found yet if ((wi == null) && (!String.IsNullOrEmpty(widgetName))) { wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } if (wi != null) { PageTitle.TitleText = GetString("Widgets.Properties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WidgetDisplayName)) + ")"; } // If no zonetype defined or not inline dont show documentation string documentationUrl = String.Empty; switch (zoneType) { case WidgetZoneTypeEnum.Dashboard: case WidgetZoneTypeEnum.Editor: case WidgetZoneTypeEnum.Group: case WidgetZoneTypeEnum.User: documentationUrl = ResolveUrl("~/CMSModules/Widgets/LiveDialogs/WidgetDocumentation.aspx"); break; // If no zone set dont create documentation link default: if (isInline) { documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx"); } else { return; } break; } // Generate documentation link Literal ltr = new Literal(); PageTitle.RightPlaceHolder.Controls.Add(ltr); // Ensure correct parameters in documentation url documentationUrl += URLHelper.GetQuery(URLHelper.CurrentURL); if (!String.IsNullOrEmpty(widgetName)) { documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetname", widgetName); } if (!String.IsNullOrEmpty(widgetId)) { documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetid", widgetId); } string docScript = "NewWindow('" + documentationUrl + "', 'WebPartPropertiesDocumentation', 800, 800); return false;"; ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\"><img src=\"" + ResolveUrl(GetImageUrl("General/HelpLargeDark.png")) + "\" style=\"border-width: 0px;\"></a>"; } }
/// <summary> /// Initializes menu. /// </summary> protected void InitalizeMenu() { if (!String.IsNullOrEmpty(widgetId) || !String.IsNullOrEmpty(widgetName)) { WidgetInfo wi = null; // Get page info PageInfo pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { Visible = false; return; } // Get template instance PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (templateInstance != null) { // Get zone type WebPartZoneInstance zoneInstance = templateInstance.GetZone(zoneId); if (zoneInstance != null) { zoneType = zoneInstance.WidgetZoneType; } if (!isNewWidget) { // Get web part WebPartInstance widget = templateInstance.GetWebPart(instanceGuid, widgetId); if ((widget != null) && widget.IsWidget) { // WebPartType = codename, get widget by codename wi = WidgetInfoProvider.GetWidgetInfo(widget.WebPartType); // Set the variant mode (MVT/Content personalization) variantMode = widget.VariantMode; } } } // New widget if (isNewWidget) { int id = ValidationHelper.GetInteger(widgetId, 0); if (id > 0) { wi = WidgetInfoProvider.GetWidgetInfo(id); } else if (!String.IsNullOrEmpty(widgetName)) { wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } } // Get widget info from name if not found yet if ((wi == null) && (!String.IsNullOrEmpty(widgetName))) { wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } if (wi != null) { pageTitle.TitleText = GetString("Widgets.Properties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WidgetDisplayName)) + ")"; } // Use live or non live dialogs string documentationUrl = String.Empty; // If no zone type defined or not inline => do not show documentation switch (zoneType) { case WidgetZoneTypeEnum.Dashboard: case WidgetZoneTypeEnum.Editor: case WidgetZoneTypeEnum.Group: case WidgetZoneTypeEnum.User: documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx"); break; // If no zone set => do not create documentation link default: if (inline) { documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx"); } else { return; } break; } // Generate documentation link Literal ltr = new Literal(); pageTitle.RightPlaceHolder.Controls.Add(ltr); // Ensure correct parameters in documentation URL documentationUrl += URLHelper.GetQuery(RequestContext.CurrentURL); if (wi != null) { documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetid", wi.WidgetID.ToString()); } string docScript = "NewWindow('" + ScriptHelper.GetString(documentationUrl, encapsulate: false) + "', 'WebPartPropertiesDocumentation', 800, 800); return false;"; string tooltip = GetString("help.tooltip"); ltr.Text += String.Format ("<div class=\"action-button\"><a onclick=\"{0}\" href=\"#\"><span class=\"sr-only\">{1}</span><i class=\"icon-modal-question cms-icon-80\" title=\"{1}\" aria-hidden=\"true\"></i></a></div>", HTMLHelper.EncodeForHtmlAttribute(docScript), tooltip); } }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Public user is not allowed for widgets if (!AuthenticationHelper.IsAuthenticated()) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } var viewMode = ViewModeCode.FromString(QueryHelper.GetString("viewmode", String.Empty)); var hash = QueryHelper.GetString("hash", String.Empty); LiveSiteWidgetsParameters dialogparameters = new LiveSiteWidgetsParameters(aliasPath, viewMode) { ZoneId = zoneId, ZoneType = zoneType, InstanceGuid = instanceGuid, TemplateId = templateId, IsInlineWidget = inline }; if (!dialogparameters.ValidateHash(hash)) { return; } // Set page title Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title"); if ((widgetId != string.Empty) && (aliasPath != string.Empty)) { // Get page info var siteName = SiteContext.CurrentSiteName; PageInfo pi = PageInfoProvider.GetPageInfo(siteName, aliasPath, LocalizationContext.PreferredCultureCode, null, SiteInfoProvider.CombineWithDefaultCulture(siteName)); if (pi == null) { return; } // Get template instance PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); // Get widget from instance WidgetInfo wi = null; if (!isNewWidget) { // Get the instance of widget WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetId); if (widgetInstance == null) { return; } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0)); } if (wi != null) { WebPartZoneInstance zone = templateInstance.GetZone(zoneId); if (zone != null) { var currentUser = MembershipContext.AuthenticatedUser; bool checkSecurity = true; // Check security // It is group zone type but widget is not allowed in group if (zone.WidgetZoneType == WidgetZoneTypeEnum.Group) { // Should always be, only group widget are allowed in group zone if (wi.WidgetForGroup) { if (!currentUser.IsGroupAdministrator(pi.NodeGroupID)) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } // All ok, don't check classic security checkSecurity = false; } } if (checkSecurity && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } } } } // If all ok, set up frames rowsFrameset.Attributes.Add("rows", string.Format("{0}, *", TitleOnlyHeight)); frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + RequestContext.CurrentQueryString); if (inline && !isNewWidget) { frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm")); } else { frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + RequestContext.CurrentQueryString); } }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return false; } } // Save the data if ((pi != null) && (templateInstance != null) && SaveForm(formCustom)) { // Check manage permission for non-livesite version if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.DashboardWidgets)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(pi.NodeID, pi.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { return false; } } PageTemplateInfo pti = templateInstance.ParentPageTemplate; if ((CMSContext.ViewMode == ViewModeEnum.Design) && CMSObjectHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.ObjectType, pti.DisplayName, userName)); return false; } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = zoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance widgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, templateInstance, null); } widgetInstance.XMLVersion = 1; if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); if (pi.DocumentTemplateInstance.WebPartZones.Count == 0) { // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } // Get basicform's datarow and update widget SaveFormToWidget(formCustom, templateInstance); if (IsNewVariant) { // Ensures unique id for new widget variant widgetInstance.ControlID = WebPartZoneInstance.GetUniqueWebPartId(wi.WidgetName, zone.ParentTemplateInstance); } // Allow set dashboard in design mode if ((zoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, templateInstance, zoneType, CMSContext.ViewMode, tree); } else if ((CMSContext.ViewMode == ViewModeEnum.Edit) && (zoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; PortalHelper.SaveWebPartVariantChanges(widgetInstance, VariantID, 0, VariantMode, properties); // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); } return true; } return false; }
protected void Page_Load(object sender, EventArgs e) { string aliasPath = QueryHelper.GetString("aliaspath", ""); string webpartId = QueryHelper.GetString("webpartid", ""); string zoneId = QueryHelper.GetString("zoneid", ""); Guid webpartGuid = QueryHelper.GetGuid("webpartguid", Guid.Empty); int templateId = QueryHelper.GetInteger("templateId", 0); PageTemplateInfo pti = null; if (templateId > 0) { pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId); } if (pti == null) { var siteName = SiteContext.CurrentSiteName; PageInfo pi = PageInfoProvider.GetPageInfo(siteName, aliasPath, LocalizationContext.PreferredCultureCode, null, SiteInfoProvider.CombineWithDefaultCulture(siteName)); if (pi != null) { pti = pi.UsedPageTemplateInfo; } } if (pti != null) { // Get web part WebPartInstance webPart = pti.TemplateInstance.GetWebPart(webpartGuid, webpartId); if (webPart != null) { StringBuilder sb = new StringBuilder(); Hashtable properties = webPart.Properties; // Get the webpart object WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wi != null) { // Add the header sb.Append("Webpart properties (" + wi.WebPartDisplayName + ")" + Environment.NewLine + Environment.NewLine); sb.Append("Alias path: " + aliasPath + Environment.NewLine); sb.Append("Zone ID: " + zoneId + Environment.NewLine + Environment.NewLine); string wpProperties = "<default></default>"; // Get the form info object and load it with the data if (wi.WebPartParentID > 0) { // Load parent properties WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (wpi != null) { wpProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WebPartProperties); } } else { wpProperties = wi.WebPartProperties; } FormInfo fi = new FormInfo(wpProperties); // General properties of webparts string beforeFormDefinition = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wi.WebPartType, PropertiesPosition.Before); string afterFormDefinition = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wi.WebPartType, PropertiesPosition.After); // General properties before custom if (!String.IsNullOrEmpty(beforeFormDefinition)) { // Load before definition fi = new FormInfo(FormHelper.MergeFormDefinitions(beforeFormDefinition, wpProperties, true)); // Add Default category for first before items sb.Append(Environment.NewLine + "Default" + Environment.NewLine + Environment.NewLine + Environment.NewLine); } // General properties after custom if (!String.IsNullOrEmpty(afterFormDefinition)) { // Load after definition fi = new FormInfo(FormHelper.MergeFormDefinitions(fi.GetXmlDefinition(), afterFormDefinition, true)); } // Generate all properties sb.Append(GetProperties(fi.GetFormElements(true, false), webPart)); // Send the text file to the user to download UTF8Encoding enc = new UTF8Encoding(); byte[] file = enc.GetBytes(sb.ToString()); Response.AddHeader("Content-disposition", "attachment; filename=webpartproperties_" + HTTPHelper.GetDispositionFilename(webPart.ControlID) + ".txt"); Response.ContentType = "text/plain"; Response.BinaryWrite(file); RequestHelper.EndResponse(); } } } }
/// <summary> /// Saves webpart properties. /// </summary> public bool Save() { // Check MVT/CP security if (VariantID > 0) { // Check OnlineMarketing permissions. if (!CheckPermissions("Manage")) { lblError.Visible = true; lblError.Text = GetString("general.modifynotallowed"); return false; } } // Save the data if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form)) { // Add web part if new if (IsNewWebPart) { AddWebPart(); } WebPartInstance originalWebPartInstance = webPartInstance; if (IsNewVariant) { webPartInstance = webPartInstance.Clone(); webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLower()); } // Get basicform's datarow and update webpart SaveFormToWebPart(form); bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant; if (!isWebPartVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, pti, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree); } else { // Save the variant properties if ((webPartInstance != null) && (webPartInstance.ParentZone != null) && (!webPartInstance.ParentZone.HasVariants) // Save only if the parent zone does not have any variants && (webPartInstance.ParentZone.ParentTemplateInstance != null) && (webPartInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate != null)) { string variantName = string.Empty; string variantDisplayName = string.Empty; string variantDisplayCondition = string.Empty; string variantDescription = string.Empty; bool variantEnabled = true; string zoneId = webPartInstance.ParentZone.ZoneID; int templateId = webPartInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate.PageTemplateId; Guid instanceGuid = Guid.Empty; XmlDocument doc = new XmlDocument(); XmlNode xmlWebParts = null; if (ZoneVariantID > 0) { // This webpart is in a zone variant therefore save the whole variant webparts xmlWebParts = webPartInstance.ParentZone.GetXmlNode(doc); if (VariantMode == VariantModeEnum.MVT) { // MVT variant ModuleCommands.OnlineMarketingSaveMVTVariantWebParts(ZoneVariantID, xmlWebParts); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { // Content personalization variant ModuleCommands.OnlineMarketingSaveContentPersonalizationVariantWebParts(ZoneVariantID, xmlWebParts); } } else { // web part/widget variant xmlWebParts = webPartInstance.GetXmlNode(doc); instanceGuid = InstanceGUID; Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { variantName = ValidationHelper.GetString(properties["codename"], string.Empty); variantDisplayName = ValidationHelper.GetString(properties["displayname"], string.Empty); variantDescription = ValidationHelper.GetString(properties["description"], string.Empty); variantEnabled = ValidationHelper.GetBoolean(properties["enabled"], true); if (VariantMode == VariantModeEnum.ContentPersonalization) { variantDisplayCondition = ValidationHelper.GetString(properties["condition"], string.Empty); } } // Save the web part variant properties if (VariantMode == VariantModeEnum.MVT) { // MVT variant ModuleCommands.OnlineMarketingSaveMVTVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, zoneId, webPartInstance.InstanceGUID, templateId, 0, xmlWebParts); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { // Content personalization variant ModuleCommands.OnlineMarketingSaveContentPersonalizationVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, variantDisplayCondition, zoneId, webPartInstance.InstanceGUID, templateId, 0, xmlWebParts); } // The variants are cached -> Reload if (originalWebPartInstance != null) { originalWebPartInstance.LoadVariants(true, VariantMode); } } } } // Reload the form (because of macro values set only by JS) form.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLower()); } return true; } return false; }
/// <summary> /// Handles form's after data load event. /// </summary> protected void EditForm_OnAfterDataLoad(object sender, EventArgs e) { etaCode.Language = LanguageEnum.HTML; cssLayoutEditor.Editor.Language = LanguageEnum.CSS; cssLayoutEditor.Editor.ShowBookmarks = true; // Do not check changes DocumentManager.RegisterSaveChangesScript = false; EditForm.OnBeforeSave += EditForm_OnBeforeSave; etaCode.Language = LanguageEnum.HTML; wpli = UIContext.EditedObject as WebPartLayoutInfo; layoutID = QueryHelper.GetInteger("layoutid", 0); isSiteManager = ((MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && layoutID != 0) || QueryHelper.GetBoolean("sitemanager", false)); isNew = (LayoutCodeName == "|new|"); isDefault = (LayoutCodeName == "|default|") || (!isSiteManager && string.IsNullOrEmpty(LayoutCodeName)); if ((wpli == null) || (wpli.WebPartLayoutID <= 0)) { isNew |= isSiteManager; editMenuElem.ObjectManager.ObjectType = WebPartLayoutInfo.OBJECT_TYPE; } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "PreviewHierarchyPerformAction", ScriptHelper.GetScript("function actionPerformed(action) { if (action == 'saveandclose') { document.getElementById('" + hdnClose.ClientID + "').value = '1'; } " + editMenuElem.ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null) + "; }")); currentUser = MembershipContext.AuthenticatedUser; // Get web part instance (if edited in administration) if ((webpartId != "") && !isSiteManager) { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("WebPartProperties.WebPartNotFound"), persistent: false); } else { // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } } // If the web part is not found, try web part ID if (webPart == null) { wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wpi == null) { ShowError(GetString("WebPartProperties.WebPartNotFound")); return; } } else { // CMS desk wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (string.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (wpi != null) { // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { if (wpli != null) { editMenuElem.MenuPanel.Visible = true; // Read-only code text area etaCode.Editor.ReadOnly = false; loaded = true; } if (!loaded) { string fileName = WebPartInfoProvider.GetFullPhysicalPath(webPartInfo); // Check if filename exist if (!FileHelper.FileExists(fileName)) { ShowError(GetString("WebPartProperties.FileNotExist")); pnlContent.Visible = false; editMenuElem.ObjectEditMenu.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS cssLayoutEditor.Text = wpi.WebPartCSS; } } } } if (((wpli == null) || (wpli.WebPartLayoutID <= 0)) && isSiteManager) { editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("WebParts.Layout"), RedirectUrl = String.Format("{0}&parentobjectid={1}&displaytitle={2}", UIContextHelper.GetElementUrl("CMS.Design", "WebPart.Layout"), QueryHelper.GetInteger("webpartid", 0), false) }); editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("webparts_layout_newlayout"), }); } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + hidRefresh.ClientID + @"').value = refreshpage; } function OnApplyButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('save');refreshPreview(); } function OnOKButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('saveandclose'); } ")); InitLayoutForm(); }
/// <summary> /// Loads the widget form. /// </summary> private void LoadForm() { // Setup basic form on live site formCustom.AllowMacroEditing = false; formCustom.IsLiveSite = IsLiveSite; // Load settings if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the widget variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false); // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } EnsureDashboard(); if (!String.IsNullOrEmpty(WidgetId) && !IsInline) { if (CurrentPageInfo == null) { ShowError(GetString("Widgets.Properties.aliasnotfound")); pnlFormArea.Visible = false; return; } // Get template instance mTemplateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo); if (!IsNewWidget) { // Get the instance of widget mWidgetInstance = mTemplateInstance.GetWebPart(InstanceGUID, WidgetId); if (mWidgetInstance == null) { ShowError(GetString("Widgets.Properties.WidgetNotFound")); pnlFormArea.Visible = false; return; } if ((VariantID > 0) && (mWidgetInstance != null) && (mWidgetInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { mWidgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId); mWidgetInstance = mWidgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID)); // Set the widget variant mode if (mWidgetInstance != null) { VariantMode = mWidgetInstance.VariantMode; } } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } // Get widget info by widget name(widget type) mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(mWidgetInstance.WebPartType); } // Widget instance hasn't created yet else { mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } // Keep xml version if (mWidgetInstance != null) { mXmlVersion = mWidgetInstance.XMLVersion; } UIContext.EditedObject = mWidgetInfo; // Get the zone to which it inserts WebPartZoneInstance zone = mTemplateInstance.GetZone(ZoneId); if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null)) { ZoneType = zone.WidgetZoneType; } // Check security var currentUser = MembershipContext.AuthenticatedUser; switch (ZoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!mWidgetInfo.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!mWidgetInfo.WidgetForEditor) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!mWidgetInfo.WidgetForUser) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for dashboard zones case WidgetZoneTypeEnum.Dashboard: if (!mWidgetInfo.WidgetForDashboard) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; } // Check security if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } // Get form schemas mWebPartInfo = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(mWebPartInfo.WebPartProperties, mWidgetInfo.WidgetProperties); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, ZoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues); if (fi != null) { fi.ContextResolver.Settings.RelatedObject = mTemplateInstance; // Check if there are some editable properties var ffi = fi.GetFields(true, false); if ((ffi == null) || (ffi.Count == 0)) { ShowInformation(GetString("widgets.emptyproperties")); } DataRow dr = fi.GetDataRow(); // Load overridden values for new widget if (IsNewWidget || (mXmlVersion > 0)) { fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible); } if (IsNewWidget) { // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(mWidgetInfo.WidgetDisplayName)); } // Load values from existing widget LoadDataRowFromWidget(dr, fi); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.Base.Web.UI.ControlContext.WIDGET_PROPERTIES; } } if (IsInline) { // Load text definition from session string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), String.Empty); if (String.IsNullOrEmpty(definition)) { definition = Request.Form[hdnWidgetDefinition.UniqueID]; } else { hdnWidgetDefinition.Value = definition; } Hashtable parameters = null; string widgetName = String.Empty; if (IsNewWidget) { // New widget - load widget info by id if (!String.IsNullOrEmpty(WidgetId)) { mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } else { // Try to get widget from codename widgetName = QueryHelper.GetString("WidgetName", String.Empty); mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName); } } else { if (definition == null) { DisplayError("widget.failedtoload"); return; } // Parse definition parameters = CMSDialogHelper.GetHashTableFromString(definition); // Trim control name if (parameters["name"] != null) { widgetName = parameters["name"].ToString(); } mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName); } if (mWidgetInfo == null) { DisplayError("widget.failedtoload"); return; } // If widget cant be used as inline if (!mWidgetInfo.WidgetForInline) { DisplayError("widget.cantbeusedasinline"); return; } // Test permission for user var currentUser = MembershipContext.AuthenticatedUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { mIsValidWidget = false; OnNotAllowed(this, null); } // If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName)) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, mWidgetInfo.WidgetProperties); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, zoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues); if (fi != null) { // Check if there are some editable properties mFields = fi.GetFields(true, true); if ((mFields == null) || !mFields.Any()) { ShowInformation(GetString("widgets.emptyproperties")); } // Get datarows with required columns DataRow dr = PortalHelper.CombineWithDefaultValues(fi, mWidgetInfo); if (IsNewWidget) { // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible); } else { foreach (string key in parameters.Keys) { object value = parameters[key]; // Test if given property exists if (dr.Table.Columns.Contains(key) && (value != null)) { try { dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType); } catch { } } } } // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", mWidgetInfo.WidgetDisplayName); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.Base.Web.UI.ControlContext.WIDGET_PROPERTIES; } } }
/// <summary> /// Saves webpart properties. /// </summary> public bool Save() { // Check MVT/CP security if (VariantID > 0) { // Check OnlineMarketing permissions. if (!CheckPermissions("Manage")) { ShowError(GetString("general.modifynotallowed")); return(false); } } // Save the data if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form)) { if (SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } ShowError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName)); return(false); } // Add web part if new if (IsNewWebPart) { int webpartId = ValidationHelper.GetInteger(WebPartID, 0); // Ensure layout zone flag if (QueryHelper.GetBoolean("layoutzone", false)) { WebPartZoneInstance zone = pti.TemplateInstance.EnsureZone(ZoneID); zone.LayoutZone = true; } webPartInstance = PortalHelper.AddNewWebPart(webpartId, ZoneID, false, ZoneVariantID, Position, templateInstance); // Set default layout if (wpi.WebPartParentID > 0) { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetDefaultLayout(wpi.WebPartID); if (wpli != null) { webPartInstance.SetValue("WebPartLayout", wpli.WebPartLayoutCodeName); } } } webPartInstance.XMLVersion = 1; if (IsNewVariant) { webPartInstance = webPartInstance.Clone(); webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLowerInvariant()); } // Get basic form's data row and update web part SaveFormToWebPart(form); // Set new position if set if (PositionLeft > 0) { webPartInstance.SetValue("PositionLeft", PositionLeft); } if (PositionTop > 0) { webPartInstance.SetValue("PositionTop", PositionTop); } bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant; if (!isWebPartVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree); } else { Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable; // Save changes to the web part variant VariantHelper.SaveWebPartVariantChanges(webPartInstance, VariantID, ZoneVariantID, VariantMode, varProperties); } // Reload the form (because of macro values set only by JS) form.ReloadData(); // Clear the cached web part CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerInvariant()); ShowChangesSaved(); return(true); } if (webPartInstance?.ParentZone?.ParentTemplateInstance != null) { // Reload the zone/web part variants when saving of the form fails webPartInstance.ParentZone.ParentTemplateInstance.LoadVariants(true, VariantModeEnum.None); } return(false); }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return(false); } } // Save the data if ((CurrentPageInfo != null) && (mTemplateInstance != null) && SaveForm(formCustom)) { ViewModeEnum viewMode = PortalContext.ViewMode; // Check manage permission for non-livesite version if (!viewMode.IsLiveSite() && viewMode != ViewModeEnum.DashboardWidgets && viewMode != ViewModeEnum.UserWidgets) { if (CurrentUser.IsAuthorizedPerDocument(CurrentPageInfo.NodeID, CurrentPageInfo.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { DisplayError("general.modifynotallowed"); return(false); } // Check design permissions if (PortalContext.IsDesignMode(viewMode, false) && !PortalContext.CurrentUserIsDesigner) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = mTemplateInstance.ParentPageTemplate; if (PortalContext.IsDesignMode(viewMode) && SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName)); return(false); } // Get the zone mWebPartZoneInstance = mTemplateInstance.EnsureZone(ZoneId); if (mWebPartZoneInstance != null) { mWebPartZoneInstance.WidgetZoneType = ZoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance mWidgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, mTemplateInstance); } // Ensure handling of the currently edited object (if not exists -> redirect) UIContext.EditedObject = mWidgetInstance; mWidgetInstance.XMLVersion = 1; if (IsNewVariant) { mWidgetInstance = mWidgetInstance.Clone(); // Check whether the editor widgets have been already customized if (CurrentPageInfo.DocumentTemplateInstance.WebPartZones.Count == 0) { // There are no customized editor widgets yet => copy the default editor widgets from the page template under the document (to enable customization) // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); // Extract and set the document web parts node.SetValue("DocumentWebParts", mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, mTreeProvider); } } bool isLayoutWidget = ((mWebPartInfo != null) && ((WebPartTypeEnum)mWebPartInfo.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, mTemplateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(mWidgetInfo.WidgetName); if (!string.IsNullOrEmpty(controlId)) { mWidgetInstance.ControlID = controlId; } else { DisplayError("Unable to generate unique widget id."); return(false); } } // Allow set dashboard in design mode if ((ZoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { viewMode = ViewModeEnum.Design; PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes if ((viewMode.IsEdit(true) || viewMode.IsEditLive()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { if (DocumentManager.AllowSave) { // Store the editor widgets in the temporary interlayer PortalContext.SaveEditorWidgets(CurrentPageInfo.DocumentID, mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); } } else { // Save the changes CMSPortalManager.SaveTemplateChanges(CurrentPageInfo, mTemplateInstance, ZoneType, viewMode, mTreeProvider); } } else if ((viewMode.IsEdit()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; VariantHelper.SaveWebPartVariantChanges(mWidgetInstance, VariantID, 0, VariantMode, properties); // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, mTreeProvider); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Display info message ShowChangesSaved(); // Clear the cached web part CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); return(true); } return(false); }
/// <summary> /// Handles form's after data load event. /// </summary> protected void EditForm_OnAfterDataLoad(object sender, EventArgs e) { etaCode.Language = LanguageEnum.HTML; cssLayoutEditor.Editor.Language = LanguageEnum.CSS; cssLayoutEditor.Editor.ShowBookmarks = true; // Do not check changes DocumentManager.RegisterSaveChangesScript = false; EditForm.OnBeforeSave += EditForm_OnBeforeSave; etaCode.Language = LanguageEnum.HTML; wpli = UIContext.EditedObject as WebPartLayoutInfo; layoutID = QueryHelper.GetInteger("layoutid", 0); isSiteManager = ((MembershipContext.AuthenticatedUser.IsGlobalAdministrator && layoutID != 0) || QueryHelper.GetBoolean("sitemanager", false)); isNew = (LayoutCodeName == "|new|"); isDefault = (LayoutCodeName == "|default|") || (!isSiteManager && string.IsNullOrEmpty(LayoutCodeName)); if ((wpli == null) || (wpli.WebPartLayoutID <= 0)) { isNew |= isSiteManager; editMenuElem.ObjectManager.ObjectType = WebPartLayoutInfo.OBJECT_TYPE; } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "PreviewHierarchyPerformAction", ScriptHelper.GetScript("function actionPerformed(action) { if (action == 'saveandclose') { document.getElementById('" + hdnClose.ClientID + "').value = '1'; } " + editMenuElem.ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null) + "; }")); currentUser = MembershipContext.AuthenticatedUser; // Get web part instance (if edited in CMSDesk) if ((webpartId != "") && !isSiteManager) { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("WebPartProperties.WebPartNotFound"), persistent: false); } else { // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } } // If the web part is not found, try web part ID if (webPart == null) { wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wpi == null) { ShowError(GetString("WebPartProperties.WebPartNotFound")); startWithFullScreen = false; return; } } else { // CMS desk wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (string.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (wpi != null) { // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { if (wpli != null) { editMenuElem.MenuPanel.Visible = true; // Read-only code text area etaCode.Editor.ReadOnly = false; loaded = true; } if (!loaded) { string fileName = webPartInfo.WebPartFileName; if (webPartInfo.WebPartParentID > 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(webPartInfo.WebPartParentID); if (pwpi != null) { fileName = pwpi.WebPartFileName; } } if (!fileName.StartsWithCSafe("~")) { fileName = "~/CMSWebparts/" + fileName; } // Check if filename exist if (!FileHelper.FileExists(fileName)) { ShowError(GetString("WebPartProperties.FileNotExist")); pnlContent.Visible = false; editMenuElem.ObjectEditMenu.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS cssLayoutEditor.Text = wpi.WebPartCSS; startWithFullScreen = false; } } } } if (((wpli == null) || (wpli.WebPartLayoutID <= 0)) && isSiteManager) { editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("WebParts.Layout"), RedirectUrl = String.Format("{0}&parentobjectid={1}&displaytitle={2}", UIContextHelper.GetElementUrl("CMS.Design", "WebPart.Layout"), QueryHelper.GetInteger("webpartid", 0), false) }); editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("webparts_layout_newlayout"), }); } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + hidRefresh.ClientID + @"').value = refreshpage; } function OnApplyButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('save');refreshPreview(); } function OnOKButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('saveandclose'); } ")); InitLayoutForm(); }
/// <summary> /// Loads the widget form. /// </summary> private void LoadForm() { // Setup basic form on live site formCustom.AllowMacroEditing = false; formCustom.IsLiveSite = IsLiveSite; // Load settings if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the widget variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false); // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } EnsureDashboard(); if (!String.IsNullOrEmpty(WidgetId) && !IsInline) { if (CurrentPageInfo == null) { ShowError(GetString("Widgets.Properties.aliasnotfound")); pnlFormArea.Visible = false; return; } // Get template instance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo); if (!IsNewWidget) { // Get the instance of widget widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId); if (widgetInstance == null) { ShowError(GetString("Widgets.Properties.WidgetNotFound")); pnlFormArea.Visible = false; return; } if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { widgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId); widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID)); // Set the widget variant mode if (widgetInstance != null) { VariantMode = widgetInstance.VariantMode; } } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } // Keep xml version if (widgetInstance != null) { xmlVersion = widgetInstance.XMLVersion; } UIContext.EditedObject = wi; // Get the zone to which it inserts WebPartZoneInstance zone = templateInstance.GetZone(ZoneId); if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null)) { ZoneType = zone.WidgetZoneType; } // Check security var currentUser = MembershipContext.AuthenticatedUser; switch (ZoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!wi.WidgetForEditor) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!wi.WidgetForUser) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for dashboard zones case WidgetZoneTypeEnum.Dashboard: if (!wi.WidgetForDashboard) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; } // Check security if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } // Get form schemas wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(ZoneType); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), ZoneType), widgetProperties, zoneTypeDefinition, true, wi.WidgetDefaultValues); if (fi != null) { fi.ContextResolver.Settings.RelatedObject = templateInstance; // Check if there are some editable properties var ffi = fi.GetFields(true, false).ToList<FormFieldInfo>(); if ((ffi == null) || (ffi.Count == 0)) { ShowInformation(GetString("widgets.emptyproperties")); } DataRow dr = fi.GetDataRow(); // Load overridden values for new widget if (IsNewWidget || (xmlVersion > 0)) { fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible); } if (IsNewWidget) { // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName)); } // Load values from existing widget LoadDataRowFromWidget(dr, fi); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES; } } if (IsInline) { // Load text definition from session string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty); if (String.IsNullOrEmpty(definition)) { definition = Request.Form[hdnWidgetDefinition.UniqueID]; } else { hdnWidgetDefinition.Value = definition; } Hashtable parameters = null; string widgetName = string.Empty; if (IsNewWidget) { // New widget - load widget info by id if (!String.IsNullOrEmpty(WidgetId)) { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } else { // Try to get widget from codename widgetName = QueryHelper.GetString("WidgetName", String.Empty); wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } } else { if (definition == null) { DisplayError("widget.failedtoload"); return; } // Parse definition parameters = CMSDialogHelper.GetHashTableFromString(definition); // Trim control name if (parameters["name"] != null) { widgetName = parameters["name"].ToString(); } wi = WidgetInfoProvider.GetWidgetInfo(widgetName); } if (wi == null) { DisplayError("widget.failedtoload"); return; } // If widget cant be used as inline if (!wi.WidgetForInline) { DisplayError("widget.cantbeusedasinline"); return; } // Test permission for user var currentUser = MembershipContext.AuthenticatedUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { isValidWidget = false; OnNotAllowed(this, null); } // If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName)) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true, wi.WidgetDefaultValues); if (fi != null) { // Check if there are some editable properties mFields = fi.GetFields(true, true); if ((mFields == null) || !mFields.Any()) { ShowInformation(GetString("widgets.emptyproperties")); } // Get datarows with required columns DataRow dr = PortalHelper.CombineWithDefaultValues(fi, wi); if (IsNewWidget) { // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible); } else { foreach (string key in parameters.Keys) { object value = parameters[key]; // Test if given property exists if (dr.Table.Columns.Contains(key) && (value != null)) { try { dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType); } catch { } } } } // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES; } } }
public void BindData() { if (WebpartId != "") { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId, CultureCode); if (pi == null) { Visible = false; return; } // Get page template info pti = pi.UsedPageTemplateInfo; if (pti != null) { // Get web part instance webPart = pti.GetWebPart(InstanceGUID, WebpartId); if (webPart == null) { CMSPage.EditedObject = null; return; } // Get the web part info WebPartInfo wpi = WebPartInfoProvider.GetBaseWebPart(webPart.WebPartType); if (wpi == null) { return; } // Get webpart properties (XML) string wpProperties = wpi.WebPartProperties; FormInfo fi = PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); // Get datarow with required columns DataRow dr = fi.GetDataRow(); // Bind drop down list if (!RequestHelper.IsPostBack()) { DataTable dropTable = new DataTable(); dropTable.Columns.Add("name"); foreach (DataColumn column in dr.Table.Columns) { dropTable.Rows.Add(column.ColumnName); } dropTable.DefaultView.Sort = "name"; drpProperty.DataTextField = "name"; drpProperty.DataValueField = "name"; drpProperty.DataSource = dropTable.DefaultView; drpProperty.DataBind(); } // Bind grid view DataTable table = new DataTable(); table.Columns.Add("LocalProperty"); table.Columns.Add("SourceProperty"); bindings = webPart.Bindings; foreach (DataColumn column in dr.Table.Columns) { string propertyName = column.ColumnName.ToLowerCSafe(); if (bindings.ContainsKey(propertyName)) { WebPartBindingInfo bi = (WebPartBindingInfo)bindings[propertyName]; table.Rows.Add(column.ColumnName, bi.SourceWebPart + "." + bi.SourceProperty); } } gvBinding.DataSource = table; gvBinding.DataBind(); } } }
/// <summary> /// Saves webpart properties. /// </summary> public bool Save() { // Check MVT/CP security if (VariantID > 0) { // Check OnlineMarketing permissions. if (!CheckPermissions("Manage")) { ShowError("general.modifynotallowed"); return false; } } // Save the data if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form)) { if (SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } ShowError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName)); return false; } // Add web part if new if (IsNewWebPart) { int webpartId = ValidationHelper.GetInteger(WebPartID, 0); // Ensure layout zone flag if (QueryHelper.GetBoolean("layoutzone", false)) { WebPartZoneInstance zone = pti.TemplateInstance.EnsureZone(ZoneID); zone.LayoutZone = true; } webPartInstance = PortalHelper.AddNewWebPart(webpartId, ZoneID, false, ZoneVariantID, Position, templateInstance); // Set default layout if (wpi.WebPartParentID > 0) { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetDefaultLayout(wpi.WebPartID); if (wpli != null) { webPartInstance.SetValue("WebPartLayout", wpli.WebPartLayoutCodeName); } } } webPartInstance.XMLVersion = 1; if (IsNewVariant) { webPartInstance = webPartInstance.Clone(); webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLowerCSafe()); } // Get basic form's data row and update web part SaveFormToWebPart(form); // Set new position if set if (PositionLeft > 0) { webPartInstance.SetValue("PositionLeft", PositionLeft); } if (PositionTop > 0) { webPartInstance.SetValue("PositionTop", PositionTop); } // Ensure the data source web part instance in the main web part if (NestedWebPartID > 0) { webPartInstance.WebPartType = wpi.WebPartName; mainWebPartInstance.NestedWebParts[NestedWebPartKey] = webPartInstance; } bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant; if (!isWebPartVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree); } else { Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable; // Save changes to the web part variant VariantHelper.SaveWebPartVariantChanges(webPartInstance, VariantID, ZoneVariantID, VariantMode, varProperties); } // Reload the form (because of macro values set only by JS) form.ReloadData(); // Clear the cached web part CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); ShowChangesSaved(); return true; } else if ((mainWebPartInstance != null) && (mainWebPartInstance.ParentZone != null) && (mainWebPartInstance.ParentZone.ParentTemplateInstance != null)) { // Reload the zone/web part variants when saving of the form fails mainWebPartInstance.ParentZone.ParentTemplateInstance.LoadVariants(true, VariantModeEnum.None); } return false; }
/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(ArrayList elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.CategoryCaption + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.Caption + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return sb.ToString(); }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> /// <param name="webPart">Source web part</param> /// <param name="formInfo">Web part form info</param> private void LoadDataRowFromWebPart(DataRow dr, WebPartInstance webPart, FormInfo formInfo) { if (webPart != null) { foreach (DataColumn column in dr.Table.Columns) { try { bool load = true; // switch by xml version switch (xmlVersion) { case 1: load = webPart.Properties.Contains(column.ColumnName.ToLowerCSafe()) || column.ColumnName.EqualsCSafe("webpartcontrolid", true); break; // Version 0 default: // Load default value for Boolean type in old XML version if ((column.DataType == typeof(bool)) && !webPart.Properties.Contains(column.ColumnName.ToLowerCSafe())) { FormFieldInfo ffi = formInfo.GetFormField(column.ColumnName); if (ffi != null) { webPart.SetValue(column.ColumnName, ffi.GetPropertyValue(FormFieldPropertyEnum.DefaultValue)); } } break; } if (load) { var value = webPart.GetValue(column.ColumnName); // Convert value into default format if ((value != null) && (ValidationHelper.GetString(value, String.Empty) != String.Empty)) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.MinValue, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } } catch (Exception ex) { EventLogProvider.LogException("WebPartProperties", "LOADDATAROW", ex); } } } }
/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(IEnumerable<IField> elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.GetPropertyValue(FormCategoryPropertyEnum.Caption, MacroContext.CurrentResolver) + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver) + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return sb.ToString(); }
/// <summary> /// Loads the web part form. /// </summary> protected void LoadForm() { // Load settings if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Indicates whether the new variant should be chosen when closing this dialog selectNewVariant = IsNewVariant; // Try to find the web part variant in the database and set its VariantID if (IsNewVariant) { Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable; if (varProperties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(varProperties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateID, variantName, true); // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } if (!String.IsNullOrEmpty(WebPartID)) { // Get the page info pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode); if (pi == null) { ShowError(GetString("general.pagenotfound")); pnlExport.Visible = false; return; } // Get template pti = pi.UsedPageTemplateInfo; // Get template instance templateInstance = pti.TemplateInstance; if (!IsNewWebPart) { // Standard zone webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebPartID); // If the web part not found, try to find it among the MVT/CP variants if (webPartInstance == null) { // MVT/CP variant // Clone templateInstance to avoid caching of the temporary template instance loaded with CP/MVT variants var tempTemplateInstance = templateInstance.Clone(); tempTemplateInstance.LoadVariants(false, VariantModeEnum.None); webPartInstance = tempTemplateInstance.GetWebPart(InstanceGUID, -1); // Set the VariantMode according to the selected web part/zone variant if (webPartInstance?.ParentZone != null) { VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode; } else { VariantMode = VariantModeEnum.None; } } else { // Ensure that the ZoneVariantID is not set when the web part was found in a regular zone ZoneVariantID = 0; } if ((VariantID > 0) && webPartInstance?.PartInstanceVariants != null) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { webPartInstance = webPartInstance.FindVariant(VariantID); } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } if (webPartInstance == null) { UIContext.EditedObject = null; return; } } // Keep xml version if (webPartInstance != null) { xmlVersion = webPartInstance.XMLVersion; } // Get the form info FormInfo fi = GetWebPartFormInfo(); // Get the form definition if (fi != null) { fi.ContextResolver.Settings.RelatedObject = templateInstance; form.AllowMacroEditing = true; // Get data row with required columns DataRow dr = fi.GetDataRow(); if (IsNewWebPart || (xmlVersion > 0)) { fi.LoadDefaultValues(dr); } // Load values from existing web part LoadDataRowFromWebPart(dr, webPartInstance, fi); // Set a unique WebPartControlID for the new variant if (IsNewVariant || IsNewWebPart) { dr["WebPartControlID"] = GetUniqueWebPartId(); } // Init the form InitForm(form, dr, fi); DisplayExportPropertiesButton(); } else { UIContext.EditedObject = null; } } }
/// <summary> /// Init event handler. /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); // Load settings if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the web part variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = 0; if (VariantMode == VariantModeEnum.MVT) { variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName); } // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } if (!String.IsNullOrEmpty(WebpartId)) { // Get the page info pi = CMSWebPartPropertiesPage.GetPageInfo(this.AliasPath, this.PageTemplateId); if (pi != null) { // Get template pti = pi.PageTemplateInfo; // Get template instance templateInstance = pti.TemplateInstance; // Parent webpart WebPartInfo parentWpi = null; //Before FormInfo FormInfo beforeFI = null; //After FormInfo FormInfo afterFI = null; // Webpart form info FormInfo fi = null; if (!IsNewWebPart) { if (ZoneVariantID > 0) { // Zone variant WebPartZoneInstance wpzi = pti.GetZone(ZoneId, ZoneVariantID); webPartInstance = wpzi.GetWebPart(InstanceGUID); } else { // Standard zone webPartInstance = pti.GetWebPart(InstanceGUID, WebpartId); } if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { webPartInstance = webPartInstance.FindVariant(VariantID); } else { // Not authorised for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } if (webPartInstance == null) { lblInfo.Text = GetString("WebPartProperties.WebPartNotFound"); pnlFormArea.Visible = false; return; } wpi = WebPartInfoProvider.GetWebPartInfo(webPartInstance.WebPartType); form.Mode = FormModeEnum.Update; } // Webpart instance hasn't created yet else { wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(WebpartId, 0)); form.Mode = FormModeEnum.Insert; } // Load parent if (wpi != null) { if (wpi.WebPartParentID > 0) { parentWpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); } } // Get the form definition string wpProperties = "<form></form>"; if (wpi != null) { wpProperties = wpi.WebPartProperties; // Use parent webpart if is defined if (parentWpi != null) { wpProperties = parentWpi.WebPartProperties; } // Get before FormInfo if (BeforeFormDefinition == null) { beforeFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before); } else { beforeFI = new FormInfo(BeforeFormDefinition); } // Get after FormInfo if (AfterFormDefinition == null) { afterFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After); } else { afterFI = new FormInfo(AfterFormDefinition); } } // Add 'General' category at the beginning if no one is specified if (!string.IsNullOrEmpty(wpProperties) && (!wpProperties.StartsWith("<form><category", StringComparison.InvariantCultureIgnoreCase))) { wpProperties = wpProperties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />"); } // Get merged web part FormInfo fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName, wpProperties, beforeFI, afterFI, true); // Get datarow with required columns DataRow dr = fi.GetDataRow(); if (IsNewWebPart) { // Load default properties values fi.LoadDefaultValues(dr); // Load overriden system values fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues); // Set control ID FormFieldInfo ffi = fi.GetFormField("WebPartControlID"); if (ffi != null) { ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance); fi.UpdateFormField("WebPartControlID", ffi); } } // Load values from existing webpart LoadDataRowFromWebPart(dr, webPartInstance); // Set a unique WebPartControlID for athe new variant if (IsNewVariant) { // Set control ID dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance); } // Init the form InitForm(form, dr, fi); AddExportLink(); } } }
protected override void OnLoad(EventArgs e) { plImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png"); minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png"); if (WebpartID != String.Empty) { wpi = WebPartInfoProvider.GetWebPartInfo(WebpartID); } // Ensure correct view mode if (String.IsNullOrEmpty(AliasPath)) { // Ensure the dashboard mode for the dialog if (!string.IsNullOrEmpty(DashboardName)) { PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets); PortalContext.DashboardName = DashboardName; PortalContext.DashboardSiteName = DashboardSiteName; } // Ensure the design mode for the dialog else { PortalContext.SetRequestViewMode(ViewModeEnum.Design); } } if (WidgetID != 0) { PageInfo pi = null; try { // Load page info from alias path and page template pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi != null) { PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (templateInstance != null) { // Get the instance of widget WebPartInstance widgetInstance = templateInstance.GetWebPart(InstanceGUID); // Info for zone type WebPartZoneInstance zone = templateInstance.GetZone(ZoneID); if (zone != null) { zoneType = zone.WidgetZoneType; } if (widgetInstance != null) { // Create widget from webpart instance wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } } } // If inline widget display columns as in editor zone if (IsInline) { zoneType = WidgetZoneTypeEnum.Editor; } // If no zone set (only global admins allowed to continue) if (zoneType == WidgetZoneTypeEnum.None) { if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { RedirectToAccessDenied(GetString("attach.actiondenied")); } } // If wi is still null (new item f.e.) if (wi == null) { // Try to get widget info directly by ID wi = WidgetInfoProvider.GetWidgetInfo(WidgetID); } } String itemDescription = String.Empty; String itemType = String.Empty; String itemDisplayName = String.Empty; String itemDocumentation = String.Empty; String itemIcon = String.Empty; int itemID = 0; // Check whether webpart was found if (wpi != null) { itemDescription = wpi.WebPartDescription; itemType = WebPartInfo.OBJECT_TYPE; itemID = wpi.WebPartID; itemDisplayName = wpi.WebPartDisplayName; itemDocumentation = wpi.WebPartDocumentation; itemIcon = PortalHelper.GetIconHtml(wpi.WebPartThumbnailGUID, wpi.WebPartIconClass ?? PortalHelper.DefaultWebPartIconClass); } // Or widget was found else if (wi != null) { itemDescription = wi.WidgetDescription; itemType = WidgetInfo.OBJECT_TYPE; itemID = wi.WidgetID; itemDisplayName = wi.WidgetDisplayName; itemDocumentation = wi.WidgetDocumentation; itemIcon = PortalHelper.GetIconHtml(wi.WidgetThumbnailGUID, wi.WidgetIconClass ?? PortalHelper.DefaultWidgetIconClass); } if ((wpi != null) || (wi != null)) { // Get WebPart (widget) icon ltrImage.Text = itemIcon; // Set description of webpart ltlDescription.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(itemDescription)); // Get description from parent weboart if webpart is inherited if ((wpi != null) && (string.IsNullOrEmpty(wpi.WebPartDescription) && (wpi.WebPartParentID > 0))) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null) { ltlDescription.Text = HTMLHelper.HTMLEncode(pwpi.WebPartDescription); } } FormInfo fi = null; // Generate properties if (wpi != null) { // Get form info from parent if webpart is inherited if (wpi.WebPartParentID != 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null) { fi = GetWebPartProperties(pwpi); } } else { fi = GetWebPartProperties(wpi); } } else if (wi != null) { fi = GetWidgetProperties(wi); } // Generate properties if (fi != null) { GenerateProperties(fi); } // Generate documentation text if (itemDocumentation == null || itemDocumentation.Trim() == "") { if ((wpi != null) && (wpi.WebPartParentID != 0)) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null && pwpi.WebPartDocumentation.Trim() != "") { ltlContent.Text = HTMLHelper.ResolveUrls(pwpi.WebPartDocumentation, null); } else { ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />"; } } else { ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />"; } } else { ltlContent.Text = HTMLHelper.ResolveUrls(itemDocumentation, null); } } ScriptHelper.RegisterJQuery(Page); string script = @" $cmsj(document.body).ready(initializeResize); function initializeResize () { resizeareainternal(); $cmsj(window).resize(function() { resizeareainternal(); }); } function resizeareainternal () { var height = document.body.clientHeight ; var panel = document.getElementById ('" + divScrolable.ClientID + @"'); // Get parent footer to count proper height (with padding included) var footer = $cmsj('#divFooter'); panel.style.height = (height - footer.outerHeight() - panel.offsetTop) +'px'; }"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "mainScript", ScriptHelper.GetScript(script)); // Init tabs tabControlElem.UsePostback = true; tabControlElem.AddTab(new UITabItem() { Text = GetString("webparts.documentation"), }); tabControlElem.AddTab(new UITabItem() { Text = GetString("general.properties"), }); // Disable caching Response.Cache.SetNoStore(); base.OnLoad(e); }
protected void Page_Load(object sender, EventArgs e) { this.CurrentMaster.DisplaySiteSelectorPanel = true; if (webpartId != "") { // Get pageinfo pi = GetPageInfo(aliasPath, templateId); if (pi == null) { RedirectToInformation(GetString("WebPartProperties.WebPartNotFound")); return; } // Get page template pti = pi.PageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); } } // If the web part is not found, do not continue if (webPart == null) { RedirectToInformation(GetString("WebPartProperties.WebPartNotFound")); return; } else { // Get the current layout name if (String.IsNullOrEmpty(LayoutCodeName)) { mLayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } // Strings lblLayouts.Text = GetString("WebPartPropertise.LayoutList"); if (!RequestHelper.IsPostBack()) { LoadLayouts(); } // Add default drop down items selectLayout.ShowDefaultItem = true; // Add new item if (SettingsKeyProvider.UsingVirtualPathProvider && CurrentUser.IsAuthorizedPerResource("CMS.Design", "EditCode")) { selectLayout.ShowNewItem = true; } webPartInfo = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); // Where condition selectLayout.WhereCondition = "WebPartLayoutWebPartID =" + webPartInfo.WebPartID; if (QueryHelper.GetBoolean("reload", false)) { SetContentPage(); } }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { ShowError("general.modifynotallowed"); return false; } } // Save the data if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(formCustom)) { // Check manage permission for non-livesite version if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.DashboardWidgets)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(pi.NodeId, pi.ClassName, NodePermissionsEnum.Modify, CMSContext.CurrentSiteName) != AuthorizationResultEnum.Allowed) { return false; } } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = zoneType; // Add new widget if (IsNewWidget) { AddWidget(); } if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); if (pi.DocumentTemplateInstance.WebPartZones.Count == 0) { // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(pi.DocumentId, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } // Get basicform's datarow and update widget SaveFormToWidget(formCustom); if (IsNewVariant) { // Ensures unique id for new widget variant widgetInstance.ControlID = WebPartZoneInstance.GetUniqueWebPartId(wi.WidgetName, zone.ParentTemplateInstance); } // Allow set dashboard in design mode if ((zoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, pti, templateInstance, zoneType, CMSContext.ViewMode, tree); } else if ((CMSContext.ViewMode == ViewModeEnum.Edit) && (zoneType == WidgetZoneTypeEnum.Editor)) { // Save the variant properties if ((widgetInstance != null) && (widgetInstance.ParentZone != null) && (widgetInstance.ParentZone.ParentTemplateInstance != null) && (widgetInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate != null)) { string variantName = string.Empty; string variantDisplayName = string.Empty; string variantDisplayCondition = string.Empty; string variantDescription = string.Empty; bool variantEnabled = true; string zoneId = widgetInstance.ParentZone.ZoneID; int templateId = widgetInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate.PageTemplateId; Guid instanceGuid = Guid.Empty; XmlDocument doc = new XmlDocument(); XmlNode xmlWebParts = null; xmlWebParts = widgetInstance.GetXmlNode(doc); instanceGuid = InstanceGUID; Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { variantName = ValidationHelper.GetString(properties["codename"], string.Empty); variantDisplayName = ValidationHelper.GetString(properties["displayname"], string.Empty); variantDescription = ValidationHelper.GetString(properties["description"], string.Empty); variantEnabled = ValidationHelper.GetBoolean(properties["enabled"], true); if (VariantMode == VariantModeEnum.ContentPersonalization) { variantDisplayCondition = ValidationHelper.GetString(properties["condition"], string.Empty); } } // Save the web part variant properties if (VariantMode == VariantModeEnum.MVT) { ModuleCommands.OnlineMarketingSaveMVTVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, zoneId, widgetInstance.InstanceGUID, templateId, pi.DocumentId, xmlWebParts); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { ModuleCommands.OnlineMarketingSaveContentPersonalizationVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, variantDisplayCondition, zoneId, widgetInstance.InstanceGUID, templateId, pi.DocumentId, xmlWebParts); } // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(pi.DocumentId, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLower()); } return true; } return false; }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { string widgetId = QueryHelper.GetString("widgetid", String.Empty); string aliasPath = QueryHelper.GetString("aliasPath", String.Empty); int templateId = QueryHelper.GetInteger("templateid", 0); string zoneId = QueryHelper.GetString("zoneid", String.Empty); Guid instanceGUID = QueryHelper.GetGuid("instanceguid", Guid.Empty); bool isNewWidget = QueryHelper.GetBoolean("isnew", false); bool inline = QueryHelper.GetBoolean("inline", false); int variantId = QueryHelper.GetInteger("variantid", 0); string culture = QueryHelper.GetString("culture", CMSContext.PreferredCultureCode); // Set page title Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title"); // Resize the header (enlarge) to make a space for the tabs header when displaying a widget variant if (variantId > 0) { rowsFrameset.Attributes.Add("rows", "67, *"); } // Ensure correct view mode if (String.IsNullOrEmpty(aliasPath)) { // Ensure the dashboard mode for the dialog if (QueryHelper.Contains("dashboard")) { PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets); PortalContext.DashboardName = QueryHelper.GetString("dashboard", String.Empty); PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty); } // Ensure the design mode for the dialog else { PortalContext.SetRequestViewMode(ViewModeEnum.Design); } } if (widgetId != "") { // Get pageinfo PageInfo pi = null; try { pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi == null) { return; } // Get template instance PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); // Get widget from instance WidgetInfo wi = null; if (!isNewWidget) { // Get the instance of widget WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGUID, widgetId); if (widgetInstance == null) { return; } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0)); } if (wi != null) { WebPartZoneInstance zone = templateInstance.GetZone(zoneId); if (zone != null) { CurrentUserInfo currentUser = CMSContext.CurrentUser; switch (zone.WidgetZoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupID) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!wi.WidgetForEditor) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!wi.WidgetForUser) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } break; } if ((zone.WidgetZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { RedirectToAccessDenied(GetString("widgets.security.notallowed")); } } // If all ok, set up frames frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query); frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query); } } frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query); if (inline && !isNewWidget) { frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm")); } else { frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query); } }
/// <summary> /// Adds web part. /// </summary> private void AddWebPart() { int webpartID = ValidationHelper.GetInteger(WebpartId, 0); // Add web part to the currently selected zone under currently selected page if ((webpartID > 0) && !string.IsNullOrEmpty(ZoneId)) { // Get the web part by code name WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webpartID); if (wi != null) { // Ensure layout zone flag if (QueryHelper.GetBoolean("layoutzone", false)) { WebPartZoneInstance zone = pti.EnsureZone(ZoneId); zone.LayoutZone = true; } // Add the web part WebPartInstance newPart = null; if (ZoneVariantID == 0) { newPart = pti.AddWebPart(ZoneId, webpartID); } else { WebPartZoneInstance wpzi = templateInstance.EnsureZone(ZoneId); wpzi = wpzi.ZoneInstanceVariants.Find(z => z.VariantID.Equals(ZoneVariantID)); if (wpzi != null) { newPart = wpzi.AddWebPart(webpartID); } } if (newPart != null) { // Prepare the form info to get the default properties FormInfo fi = null; if (wi.WebPartParentID > 0) { // Get from parent WebPartInfo parentWi = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentWi != null) { fi = new FormInfo(parentWi.WebPartProperties); } } if (fi == null) { fi = new FormInfo(wi.WebPartProperties); } // Load the default values to the properties if (fi != null) { DataRow dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); newPart.LoadProperties(dr); } // Add webpart to user's last recently used CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWebPart(wi.WebPartName); // Add last selection date to webpart wi.WebPartLastSelection = DateTime.Now; WebPartInfoProvider.SetWebPartInfo(wi); webPartInstance = newPart; } } } }