protected void Page_Load(object sender, EventArgs e) { // Get web part info webPartInfo = WebPartInfoProvider.GetWebPartInfo(WebPartID); UIContext.EditedObject = webPartInfo; // Check if info object exists if (webPartInfo != null) { // Set field editor if (webPartInfo.WebPartParentID > 0) { parentWebPartInfo = WebPartInfoProvider.GetWebPartInfo(webPartInfo.WebPartParentID); if (parentWebPartInfo != null) { fieldEditor.Mode = FieldEditorModeEnum.InheritedWebPartProperties; fieldEditor.AllowExtraFields = true; fieldEditor.OriginalFormDefinition = parentWebPartInfo.WebPartProperties; fieldEditor.FormDefinition = FormHelper.MergeFormDefinitions(parentWebPartInfo.WebPartProperties, webPartInfo.WebPartProperties); fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; } } else { fieldEditor.Mode = FieldEditorModeEnum.WebPartProperties; fieldEditor.WebPartId = WebPartID; // Check newly created field for widgets update fieldEditor.OnFieldCreated += UpdateWidgetsDefinition; fieldEditor.AfterItemDeleted += fieldEditor_AfterItemDeleted; } } }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { previewState = GetPreviewStateFromCookies(CMSPreviewControl.WEBPARTCSS); startWithFullScreen = previewState != 0; // Hide to better fullscreen load bool hide = (BrowserHelper.IsSafari() || BrowserHelper.IsChrome()); pnlContent.Attributes["style"] = (startWithFullScreen && !hide) ? "display:none" : "display:block"; // Register preview scripts ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "performAction", ScriptHelper.GetScript("function actionPerformed(action) { " + Page.ClientScript.GetPostBackEventReference(btnAction, "#").Replace("'#'", "action") + ";}")); wpi = UIContext.EditedObject as WebPartInfo; if ((wpi != null) && !URLHelper.IsPostback()) { etaCSS.Text = wpi.WebPartCSS; } InitHeaderActions(); RegisterInitScripts(pnlContent.ClientID, pnlMenu.ClientID, startWithFullScreen); }
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(); } } } }
protected void Page_Load(object sender, EventArgs e) { widgetInfo = WidgetInfoProvider.GetWidgetInfo(WidgetID); if (widgetInfo != null) { webpartInfo = WebPartInfoProvider.GetWebPartInfo(widgetInfo.WidgetWebPartID); fieldEditor.DisplayIn = FormInfo.DISPLAY_CONTEXT_DASHBOARD; if (webpartInfo != null) { // Merge class and alternative form definitions string formDef = FormHelper.MergeFormDefinitions(webpartInfo.WebPartProperties, widgetInfo.WidgetProperties); // Use alternative form mode for field editor fieldEditor.Mode = FieldEditorModeEnum.General; fieldEditor.FormDefinition = formDef; fieldEditor.IsAlternativeForm = true; // Use same control for widgets as for webparts fieldEditor.DisplayedControls = FieldEditorControlsEnum.Controls; // Handle definition update (move up, move down, delete, OK button) fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; } } else { fieldEditor.Visible = false; ShowError(GetString("general.invalidid")); } }
/// <summary> /// Adds the inline widget without the properties dialog. /// </summary> /// <param name="widgetId">The widget id</param> private string AddInlineWidgetWithoutDialog(int widgetId) { string script = string.Empty; if (widgetId > 0) { // New widget - load widget info by id WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetId); if ((wi != null) && wi.WidgetForInline) { // Test permission for user CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(widgetId, currentUser.UserID, currentUser.IsAuthenticated())) { return(string.Empty); } // If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.IsEditor) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); // Get the properties xml according to the zone type FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType); // Merge the parent web part properties definition with the widget properties definition string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); // Create the FormInfo for the current widget properties definition FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); DataRow dr = null; if (fi != null) { // Check if there are some editable properties List <FormFieldInfo> mFields = fi.GetFields(true, true); // Get data rows with required columns dr = PortalHelper.CombineWithDefaultValues(fi, wi); // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); } // Save inline widget script script = PortalHelper.GetAddInlineWidgetScript(wi, dr, fi.GetFields(true, true)); script += " CloseDialog();"; if (!string.IsNullOrEmpty(script)) { // Add to recently used widgets collection CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName); } } } return(script); }
/// <summary> /// Generate form info for webpart. /// </summary> /// <param name="wpi">Web part info</param> private FormInfo CreateFormInfo(WebPartInfo wpi) { if (wpi != null) { // Get parent webpart if webpart is inherited if (wpi.WebPartParentID != 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null) { wpi = pwpi; } } } return FormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); }
/// <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; } } }
/// <summary> /// Creates new web part. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Validate the text box fields string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result; // Validate and trim file name textbox only if it's visible if (radNewWebPart.Checked && radNewFile.Checked) { if (String.IsNullOrEmpty(errorMessage)) { errorMessage = new Validator().IsFileName(Path.GetFileName(txtCodeFileName.Text), GetString("WebPart_Clone.InvalidFileName")).Result; } } // Check file name if (radExistingFile.Checked && radNewWebPart.Checked) { if (String.IsNullOrEmpty(errorMessage)) { string webpartPath = WebPartInfoProvider.GetWebPartPhysicalPath(FileSystemSelector.Value.ToString()); errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result; } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(HTMLHelper.HTMLEncode(errorMessage)); return; } // Run in transaction using (var tr = new CMSTransactionScope()) { WebPartInfo wi = new WebPartInfo(); // Check if new name is unique WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text); if (webpart != null) { ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text)); return; } string filename = String.Empty; if (radNewWebPart.Checked) { if (radExistingFile.Checked) { filename = FileSystemSelector.Value.ToString().Trim(); if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/")) { filename = filename.Substring("~/cmswebparts/".Length); } } else { filename = txtCodeFileName.Text.Trim(); if (!filename.EndsWithCSafe(".ascx")) { filename += ".ascx"; } } } wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim(); wi.WebPartFileName = filename; wi.WebPartName = txtWebPartName.Text.Trim(); wi.WebPartCategoryID = QueryHelper.GetInteger("parentobjectid", 0); wi.WebPartDescription = ""; wi.WebPartDefaultValues = "<form></form>"; // Initialize WebPartType - fill it with the default value wi.WebPartType = wi.WebPartType; wi.WebPartIconClass = PortalHelper.DefaultWebPartIconClass; // Inherited web part if (radInherited.Checked) { // Check if is selected webpart and isn't category item if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0) { ShowError(GetString("WebPartNew.InheritedCategory")); return; } int parentId = ValidationHelper.GetInteger(webpartSelector.Value, 0); var parent = WebPartInfoProvider.GetWebPartInfo(parentId); if (parent != null) { wi.WebPartType = parent.WebPartType; wi.WebPartResourceID = parent.WebPartResourceID; wi.WebPartSkipInsertProperties = parent.WebPartSkipInsertProperties; wi.WebPartIconClass = parent.WebPartIconClass; } wi.WebPartParentID = parentId; // Create empty default values definition wi.WebPartProperties = "<defaultvalues></defaultvalues>"; } else { // Check if filename was added if (FileSystemSelector.Visible && !FileSystemSelector.IsValid()) { ShowError(FileSystemSelector.ValidationError); return; } wi.WebPartProperties = "<form></form>"; wi.WebPartParentID = 0; } // Save the web part WebPartInfoProvider.SetWebPartInfo(wi); if (radNewFile.Checked && radNewWebPart.Checked) { string physicalFile = WebPartInfoProvider.GetFullPhysicalPath(wi); if (!File.Exists(physicalFile)) { // Write the files try { var generator = new WebPartCodeGenerator(SystemContext.ApplicationPath, SystemContext.IsWebApplicationProject); var result = generator.GenerateWebPartCode(wi); string folder = Path.GetDirectoryName(physicalFile); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } File.WriteAllText(physicalFile, result.Markup); File.WriteAllText(physicalFile + ".cs", result.Code); // Designer file if (!String.IsNullOrEmpty(result.Designer)) { File.WriteAllText(physicalFile + ".designer.cs", result.Designer); } } catch (Exception ex) { LogAndShowError("WebParts", "GENERATEFILES", ex, true); return; } } else { ShowError(String.Format(GetString("General.FileExistsPath"), physicalFile)); return; } } // Refresh web part tree ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframee", ScriptHelper.GetScript( "parent.location = '" + UIContextHelper.GetElementUrl("cms.design", "Development.Webparts", false, wi.WebPartID) + "';")); PageBreadcrumbs.Items[1].Text = HTMLHelper.HTMLEncode(wi.WebPartDisplayName); ShowChangesSaved(); plcTable.Visible = false; tr.Commit(); } }
/// <summary> /// PreInit event handler. /// </summary> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); // Init the page components PageManager = manPortal; manPortal.SetMainPagePlaceholder(plc); int webPartId = QueryHelper.GetInteger("webpartid", 0); wpi = WebPartInfoProvider.GetWebPartInfo(webPartId); UIContext.EditedObject = wpi; // If default configuration not available, do not display content configAvailable = wpi.HasDefaultConfiguration(); var pt = wpi.GetVirtualPageTemplate(); PageInfo pi = PageInfoProvider.GetVirtualPageInfo(pt); pi.DocumentNamePath = "/" + ResHelper.GetString("edittabs.design"); DocumentContext.CurrentPageInfo = pi; // Set the design mode PortalContext.SetRequestViewMode(ViewModeEnum.DesignWebPart); ManagersContainer = plcManagers; ScriptManagerControl = manScript; }
/// <summary> /// Selected index changed. /// </summary> private void InitLayoutForm() { if (webPartInfo != null) { if (!String.IsNullOrEmpty(LayoutCodeName)) { if (LayoutCodeName == "|new|") { // New layout plcDescription.Visible = true; plcValues.Visible = true; etaCode.ReadOnly = false; etaCSS.ReadOnly = false; etaCode.Rows = 19; pnlMenu.Visible = false; pnlCheckOutInfo.Visible = false; // Prefill with default layout etaCode.Text = GetDefaultCode(); } else { etaCode.Rows = 24; plcDescription.Visible = false; plcValues.Visible = false; etaCode.ReadOnly = false; if (LayoutCodeName == "|default|") { // Get default code and disable editing etaCode.Text = GetDefaultCode(); etaCode.ReadOnly = true; etaCSS.ReadOnly = true; etaCSS.Text = webPartInfo.WebPartCSS; pnlMenu.Visible = false; pnlCheckOutInfo.Visible = false; } else { // Other layouts etaCode.Rows = 18; pnlMenu.Visible = true; pnlCheckOutInfo.Visible = true; etaCode.Text = "Loading..."; WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wpi != null) { // Get the layout code from layout info WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); if (wpli != null) { SetCheckPanel(null); etaCode.Text = wpli.WebPartLayoutCode; etaCSS.ReadOnly = false; etaCSS.Text = wpli.WebPartLayoutCSS; } } } } } } else { } }
/// <summary> /// Sets current layout. /// </summary> protected void SetCurrentLayout(bool saveToWebPartInstance, bool updateLayout) { if ((webPart != null) && (LayoutCodeName != "|new|")) { if (saveToWebPartInstance) { if (LayoutCodeName == "|default|") { webPart.SetValue("WebPartLayout", ""); } else { webPart.SetValue("WebPartLayout", LayoutCodeName); } bool isWebPartVariant = (variantId > 0) || (zoneVariantId > 0) || isNewVariant; if (!isWebPartVariant) { // Update page template PageTemplateInfoProvider.SetPageTemplateInfo(pti); } else { // Save the variant properties if ((webPart != null) && (webPart.ParentZone != null) && (webPart.ParentZone.ParentTemplateInstance != null) && (webPart.ParentZone.ParentTemplateInstance.ParentPageTemplate != null)) { XmlDocument doc = new XmlDocument(); XmlNode xmlWebParts = null; if (zoneVariantId > 0) { // This webpart is in a zone variant therefore save the whole variant webparts xmlWebParts = webPart.ParentZone.GetXmlNode(doc); if (webPart.VariantMode == VariantModeEnum.MVT) { ModuleCommands.OnlineMarketingSaveMVTVariantWebParts(zoneVariantId, xmlWebParts); } else if (webPart.VariantMode == VariantModeEnum.ContentPersonalization) { ModuleCommands.OnlineMarketingSaveContentPersonalizationVariantWebParts(zoneVariantId, xmlWebParts); } } else if (variantId > 0) { // This webpart is a web part variant xmlWebParts = webPart.GetXmlNode(doc); if (webPart.VariantMode == VariantModeEnum.MVT) { ModuleCommands.OnlineMarketingSaveMVTVariantWebParts(variantId, xmlWebParts); } else if (webPart.VariantMode == VariantModeEnum.ContentPersonalization) { ModuleCommands.OnlineMarketingSaveContentPersonalizationVariantWebParts(variantId, xmlWebParts); } } } } } string parameters = this.aliasPath + "/" + this.zoneId + "/" + this.webpartId; string cacheName = "CMSVirtualWebParts|" + parameters.ToLower().TrimStart('/'); CacheHelper.Remove(cacheName); if (updateLayout) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wpi != null) { WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); if (wpli != null) { if (CurrentUser.IsAuthorizedPerResource("CMS.Design", "EditCode")) { wpli.WebPartLayoutCode = etaCode.Text; } wpli.WebPartLayoutCSS = etaCSS.Text; WebPartLayoutInfoProvider.SetWebPartLayoutInfo(wpli); } } } } }
/// <summary> /// Loads the parent web part based on the current web part object /// </summary> private void EnsureParentWebPartInfo() { if (parentWpi != null) { return; } // Ensure the web part EnsureWebPartInfo(); if ((wpi != null) && (wpi.WebPartParentID > 0)) { parentWpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); } }
/// <summary> /// Button OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Trim text values txtWebPartName.Text = txtWebPartName.Text.Trim(); txtWebPartDisplayName.Text = txtWebPartDisplayName.Text.Trim(); txtWebPartFileName.Text = txtWebPartFileName.Text.Trim(); // Validate the text box fields string errorMessage = new Validator() .NotEmpty(txtWebPartName.Text, rfvWebPartName.ErrorMessage) .NotEmpty(txtWebPartDisplayName.Text, rfvWebPartDisplayName.ErrorMessage) .IsCodeName(txtWebPartName.Text, GetString("WebPart_Clone.InvalidCodeName")) .Result; // Validate file name if (string.IsNullOrEmpty(errorMessage) && chckCloneWebPartFiles.Checked) { errorMessage = new Validator() .NotEmpty(txtWebPartFileName.Text, rfvWebPartFileName.ErrorMessage) .IsFileName(Path.GetFileName(txtWebPartFileName.Text.Trim('~')), GetString("WebPart_Clone.InvalidFileName")).Result; } // Check if webpart with same name exists if (WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text) != null) { errorMessage = GetString(String.Format("Development-WebPart_Clone.WebPartExists", txtWebPartName.Text)); } // Check if webpart is not cloned to the root category WebPartCategoryInfo wci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("/"); if (wci.CategoryID == ValidationHelper.GetInteger(drpWebPartCategories.SelectedValue, -1)) { errorMessage = GetString("Development-WebPart_Clone.cannotclonetoroot"); } if (errorMessage != "") { lblError.Text = errorMessage; lblError.Visible = true; return; } // get web part info object WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webPartId); if (wi == null) { lblError.Text = GetString("WebPart_Clone.InvalidWebPartID"); lblError.Visible = true; return; } // Create new webpart with all properties from source webpart WebPartInfo nwpi = new WebPartInfo(wi, false); nwpi.WebPartID = 0; nwpi.WebPartGUID = Guid.NewGuid(); // Modify clone info nwpi.WebPartName = txtWebPartName.Text; nwpi.WebPartDisplayName = txtWebPartDisplayName.Text; nwpi.WebPartCategoryID = ValidationHelper.GetInteger(drpWebPartCategories.SelectedValue, -1); if (nwpi.WebPartParentID <= 0) { nwpi.WebPartFileName = txtWebPartFileName.Text; } string path = String.Empty; string filename = String.Empty; string inher = String.Empty; try { // Copy file if needed and webpart is not ihnerited if (chckCloneWebPartFiles.Checked && (wi.WebPartParentID == 0)) { // Get source file path string srcFile = GetWebPartPhysicalPath(wi.WebPartFileName); // Get destination file path string dstFile = GetWebPartPhysicalPath(nwpi.WebPartFileName); // Ensure directory DirectoryHelper.EnsureDiskPath(Path.GetDirectoryName(DirectoryHelper.EnsurePathBackSlash(dstFile)), URLHelper.WebApplicationPhysicalPath); // Check if source and target file path are different if (File.Exists(dstFile)) { throw new Exception(GetString("general.fileexists")); } // Get file name filename = Path.GetFileName(dstFile); // Get path to the partial class name replace string wpPath = nwpi.WebPartFileName; if (!wpPath.StartsWith("~/")) { wpPath = WebPartInfoProvider.WebPartsDirectory + "/" + wpPath.TrimStart('/'); } path = Path.GetDirectoryName(wpPath); inher = path.Replace('\\', '_').Replace('/', '_') + "_" + Path.GetFileNameWithoutExtension(filename).Replace('.', '_'); inher = inher.Trim('~'); inher = inher.Trim('_'); // Read .aspx file, replace classname and save as new file string text = File.ReadAllText(srcFile); File.WriteAllText(dstFile, ReplaceASCX(text, DirectoryHelper.CombinePath(path, filename), inher)); // Read .aspx file, replace classname and save as new file if (File.Exists(srcFile + ".cs")) { text = File.ReadAllText(srcFile + ".cs"); File.WriteAllText(dstFile + ".cs", ReplaceASCXCS(text, inher)); } if (File.Exists(srcFile + ".vb")) { text = File.ReadAllText(srcFile + ".vb"); File.WriteAllText(dstFile + ".vb", ReplaceASCXVB(text, inher)); } // Copy web part subfolder string srcDirectory = srcFile.Remove(srcFile.Length - Path.GetFileName(srcFile).Length) + Path.GetFileNameWithoutExtension(srcFile) + "_files"; if (Directory.Exists(srcDirectory)) { string dstDirectory = dstFile.Remove(dstFile.Length - Path.GetFileName(dstFile).Length) + Path.GetFileNameWithoutExtension(dstFile) + "_files"; if (srcDirectory.ToLower() != dstDirectory.ToLower()) { DirectoryHelper.EnsureDiskPath(srcDirectory, URLHelper.WebApplicationPhysicalPath); DirectoryHelper.CopyDirectory(srcDirectory, dstDirectory); } } } } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; return; } // Add new web part to database WebPartInfoProvider.SetWebPartInfo(nwpi); try { // Get and duplicate all webpart layouts associated to webpart DataSet ds = WebPartLayoutInfoProvider.GetWebPartLayouts(webPartId); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { WebPartLayoutInfo wpli = new WebPartLayoutInfo(dr); wpli.WebPartLayoutID = 0; // Create new record wpli.WebPartLayoutWebPartID = nwpi.WebPartID; // Associate layout to new webpart wpli.WebPartLayoutGUID = Guid.NewGuid(); wpli.WebPartLayoutCheckedOutByUserID = 0; wpli.WebPartLayoutCheckedOutFilename = ""; wpli.WebPartLayoutCheckedOutMachineName = ""; // Replace classname and inherits attribut wpli.WebPartLayoutCode = ReplaceASCX(wpli.WebPartLayoutCode, DirectoryHelper.CombinePath(path, filename), inher); WebPartLayoutInfoProvider.SetWebPartLayoutInfo(wpli); } } // Duplicate associated thumbnail MetaFileInfoProvider.CopyMetaFiles(webPartId, nwpi.WebPartID, PortalObjectType.WEBPART, MetaFileInfoProvider.OBJECT_CATEGORY_THUMBNAIL, null); } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; return; } // Close clone window // Refresh web part tree and select/edit new widget string script = String.Empty; string refreshLink = URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Tree.aspx?webpartid=" + nwpi.WebPartID + "&reload=true"); if (QueryHelper.Contains("reloadAll")) { script += "wopener.parent.parent.frames['webparttree'].location.href ='" + refreshLink + "';"; } else { script = "wopener.location = '" + refreshLink + "';"; } script += "window.close();"; ltlScript.Text = ScriptHelper.GetScript(script); }
/// <summary> /// Adds the inline widget without the properties dialog. /// </summary> /// <param name="widgetId">The widget id</param> private string AddInlineWidgetWithoutDialog(int widgetId) { string script = string.Empty; if (widgetId > 0) { // New widget - load widget info by id WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetId); if ((wi != null) && wi.WidgetForInline) { // Test permission for user var currentUser = MembershipContext.AuthenticatedUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(widgetId, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { return(string.Empty); } // 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); // Merge the parent web part properties definition with the widget properties definition string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); // Create the FormInfo for the current widget properties definition FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, zoneType, widgetProperties, true); DataRow dr = null; if (fi != null) { // Get data rows with required columns dr = PortalHelper.CombineWithDefaultValues(fi, wi); // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); } // Save inline widget script script = PortalHelper.GetAddInlineWidgetScript(wi, dr, fi.GetFields(true, true), Enumerable.Empty <string>()); script += " CloseDialog(false);"; if (!string.IsNullOrEmpty(script)) { // Add to recently used widgets collection MembershipContext.AuthenticatedUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName); } } } return(script); }
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 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> /// Returns form info with webpart properties. /// </summary> /// <param name="wpi">Web part info</param> protected FormInfo GetWebPartProperties(WebPartInfo wpi) { if (wpi != null) { // Before form string before = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before); FormInfo bfi = new FormInfo(before); // After form string after = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After); FormInfo afi = new FormInfo(after); // Add general category to first items in webpart without category string properties = FormHelper.EnsureDefaultCategory(wpi.WebPartProperties, GetString("general.general")); return PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName, properties, bfi, afi, true); } return null; }
/// <summary> /// Sets check out/in/undo panel /// </summary> protected void SetCheckPanel(WebPartLayoutInfo mwpli) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); WebPartLayoutInfo wpli = mwpli; if (wpi != null) { if (wpli == null) { wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wpi.WebPartName, LayoutCodeName); } } if (wpli != null) { this.pnlCheckOutInfo.Visible = true; if (wpli.WebPartLayoutCheckedOutByUserID > 0) { etaCode.ReadOnly = true; etaCSS.ReadOnly = true; string username = null; UserInfo ui = UserInfoProvider.GetUserInfo(wpli.WebPartLayoutCheckedOutByUserID); if (ui != null) { username = HTMLHelper.HTMLEncode(ui.FullName); } plcCheckOut.Visible = false; // Checked out by current machine if (wpli.WebPartLayoutCheckedOutMachineName.ToLower() == HTTPHelper.MachineName.ToLower()) { this.plcCheckIn.Visible = true; this.lblCheckOutInfo.Text = String.Format(GetString("WebPartEditLayoutEdit.CheckedOut"), Server.MapPath(wpli.WebPartLayoutCheckedOutFilename)); } else { this.lblCheckOutInfo.Text = String.Format(GetString("WebPartEditLayoutEdit.CheckedOutOnAnotherMachine"), wpli.WebPartLayoutCheckedOutMachineName, username); } if (CMSContext.CurrentUser.IsGlobalAdministrator) { this.plcUndoCheckOut.Visible = true; } } else { wpi = WebPartInfoProvider.GetWebPartInfo(wpli.WebPartLayoutWebPartID); if (wpi != null) { this.lblCheckOutInfo.Text = String.Format(GetString("WebPartEditLayoutEdit.CheckOutInfo"), Server.MapPath(WebPartLayoutInfoProvider.GetWebPartLayoutUrl(wpi.WebPartName, wpli.WebPartLayoutCodeName, null))); this.plcCheckOut.Visible = true; this.plcCheckIn.Visible = false; this.plcUndoCheckOut.Visible = false; } } } }
protected void btnSaveAll_Click(object sender, EventArgs e) { try { // Save all the document transformations DataSet ds = DataClassInfoProvider.GetAllDataClass(); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { int classId = ValidationHelper.GetInteger(dr["ClassID"], 0); string className = ValidationHelper.GetString(dr["ClassName"], ""); bool isDocumentType = ValidationHelper.GetBoolean(dr["ClassIsDocumentType"], false); if (isDocumentType) { ProcessTransformations(classId, className); } } } // Save all the custom table transformations ds = DataClassInfoProvider.GetCustomTableClasses(null, null, 0, "ClassID,ClassName,ClassIsCustomTable"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { int classId = ValidationHelper.GetInteger(dr["ClassID"], 0); string className = ValidationHelper.GetString(dr["ClassName"], ""); bool isCustomTable = ValidationHelper.GetBoolean(dr["ClassIsCustomTable"], false); if (isCustomTable) { ProcessTransformations(classId, className); } } } // Save all the layouts ds = LayoutInfoProvider.GetAllLayouts(); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string layoutName = ValidationHelper.GetString(dr["LayoutCodeName"], ""); string layoutCode = ValidationHelper.GetString(dr["LayoutCode"], ""); int checkedOutByUserId = ValidationHelper.GetInteger(dr["LayoutCheckedOutByUserID"], 0); string checkedOutMachineName = ValidationHelper.GetString(dr["LayoutCheckedOutMachineName"], ""); if ((checkedOutByUserId == 0) || (checkedOutMachineName.ToLower() != HTTPHelper.MachineName.ToLower())) { string filename = LayoutInfoProvider.GetLayoutUrl(layoutName, null); // Prepare the code string code = layoutCode; code = LayoutInfoProvider.AddLayoutDirectives(code); SiteManagerFunctions.SaveCodeFile(filename, code); } } } // Save all the page template layouts ds = PageTemplateInfoProvider.GetAllTemplates(); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string templateName = ValidationHelper.GetString(dr["PageTemplateCodeName"], ""); string templateLayout = ValidationHelper.GetString(dr["PageTemplateLayout"], ""); bool isReusable = ValidationHelper.GetBoolean(dr["PageTemplateIsReusable"], false); int checkedOutByUserId = ValidationHelper.GetInteger(dr["PageTemplateLayoutCheckedOutByUserID"], 0); string checkedOutMachineName = ValidationHelper.GetString(dr["PageTemplateLayoutCheckedOutMachineName"], ""); bool isPortalTemplate = ValidationHelper.GetBoolean(dr["PageTemplateIsPortal"], false); string pageTemplateType = ValidationHelper.GetString(dr["PageTemplateType"], ""); bool isDashboard = pageTemplateType.Equals(PageTemplateInfoProvider.GetPageTemplateTypeCode(PageTemplateTypeEnum.Dashboard)); if ((isPortalTemplate || isDashboard) && !String.IsNullOrEmpty(templateLayout) && ((checkedOutByUserId == 0) || (checkedOutMachineName.ToLower() != HTTPHelper.MachineName.ToLower()))) { string filename = null; if (isReusable) { filename = PageTemplateInfoProvider.GetLayoutUrl(templateName, null); } else { filename = PageTemplateInfoProvider.GetAdhocLayoutUrl(templateName, null); } // Prepare the code string code = templateLayout; code = LayoutInfoProvider.AddLayoutDirectives(code); SiteManagerFunctions.SaveCodeFile(filename, code); } } } // Save all the web part layouts ds = WebPartLayoutInfoProvider.GetWebPartLayouts(null, null); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string webPartLayoutCodeName = ValidationHelper.GetString(dr["WebPartLayoutCodeName"], ""); string webPartLayoutCode = ValidationHelper.GetString(dr["WebPartLayoutCode"], ""); WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(dr["WebPartLayoutWebPartID"], 0)); if (wpi != null) { int checkedOutByUserId = ValidationHelper.GetInteger(dr["WebPartLayoutCheckedOutByUserID"], 0); string checkedOutMachineName = ValidationHelper.GetString(dr["WebPartLayoutCheckedOutMachineName"], ""); if (!String.IsNullOrEmpty(webPartLayoutCode) && ((checkedOutByUserId == 0) || (checkedOutMachineName.ToLower() != HTTPHelper.MachineName.ToLower()))) { // Get layout filename string filename = WebPartLayoutInfoProvider.GetWebPartLayoutUrl(wpi.WebPartName, webPartLayoutCodeName, ""); // Get path to the code file string codeFilePath = URLHelper.GetVirtualPath(filename) + ".cs"; // Get path to the original code behind file string originalCodeFilePath = String.Empty; if (codeFileRegex.IsMatch(webPartLayoutCode, 0)) { originalCodeFilePath = codeFileRegex.Match(webPartLayoutCode).Result("$1"); } // Get original class name string originalClassName = String.Empty; if (inheritsRegex.IsMatch(webPartLayoutCode)) { originalClassName = inheritsRegex.Match(webPartLayoutCode).Result("$1"); } if (codeFileRegex.IsMatch(webPartLayoutCode)) { webPartLayoutCode = codeFileRegex.Replace(webPartLayoutCode, "CodeFile=\"" + codeFilePath + "\""); } if (inheritsRegex.IsMatch(webPartLayoutCode)) { webPartLayoutCode = inheritsRegex.Replace(webPartLayoutCode, "Inherits=\"$1_Web_Deployment\""); } // Read original codefile and change classname string codeFileCode = String.Empty; if (!String.IsNullOrEmpty(originalCodeFilePath) && FileHelper.FileExists(originalCodeFilePath)) { codeFileCode = File.ReadAllText(Server.MapPath(originalCodeFilePath)); codeFileCode = codeFileCode.Replace(originalClassName, originalClassName + "_Web_Deployment"); // Save code file SiteManagerFunctions.SaveCodeFile(filename, webPartLayoutCode); // Save code behind file SiteManagerFunctions.SaveCodeFile(codeFilePath, codeFileCode); } } } } } lblResult.Text = GetString("Deployment.ObjectsSaved"); } catch (Exception ex) { CMS.EventLog.EventLogProvider ep = new CMS.EventLog.EventLogProvider(); ep.LogEvent("System deployment", "E", ex); lblError.Visible = true; lblError.Text = ex.Message; } }
/// <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> /// Save layout code. /// </summary> protected bool SaveData() { // Remove "." due to virtual path provider replacement txtCodeName.Text = txtCodeName.Text.Replace(".", ""); txtDisplayName.Text = txtDisplayName.Text.Trim(); txtCodeName.Text = txtCodeName.Text.Trim(); string errorMessage = new Validator() .NotEmpty(txtCodeName.Text, rfvCodeName.ErrorMessage) .NotEmpty(txtDisplayName.Text, rfvDisplayName.ErrorMessage) .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename")).Result; int webPartId = ValidationHelper.GetInteger(Request.QueryString["webpartId"], 0); WebPartInfo webPartInfo = WebPartInfoProvider.GetWebPartInfo(webPartId); if (webPartInfo == null) { errorMessage = GetString("WebPartEditLayoutEdit.InvalidWebPartID"); } if (errorMessage != String.Empty) { lblError.Text = errorMessage; lblError.Visible = true; return(false); } // Get layout info WebPartLayoutInfo webPartLayoutInfo = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(layoutId); if (webPartLayoutInfo != null) { // Get layout info using its code name - layout code name must be unique DataSet ds = WebPartLayoutInfoProvider.GetWebPartLayouts("WebPartLayoutCodeName = '" + WebPartLayoutInfoProvider.GetWebPartLayoutFullCodeName(webPartInfo.WebPartName, txtCodeName.Text) + "'", null); // Find anything? if (!DataHelper.DataSourceIsEmpty(ds)) { WebPartLayoutInfo temp = new WebPartLayoutInfo(ds.Tables[0].Rows[0]); // Is it the same layout? if ((ds.Tables[0].Rows.Count > 1) || (temp.WebPartLayoutID != webPartLayoutInfo.WebPartLayoutID)) { lblError.Text = String.Format(GetString("WebPartEditLayoutEdit.CodeNameAlreadyExist"), txtCodeName.Text); lblError.Visible = true; return(false); } } webPartLayoutInfo.WebPartLayoutCodeName = txtCodeName.Text; webPartLayoutInfo.WebPartLayoutDisplayName = txtDisplayName.Text; webPartLayoutInfo.WebPartLayoutDescription = txtDescription.Text; if (!webPartLayoutInfo.Generalized.IsCheckedOut) { webPartLayoutInfo.WebPartLayoutCode = etaCode.Text; webPartLayoutInfo.WebPartLayoutCSS = tbCSS.Text; } WebPartLayoutInfoProvider.SetWebPartLayoutInfo(webPartLayoutInfo); // Reload header if changes were saved if (TabMode) { ScriptHelper.RefreshTabHeader(Page, null); } } return(true); }
/// <summary> /// Gets and bulk updates web parts. Called when the "Get and bulk update parts" button is pressed. /// Expects the CreateWebPart method to be run first. /// </summary> private bool GetAndBulkUpdateWebParts() { // Prepare the parameters string where = "WebPartName LIKE N'MyNewWebpart%'"; // Get the data DataSet webparts = WebPartInfoProvider.GetWebParts().Where(where); if (!DataHelper.DataSourceIsEmpty(webparts)) { // Loop through the individual items foreach (DataRow webpartDr in webparts.Tables[0].Rows) { // Create object from DataRow WebPartInfo modifyWebpart = new WebPartInfo(webpartDr); // Update the properties modifyWebpart.WebPartDisplayName = modifyWebpart.WebPartDisplayName.ToUpper(); // Save the changes WebPartInfoProvider.SetWebPartInfo(modifyWebpart); } return true; } return false; }
/// <summary> /// Generate editor table. /// </summary> public void GenerateEditor() { FormInfo fi = null; // Call handlers if (OnEditorLoaded != null) { fi = OnEditorLoaded(); } else { // Get parent web part info WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(ParentWebPartID); if (wpi != null) { // Create form info and load xml definition fi = PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); } else { fi = new FormInfo(SourceXMLDefinition); } } if (fi != null) { dr = fi.GetDataRow(false); // Get definition elements var infos = fi.GetFormElements(true, false); // create table part Literal table1 = new Literal(); pnlEditor.Controls.Add(table1); table1.Text = "<table cellpadding=\"3\">"; // Hashtable counter int i = 0; bool categoryExists = false; // Check all items in object array foreach (object contrl in infos) { // Generate row for form category if (contrl is FormCategoryInfo) { // Load category info FormCategoryInfo fci = contrl as FormCategoryInfo; if (fci != null) { CreateCategory(fci.CategoryCaption); categoryExists = true; } } else { // Ensure the default category if (!categoryExists) { CreateCategory(GetString("General.General")); categoryExists = true; } // Get form field info FormFieldInfo ffi = contrl as FormFieldInfo; if (ffi != null) { CreateField(ffi, ref i); } } } // End table part Literal table6 = new Literal(); pnlEditor.Controls.Add(table6); table6.Text = "</table>"; } }
/// <summary> /// Generate documentation page. /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); // Get current resolver resolver = CMSContext.CurrentResolver.CreateContextChild(); plImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png"); minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png"); webPartId = QueryHelper.GetString("webPartId", String.Empty); if (webPartId != String.Empty) { wpi = WebPartInfoProvider.GetWebPartInfo(webPartId); } string aliasPath = QueryHelper.GetString("aliaspath", String.Empty); // 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 is in query create widget documentation widgetID = QueryHelper.GetString("widgetId", String.Empty); if (widgetID != String.Empty) { // Get widget from instance string zoneId = QueryHelper.GetString("zoneid", String.Empty); Guid instanceGuid = QueryHelper.GetGuid("instanceGuid", Guid.Empty); int templateID = QueryHelper.GetInteger("templateID", 0); bool newItem = QueryHelper.GetBoolean("isNew", false); bool isInline = QueryHelper.GetBoolean("Inline", false); PageInfo pi = null; try { // Load page info from alias path and page template pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateID); } 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, widgetID); // 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 (!CMSContext.CurrentUser.UserSiteManagerAdmin) { RedirectToAccessDenied(GetString("attach.actiondenied")); } } // If wi is still null (new item f.e.) if (wi == null) { // Try to get widget info directly by ID if (!newItem) { wi = WidgetInfoProvider.GetWidgetInfo(widgetID); } else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetID, 0)); } } } String itemDescription = String.Empty; String itemType = String.Empty; String itemDisplayName = String.Empty; String itemDocumentation = String.Empty; int itemID = 0; // Check whether webpart was found if (wpi != null) { itemDescription = wpi.WebPartDescription; itemType = PortalObjectType.WEBPART; itemID = wpi.WebPartID; itemDisplayName = wpi.WebPartDisplayName; itemDocumentation = wpi.WebPartDocumentation; } // Or widget was found else if (wi != null) { itemDescription = wi.WidgetDescription; itemType = PortalObjectType.WIDGET; itemID = wi.WidgetID; itemDisplayName = wi.WidgetDisplayName; itemDocumentation = wi.WidgetDocumentation; } if ((wpi != null) || (wi != null)) { // Get WebPart (widget) image DataSet ds = MetaFileInfoProvider.GetMetaFiles(itemID, itemType); // Set image url of exists if (!DataHelper.DataSourceIsEmpty(ds)) { MetaFileInfo mtfi = new MetaFileInfo(ds.Tables[0].Rows[0]); if (mtfi != null) { if (mtfi.MetaFileImageWidth > 385) { imgTeaser.Width = 385; } imgTeaser.ImageUrl = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=" + mtfi.MetaFileGUID.ToString()); } } else { // Set default image imgTeaser.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/imagenotavailable.png"); } // Additional image information imgTeaser.ToolTip = HTMLHelper.HTMLEncode(itemDisplayName); imgTeaser.AlternateText = HTMLHelper.HTMLEncode(itemDisplayName); // Set description of webpart ltlDescription.Text = HTMLHelper.HTMLEncode(itemDescription); // Get description from parent weboart if webpart is inherited if ((wpi != null) && ((wpi.WebPartDescription == null || 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); } } }
/// <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) { 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(); } }
protected void Page_Load(object sender, EventArgs e) { mEditedObject = UIContext.EditedObject as BaseInfo; // If saved is found in query string if (!RequestHelper.IsPostBack() && (QueryHelper.GetInteger("saved", 0) == 1)) { ShowChangesSaved(); } string before; string after; string objectType = UIContextHelper.GetObjectType(UIContext); switch (objectType.ToLowerCSafe()) { case "cms.webpart": mDefaultValueColumName = "WebPartDefaultValues"; before = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.Before); after = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.After); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); WebPartInfo wi = mEditedObject as WebPartInfo; // If inherited web part load parent properties if (wi.WebPartParentID > 0) { WebPartInfo parentInfo = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentInfo != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(parentInfo.WebPartProperties, wi.WebPartProperties); } } else { mWebPartProperties = wi.WebPartProperties; } break; case "cms.widget": before = PortalFormHelper.LoadProperties("Widget", "Before.xml"); after = PortalFormHelper.LoadProperties("Widget", "After.xml"); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); mDefaultValueColumName = "WidgetDefaultValues"; WidgetInfo wii = mEditedObject as WidgetInfo; if (wii != null) { WebPartInfo wiiWp = WebPartInfoProvider.GetWebPartInfo(wii.WidgetWebPartID); if (wiiWp != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(wiiWp.WebPartProperties, wii.WidgetProperties); } } break; } // Get the web part info if (mEditedObject != null) { String defVal = ValidationHelper.GetString(mEditedObject.GetValue(mDefaultValueColumName), string.Empty); mDefaultSet = LoadDefaultValuesXML(mDefaultSet); fieldEditor.Mode = FieldEditorModeEnum.SystemWebPartProperties; fieldEditor.FormDefinition = FormHelper.MergeFormDefinitions(mDefaultSet, defVal); fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; fieldEditor.OriginalFormDefinition = mDefaultSet; fieldEditor.WebPartId = mEditedObject.Generalized.ObjectID; } ScriptHelper.HideVerticalTabs(Page); }
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 != String.Empty) { 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, WidgetID); // 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 (!CMSContext.CurrentUser.UserSiteManagerAdmin) { RedirectToAccessDenied(GetString("attach.actiondenied")); } } // If wi is still null (new item f.e.) if (wi == null) { // Try to get widget info directly by ID if (!IsNew) { wi = WidgetInfoProvider.GetWidgetInfo(WidgetID); } else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetID, 0)); } } } String itemDescription = String.Empty; String itemType = String.Empty; String itemDisplayName = String.Empty; String itemDocumentation = String.Empty; int itemID = 0; // Check whether webpart was found if (wpi != null) { itemDescription = wpi.WebPartDescription; itemType = PortalObjectType.WEBPART; itemID = wpi.WebPartID; itemDisplayName = wpi.WebPartDisplayName; itemDocumentation = wpi.WebPartDocumentation; } // Or widget was found else if (wi != null) { itemDescription = wi.WidgetDescription; itemType = PortalObjectType.WIDGET; itemID = wi.WidgetID; itemDisplayName = wi.WidgetDisplayName; itemDocumentation = wi.WidgetDocumentation; } if ((wpi != null) || (wi != null)) { // Get WebPart (widget) image DataSet ds = MetaFileInfoProvider.GetMetaFiles(itemID, itemType); // Set image url of exists if (!DataHelper.DataSourceIsEmpty(ds)) { MetaFileInfo mtfi = new MetaFileInfo(ds.Tables[0].Rows[0]); if (mtfi != null) { if (mtfi.MetaFileImageWidth > 385) { imgTeaser.Width = 385; } imgTeaser.ImageUrl = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=" + mtfi.MetaFileGUID.ToString()); } } else { // Set default image imgTeaser.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/imagenotavailable.png"); } // Additional image information imgTeaser.ToolTip = HTMLHelper.HTMLEncode(itemDisplayName); imgTeaser.AlternateText = HTMLHelper.HTMLEncode(itemDisplayName); // 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 = @" $j(document.body).ready(initializeResize); function initializeResize () { resizeareainternal(); $j(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 = $j('.PageFooterLine'); panel.style.height = (height - footer.outerHeight() - panel.offsetTop) +'px'; }"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "mainScript", ScriptHelper.GetScript(script)); string[,] tabs = new string[4, 4]; tabs[0, 0] = GetString("webparts.documentation"); tabs[1, 0] = GetString("general.properties"); tabControlElem.Tabs = tabs; tabControlElem.UsePostback = true; // Disable caching Response.Cache.SetNoStore(); base.OnLoad(e); }
protected override bool Insert() { WebPartInfo info = new WebPartInfo(); info.WebPartCategoryId = ValidationHelper.GetInteger(drlCategory.SelectedValue, 0); info.Name = txtName.Text; info.FolderPath = txtFolderPath.Text; info.Description = txtDescription.Text; info.IsDeleted = false; string guid = Guid.NewGuid().ToString(); string fileName = guid + "_" + flpScreenshot.FileName; flpScreenshot.SaveAs(Server.MapPath("~/userfiles/webparts/") + fileName); info.Screenshot = fileName; Object idObject = _webPartProvider.Create(info, ErrorList); RedrictUrl = "/administrator/webpart/webparts.aspx?categoryid=" + drlCategory.SelectedValue; return CheckErrors(); }
protected void Page_Load(object sender, EventArgs e) { // Security test if (!CMSContext.CurrentUser.UserSiteManagerAdmin) { RedirectToAccessDenied(GetString("attach.actiondenied")); } // Add link to external stylesheet CSSHelper.RegisterCSSLink(this, "Default", "/CMSDesk.css"); // Get current resolver resolver = CMSContext.CurrentResolver.CreateContextChild(); DataSet ds = null; DataSet cds = null; // Check init settings bool allWidgets = QueryHelper.GetBoolean("allWidgets", false); bool allWebParts = QueryHelper.GetBoolean("allWebparts", false); // Get webpart (widget) from querystring - only if no allwidget or allwebparts set bool isWebpartInQuery = false; bool isWidgetInQuery = false; String webpartQueryParam = String.Empty; //If not show all widgets or webparts - check if any widget or webpart is present if ((!allWidgets) && (!allWebParts)) { webpartQueryParam = QueryHelper.GetString("webpart", ""); if (!string.IsNullOrEmpty(webpartQueryParam)) { isWebpartInQuery = true; } else { webpartQueryParam = QueryHelper.GetString("widget", ""); if (!string.IsNullOrEmpty(webpartQueryParam)) { isWidgetInQuery = true; } } } // Set development option if is required if (QueryHelper.GetString("details", "0") == "1") { development = true; } // Generate all webparts if (allWebParts) { // Get all webpart categories cds = WebPartCategoryInfoProvider.GetAllCategories(); } // Generate all widgets else if (allWidgets) { // Get all widget categories cds = WidgetCategoryInfoProvider.GetWidgetCategories(String.Empty, String.Empty, 0, String.Empty); } // Generate single webpart else if (isWebpartInQuery) { // Split weparts string[] webparts = webpartQueryParam.Split(';'); if (webparts.Length > 0) { string webpartWhere = SqlHelperClass.GetWhereCondition("WebpartName", webparts); ds = WebPartInfoProvider.GetWebParts(webpartWhere, null); // If any webparts found if (!DataHelper.DataSourceIsEmpty(ds)) { StringBuilder categoryWhere = new StringBuilder(""); foreach (DataRow dr in ds.Tables[0].Rows) { categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ","); } string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")"; cds = WebPartCategoryInfoProvider.GetCategories(ctWhere, null); } } } // Generate single widget else if (isWidgetInQuery) { string[] widgets = webpartQueryParam.Split(';'); if (widgets.Length > 0) { string widgetsWhere = SqlHelperClass.GetWhereCondition("WidgetName", widgets); ds = WidgetInfoProvider.GetWidgets(widgetsWhere, null, 0, String.Empty); } if (!DataHelper.DataSourceIsEmpty(ds)) { StringBuilder categoryWhere = new StringBuilder(""); foreach (DataRow dr in ds.Tables[0].Rows) { categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ","); } string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")"; cds = WidgetCategoryInfoProvider.GetWidgetCategories(ctWhere, null, 0, String.Empty); } } if (allWidgets || isWidgetInQuery) { documentationTitle = "Kentico CMS Widgets"; Page.Header.Title = "Widgets documentation"; } if (!allWebParts && !allWidgets && !isWebpartInQuery && !isWidgetInQuery) { pnlContent.Visible = false; pnlInfo.Visible = true; } // Check whether at least one category is present if (!DataHelper.DataSourceIsEmpty(cds)) { string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty; // Loop through all web part categories foreach (DataRow cdr in cds.Tables[0].Rows) { // Get all webpart in the categories if (allWebParts) { ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"])); } // Get all widgets in the category else if (allWidgets) { int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]); ds = WidgetInfoProvider.GetWidgets("WidgetCategoryID = " + categoryID.ToString(), null, 0, null); } // Check whether current category contains at least one webpart if (!DataHelper.DataSourceIsEmpty(ds)) { // Generate category name code menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />"; // Loop through all web web parts in categories foreach (DataRow dr in ds.Tables[0].Rows) { // Init isImagePresent = false; undocumentedProperties = 0; documentation = 0; // Webpart (Widget) information string itemDisplayName = String.Empty; string itemDescription = String.Empty; string itemDocumentation = String.Empty; string itemType = String.Empty; int itemID = 0; WebPartInfo wpi = null; WidgetInfo wi = null; // Set webpart info if ((isWebpartInQuery) || (allWebParts)) { wpi = new WebPartInfo(dr); if (wpi != null) { itemDisplayName = wpi.WebPartDisplayName; itemDescription = wpi.WebPartDescription; itemDocumentation = wpi.WebPartDocumentation; itemID = wpi.WebPartID; itemType = PortalObjectType.WEBPART; if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0)) { wpi = null; } } } // Set widget info else if ((isWidgetInQuery) || (allWidgets)) { wi = new WidgetInfo(dr); if (wi != null) { itemDisplayName = wi.WidgetDisplayName; itemDescription = wi.WidgetDescription; itemDocumentation = wi.WidgetDocumentation; itemType = PortalObjectType.WIDGET; itemID = wi.WidgetID; if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0)) { wi = null; } } } // Check whether web part (widget) exists if ((wpi != null) || (wi != null)) { // Link GUID Guid mguid = Guid.NewGuid(); // Whether description is present in webpart bool isDescription = false; // Image url string wimgurl = GetItemImage(itemID, itemType); // Set description text string descriptionText = itemDescription; // Parent webpart info WebPartInfo pwpi = null; // If webpart look for parent's description and documentation if (wpi != null) { // Get parent description if webpart is inherited if (wpi.WebPartParentID > 0) { pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null) { if ((descriptionText == null || descriptionText.Trim() == "")) { // Set description from parent descriptionText = pwpi.WebPartDescription; } // Set documentation text from parent if WebPart is inherited if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == "")) { itemDocumentation = pwpi.WebPartDocumentation; if (!String.IsNullOrEmpty(itemDocumentation)) { documentation = 2; } } } } } // Set description as present if (descriptionText.Trim().Length > 0) { isDescription = true; } // Generate HTML for menu and content menu += " <a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a> "; // Generate webpart header content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + " > " + HTMLHelper.HTMLEncode(itemDisplayName) + "</a></h1></td><td style=\"text-align:right;\"> <a href=\"#top\" class=\"noprint\">top</a></td></tr></table>"; // Generate WebPart content content += @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;""> <tr> <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;""> <img src=""" + wimgurl + @""" alt=""imageTeaser""> </td> <td style=""width: 50%; vertical-align: center;text-align:center;"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(descriptionText)) + @" </td> </tr> </table>"; // Properties content content += "<div class=\"DocumentationWebPartsProperties\">"; // Generate content if (wpi != null) { GenerateDocContent(CreateFormInfo(wpi)); } else if (wi != null) { GenerateDocContent(CreateFormInfo(wi)); } // Close content area content += "</div>"; // Generate documentation text content content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" + DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") + "</div>"; // Set page break tag for print content += "<br /><p style=\"page-break-after: always;width:100%\"> </p><hr class=\"noprint\" />"; // If development is required - highlight missing description, images and doc. text if (development) { // Check image if (!isImagePresent) { menu += "<span style=\"color:Brown;\">image </span>"; } // Check properties if (undocumentedProperties > 0) { menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ") </span>"; } // Check properties if (!isDescription) { menu += "<span style=\"color:#37627F;\">description </span>"; } // Check documentation text if (String.IsNullOrEmpty(itemDocumentation)) { documentation = 1; } switch (documentation) { // Display information about missing documentation case 1: menu += "<span style=\"color:Green;\">documentation </span>"; break; // Display information about inherited documentation case 2: menu += "<span style=\"color:Green;\">documentation (inherited) </span>"; break; } } menu += "<br />"; } } } } } ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\"> </p><hr class=\"noprint\" />" + content; }
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> /// 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(); }
protected void Page_Load(object sender, EventArgs e) { // Register scripts ScriptHelper.RegisterJQuery(Page); RegisterExportScript(); treeElem.UseGlobalSettings = true; treeWireframes.UseGlobalSettings = true; // Images imgNewCategory.ImageUrl = GetImageUrl("Objects/CMS_WebPartCategory/add.png"); imgNewWebPart.ImageUrl = GetImageUrl("Objects/CMS_WebPart/add.png"); imgDeleteItem.ImageUrl = GetImageUrl("Objects/CMS_WebPart/delete.png"); imgExportObject.ImageUrl = GetImageUrl("Objects/CMS_WebPart/export.png"); imgCloneWebpart.ImageUrl = GetImageUrl("CMSModules/CMS_WebParts/clone.png"); // Resource strings lnkDeleteItem.Text = GetString("Development-WebPart_Tree.DeleteItem"); lnkNewCategory.Text = GetString("Development-WebPart_Tree.NewCategory"); lnkNewWebPart.Text = GetString("Development-WebPart_Tree.NewWebPart"); lnkExportObject.Text = GetString("Development-WebPart_Tree.ExportObject"); lnkCloneWebPart.Text = GetString("Development-WebPart_Tree.CloneWebpart"); // Setup menu action scripts lnkNewWebPart.Attributes.Add("onclick", "NewItem('webpart');"); lnkNewCategory.Attributes.Add("onclick", "NewItem('webpartcategory');"); lnkDeleteItem.Attributes.Add("onclick", "DeleteItem();"); lnkExportObject.Attributes.Add("onclick", "ExportObject();"); lnkCloneWebPart.Attributes.Add("onclick", "CloneWebPart();"); // Tooltips lnkDeleteItem.ToolTip = GetString("Development-WebPart_Tree.DeleteItem"); lnkNewCategory.ToolTip = GetString("Development-WebPart_Tree.NewCategory"); lnkNewWebPart.ToolTip = GetString("Development-WebPart_Tree.NewWebPart"); lnkExportObject.ToolTip = GetString("Development-WebPart_Tree.ExportObject"); lnkCloneWebPart.ToolTip = GetString("Development-WebPart_Tree.CloneWebpart"); string script = "var doNotReloadContent = false;\n"; // URLs for menu actions script += "var categoryURL = '" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/Category_Frameset.aspx") + "';\n"; script += "var categoryNewURL = '" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Category.aspx") + "';\n"; script += "var webpartURL = '" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Frameset.aspx") + "';\n"; script += "var newWebpartURL = '" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_New.aspx") + "';\n"; script += "var cloneURL = '" + URLHelper.ResolveUrl("~/CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?objecttype=cms.webpart") + "';\n"; script += "var doNotReloadContent = false;\n"; // Script for deleting widget or category string delPostback = ControlsHelper.GetPostBackEventReference(Page, "##"); string deleteScript = "function DeleteItem() { \n" + " if ((selectedItemId > 0) && (selectedItemParent > 0) && " + " confirm('" + GetString("general.deleteconfirmation") + "')) {\n " + delPostback.Replace("'##'", "selectedItemType+';'+selectedItemId+';'+selectedItemParent") + ";\n" + "}\n" + "}\n"; script += deleteScript; // Preselect tree item if (!RequestHelper.IsPostBack()) { int categoryId = QueryHelper.GetInteger("categoryid", 0); int webpartId = QueryHelper.GetInteger("webpartid", 0); bool reload = QueryHelper.GetBoolean("reload", false); // Select category if (categoryId > 0) { WebPartCategoryInfo wci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoById(categoryId); if (wci != null) { // If not set explicitly stop reloading of right frame if (!reload) { script += "doNotReloadContent = true;"; } script += SelectAtferLoad(wci.CategoryPath, categoryId, "webpartcategory", wci.CategoryParentID); } } // Select webpart else if (webpartId > 0) { WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webpartId); if (wi != null) { WebPartCategoryInfo wci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoById(wi.WebPartCategoryID); if (wci != null) { // If not set explicitly stop reloading of right frame if (!reload) { script += "doNotReloadContent = true;"; } string path = wci.CategoryPath + "/" + wi.WebPartName; script += SelectAtferLoad(path, webpartId, "webpart", wi.WebPartCategoryID); } } } // Select root by default else { WebPartCategoryInfo wci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("/"); if (wci != null) { script += SelectAtferLoad("/", wci.CategoryID, "webpartcategory", 0); } } } ltlScript.Text += ScriptHelper.GetScript(script); // Special browser class for RTL scrollbars correction pnlSubBox.CssClass = BrowserHelper.GetBrowserClass(); }
/// <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) { // Standard zone webPartInstance = pti.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, true); // 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 ZoneVarianID is not set when the web part was found in a regural zone. ZoneVariantID = 0; } 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); }
/// <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); // Load the zone variants if not loaded yet if (wpzi.ZoneInstanceVariants == null) { wpzi.LoadVariants(); } // Find the correct zone variant 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; } } } }
/// <summary> /// Generates Recently used category to the toolbar. /// </summary> /// <param name="allowFiltering">If true the the Recently used category doesn't take a part in filtering</param> private void RenderRecentlyUsedWebParts(bool allowFiltering) { StringBuilder result = new StringBuilder(); List <WebPartInfo> wpList = new List <WebPartInfo>(); // Get recently used web parts from user settings string[] webParts = currentUser.UserSettings.UserUsedWebParts.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string webPartName in webParts) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webPartName); if (wpi != null) { wpList.Add(wpi); } } // Sort web parts wpList = wpList.OrderBy(x => ResHelper.LocalizeString(x.WebPartDisplayName, prefferedUICultureCode)).ToList(); // Create the category if (webParts.Length > 0) { string categoryName = HTMLHelper.HTMLEncode(ResHelper.GetString("webparts.recentlyusedshort", prefferedUICultureCode)); result.Append(@"<div class=""WPTCat""><h4>"); result.Append(categoryName); if (!allowFiltering) { result.Append(@"<!--__NOFILTER__-->"); } result.Append(@"</h4></div>"); } foreach (WebPartInfo wp in wpList) { // Selector envelope Panel pnlEnvelope = new Panel(); pnlEnvelope.CssClass = "WPTSelectorEnvelope"; pnlEnvelope.ToolTip = @"<div class=""WPTTH"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wp.WebPartDisplayName, prefferedUICultureCode)) + @"</div><div class=""WPTTC"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wp.WebPartDescription, prefferedUICultureCode)) + @"</div>"; // Set the web part id pnlEnvelope.Attributes.Add("data-webpartid", Convert.ToString(wp.WebPartID)); pnlEnvelope.ID = "wpt_env_" + wp.WebPartID; // Ensure that when start dragging then a copy of the original web part item will be created pnlEnvelope.Attributes.Add("data-dragkeepcopy", "1"); pnlEnvelope.Attributes.Add("onmouseover", "wptToggle(this, true);"); pnlEnvelope.Attributes.Add("onmouseout", "wptToggle(this, false);"); // Skip the insert properties dialog when the web part allows this behavior if (wp.WebPartSkipInsertProperties) { pnlEnvelope.Attributes.Add("data-skipdialog", "1"); } // Handle Panel pnlHandle = new Panel(); pnlHandle.CssClass = "WPTHandle"; pnlEnvelope.Controls.Add(pnlHandle); pnlHandle.ID = "wpt_handle_" + wp.WebPartID; // Thumbnail image Literal ltlImage = new Literal(); imageHTML = PortalHelper.GetIconHtml( thumbnailGuid: wp.WebPartThumbnailGUID, iconClass: wp.WebPartIconClass ?? PortalHelper.DefaultWebPartIconClass); ltlImage.Text = imageHTML; pnlHandle.Controls.Add(ltlImage); // Item text Literal ltlItemTxt = new Literal(); ltlItemTxt.Text = @"<div>" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wp.WebPartDisplayName, prefferedUICultureCode)) + "</div>"; pnlHandle.Controls.Add(ltlItemTxt); // Get rendered code of web part item HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(result)); pnlEnvelope.RenderControl(writer); } ltlRecentlyUsedWebParts.Text = result.ToString(); }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Check "read" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Webpart", "Read")) { RedirectToAccessDenied("CMS.Webpart", "Read"); } webpartid = QueryHelper.GetInteger("webpartid", 0); wpi = WebPartInfoProvider.GetWebPartInfo(webpartid); if (wpi != null) { isInherited = (wpi.WebPartParentID > 0); // Initialize master page InitializeMasterPage(); } if (!RequestHelper.IsPostBack()) { InitalizeMenu(); } }
/// <summary> /// Creates new web part. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Validate the text box fields string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result; // Check file name if (!chkGenerateFiles.Checked && radNewWebPart.Checked) { if (errorMessage == String.Empty) { string webpartPath = WebPartInfoProvider.GetWebPartPhysicalPath(FileSystemSelector.Value.ToString()); if (!radInherited.Checked) { errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result; } } } if (errorMessage != String.Empty) { ShowError(HTMLHelper.HTMLEncode(errorMessage)); return; } // Run in transaction using (var tr = new CMSTransactionScope()) { WebPartInfo wi = new WebPartInfo(); // Check if new name is unique WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text); if (webpart != null) { ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text)); return; } string filename = FileSystemSelector.Value.ToString().Trim(); if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/")) { filename = filename.Substring("~/cmswebparts/".Length); } wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim(); wi.WebPartFileName = filename; wi.WebPartName = txtWebPartName.Text.Trim(); wi.WebPartCategoryID = QueryHelper.GetInteger("parentobjectid", 0); wi.WebPartDescription = ""; wi.WebPartDefaultValues = "<form></form>"; // Initialize WebPartType - fill it with the default value wi.WebPartType = wi.WebPartType; // Inherited web part if (radInherited.Checked) { // Check if is selected webpart and isn't category item if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0) { ShowError(GetString("WebPartNew.InheritedCategory")); return; } int parentId = ValidationHelper.GetInteger(webpartSelector.Value, 0); var parent = WebPartInfoProvider.GetWebPartInfo(parentId); if (parent != null) { wi.WebPartType = parent.WebPartType; wi.WebPartResourceID = parent.WebPartResourceID; wi.WebPartSkipInsertProperties = parent.WebPartSkipInsertProperties; } wi.WebPartParentID = parentId; // Create empty default values definition wi.WebPartProperties = "<defaultvalues></defaultvalues>"; } else { // Check if filename was added if (!FileSystemSelector.IsValid()) { ShowError(FileSystemSelector.ValidationError); return; } else { wi.WebPartProperties = "<form></form>"; wi.WebPartParentID = 0; } } // Save the web part WebPartInfoProvider.SetWebPartInfo(wi); if (chkGenerateFiles.Checked && radNewWebPart.Checked) { string physicalFile = WebPartInfoProvider.GetFullPhysicalPath(wi); if (!File.Exists(physicalFile)) { string ascx; string code; string designer; // Write the files try { WebPartInfoProvider.GenerateWebPartCode(wi, null, out ascx, out code, out designer); string folder = Path.GetDirectoryName(physicalFile); // Ensure the folder if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } File.WriteAllText(physicalFile, ascx); File.WriteAllText(physicalFile + ".cs", code); // Designer file if (!String.IsNullOrEmpty(designer)) { File.WriteAllText(physicalFile + ".designer.cs", designer); } } catch (Exception ex) { LogAndShowError("WebParts", "GENERATEFILES", ex, true); return; } } else { ShowError(String.Format(GetString("General.FileExistsPath"), physicalFile)); return; } } // Refresh web part tree ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframee", ScriptHelper.GetScript( "parent.location = '" + UIContextHelper.GetElementUrl("cms.design", "Development.Webparts", false, wi.WebPartID) + "';")); PageBreadcrumbs.Items[1].Text = HTMLHelper.HTMLEncode(wi.WebPartDisplayName); ShowChangesSaved(); plcTable.Visible = false; tr.Commit(); } }
/// <summary> /// 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(); }
protected void Page_Load(object sender, EventArgs e) { this.Title = "WebPart Edit - Properties"; CurrentMaster.BodyClass += " FieldEditorBody"; // get webpart ID webPartId = QueryHelper.GetInteger("webpartid", 0); FieldEditor.Visible = false; // If saved is found in query string if ((!RequestHelper.IsPostBack()) && (QueryHelper.GetInteger("saved", 0) == 1)) { lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); } if (webPartId > 0) { // Get web part info wi = WebPartInfoProvider.GetWebPartInfo(webPartId); // Check if info object exists if (wi != null) { // For inherited webpart display DefaultValue Editor if (wi.WebPartParentID > 0) { FieldEditor.Visible = false; pnlDefaultEditor.Visible = true; DefaultValueEditor1.Visible = true; DefaultValueEditor1.ParentWebPartID = wi.WebPartParentID; if (wi.WebPartParentID > 0) { DefaultValueEditor1.DefaultValueXMLDefinition = wi.WebPartDefaultValues; } else { DefaultValueEditor1.DefaultValueXMLDefinition = wi.WebPartProperties; } // Add handler to DefaultValueEditor1.XMLCreated += new EventHandler(DefaultValueEditor1_XMLCreated); } else { // set fieldeditor FieldEditor.WebPartId = webPartId; FieldEditor.Mode = FieldEditorModeEnum.WebPartProperties; FieldEditor.Visible = true; pnlDefaultEditor.Visible = false; // Check newly created field for widgets update FieldEditor.OnFieldCreated += UpdateWidgetsDefinition; } } } }
/// <summary> /// Creates new web part. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Validate the text box fields string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result; // Check file name if (errorMessage == String.Empty) { string webpartPath = GetWebPartPhysicalPath(FileSystemSelector.Value.ToString()); if (!radInherited.Checked) { errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result; } } if (errorMessage != String.Empty) { lblError.Text = HTMLHelper.HTMLEncode(errorMessage); lblError.Visible = true; return; } WebPartInfo wi = new WebPartInfo(); // Check if new name is unique WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text); if (webpart != null) { lblError.Visible = true; lblError.Text = GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text); return; } string filename = FileSystemSelector.Value.ToString().Trim(); if (filename.ToLower().StartsWith("~/cmswebparts/")) { filename = filename.Substring("~/cmswebparts/".Length); } wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim(); wi.WebPartFileName = filename; wi.WebPartName = txtWebPartName.Text.Trim(); wi.WebPartCategoryID = QueryHelper.GetInteger("parentid", 0); wi.WebPartDescription = ""; wi.WebPartDefaultValues = "<form></form>"; // Inherited webpart if (radInherited.Checked) { // Check if is selected webpart and isn't category item if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0) { lblError.Visible = true; lblError.Text = GetString("WebPartNew.InheritedCategory"); return; } wi.WebPartParentID = ValidationHelper.GetInteger(webpartSelector.Value, 0); // Create empty default values definition wi.WebPartProperties = "<defaultvalues></defaultvalues>"; } else { // Check if filename was added if (!FileSystemSelector.IsValid()) { lblError.Visible = true; lblError.Text = FileSystemSelector.ValidationError; return; } else { wi.WebPartProperties = "<form></form>"; wi.WebPartParentID = 0; } } WebPartInfoProvider.SetWebPartInfo(wi); // Refresh web part tree ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframe", ScriptHelper.GetScript( "parent.frames['webparttree'].location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Tree.aspx") + "?webpartid=" + wi.WebPartID + "');" + "location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Frameset.aspx") + "?webpartid=" + wi.WebPartID + "')" )); pageTitleTabs[1, 0] = HTMLHelper.HTMLEncode(wi.WebPartDisplayName); this.CurrentMaster.Title.Breadcrumbs = pageTitleTabs; lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); plcTable.Visible = false; }
/// <summary> /// Creates web part. Called when the "Create part" button is pressed. /// </summary> private bool CreateWebPart() { // Get parent category for web part WebPartCategoryInfo category = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("MyNewCategory"); if (category != null) { // Create new web part object WebPartInfo newWebpart = new WebPartInfo(); // Set the properties newWebpart.WebPartDisplayName = "My new web part"; newWebpart.WebPartName = "MyNewWebpart"; newWebpart.WebPartDescription = "This is my new web part."; newWebpart.WebPartFileName = "whatever"; newWebpart.WebPartProperties = "<form></form>"; newWebpart.WebPartCategoryID = category.CategoryID; // Save the web part WebPartInfoProvider.SetWebPartInfo(newWebpart); return true; } return false; }
/// <summary> /// Generates the web part code. /// </summary> /// <param name="wpi">Web part info</param> /// <param name="baseControl">Base control nested within the web part</param> /// <param name="ascx">Returning ASCX code</param> /// <param name="code">Returning code behind</param> /// <param name="designer">Returning designer file</param> public static void GenerateWebPartCode(WebPartInfo wpi, string baseControl, out string ascx, out string code, out string designer) { code = ""; ascx = ""; designer = ""; if (wpi != null) { string templateFile = HttpContext.Current.Server.MapPath("~/App_Data/CodeTemplates/WebPart"); // Generate the ASCX ascx = File.ReadAllText(templateFile + ".ascx.template"); // Prepare the path string path = URLHelper.UnResolveUrl(WebPartInfoProvider.GetWebPartUrl(wpi), SettingsKeyProvider.ApplicationPath); // Prepare the class name string className = path.Trim('~', '/'); if (className.EndsWithCSafe(".ascx")) { className = className.Substring(0, className.Length - 5); } className = ValidationHelper.GetIdentifier(className, "_"); ascx = Regex.Replace(ascx, "(Inherits)=\"[^\"]+\"", "$1=\"" + className + "\""); // Replace the code file / code behind bool webApp = CMSContext.IsWebApplication; string fileAttr = "CodeFile"; //if (webApp) //{ // fileAttr = "CodeBehind"; //} ascx = Regex.Replace(ascx, "(CodeFile|CodeBehind)=\"[^\"]+\"", fileAttr + "=\"" + path + ".cs\""); // Generate the code code = File.ReadAllText(templateFile + ".ascx.cs.template"); code = Regex.Replace(code, "( class\\s+)[^\\s]+", "$1" + className); // Prepare the properties FormInfo fi = new FormInfo(wpi.WebPartProperties); StringBuilder sbInit = new StringBuilder(); string propertiesCode = CodeGenerator.GetPropertiesCode(fi, true, baseControl, sbInit, true); // Replace in code code = code.Replace("// ##PROPERTIES##", propertiesCode); code = code.Replace("// ##SETUP##", sbInit.ToString()); // Generate the designer if (webApp) { designer = File.ReadAllText(templateFile + ".ascx.designer.cs.template"); designer = Regex.Replace(designer, "( class\\s+)[^\\s]+", "$1" + className); } } }
protected void Page_Load(object sender, EventArgs e) { // Security test if (!CMSContext.CurrentUser.UserSiteManagerAdmin) { RedirectToAccessDenied(GetString("attach.actiondenied")); } // Add link to external stylesheet CSSHelper.RegisterCSSLink(this, "~/App_Themes/Default/CMSDesk.css"); // Get current resolver resolver = CMSContext.CurrentResolver.CreateContextChild(); DataSet ds = null; DataSet cds = null; // Check init settings bool allWidgets = QueryHelper.GetBoolean("allWidgets", false); bool allWebParts = QueryHelper.GetBoolean("allWebparts", false); // Get webpart (widget) from querystring - only if no allwidget or allwebparts set bool isWebpartInQuery = false; bool isWidgetInQuery = false; String webpartQueryParam = String.Empty; //If not show all widgets or webparts - check if any widget or webpart is present if ((!allWidgets) && (!allWebParts)) { webpartQueryParam = QueryHelper.GetString("webpart", ""); if (!string.IsNullOrEmpty(webpartQueryParam)) { isWebpartInQuery = true; } else { webpartQueryParam = QueryHelper.GetString("widget", ""); if (!string.IsNullOrEmpty(webpartQueryParam)) { isWidgetInQuery = true; } } } // Set development option if is required if (QueryHelper.GetString("details", "0") == "1") { development = true; } // Generate all webparts if (allWebParts) { // Get all webpart categories cds = WebPartCategoryInfoProvider.GetAllCategories(); } // Generate all widgets else if (allWidgets) { // Get all widget categories cds = WidgetCategoryInfoProvider.GetWidgetCategories(String.Empty, String.Empty, 0, String.Empty); } // Generate single webpart else if (isWebpartInQuery) { // Split weparts string[] webparts = webpartQueryParam.Split(';'); if (webparts.Length > 0) { string webpartWhere = SqlHelperClass.GetWhereCondition("WebpartName", webparts); ds = WebPartInfoProvider.GetWebParts(webpartWhere, null); // If any webparts found if (!DataHelper.DataSourceIsEmpty(ds)) { StringBuilder categoryWhere = new StringBuilder(""); foreach (DataRow dr in ds.Tables[0].Rows) { categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ","); } string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")"; cds = WebPartCategoryInfoProvider.GetCategories(ctWhere, null); } } } // Generate single widget else if (isWidgetInQuery) { string[] widgets = webpartQueryParam.Split(';'); if (widgets.Length > 0) { string widgetsWhere = SqlHelperClass.GetWhereCondition("WidgetName", widgets); ds = WidgetInfoProvider.GetWidgets(widgetsWhere, null, 0, String.Empty); } if (!DataHelper.DataSourceIsEmpty(ds)) { StringBuilder categoryWhere = new StringBuilder(""); foreach (DataRow dr in ds.Tables[0].Rows) { categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ","); } string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")"; cds = WidgetCategoryInfoProvider.GetWidgetCategories(ctWhere, null, 0, String.Empty); } } if (allWidgets || isWidgetInQuery) { documentationTitle = "Kentico CMS Widgets"; Page.Header.Title = "Widgets documentation"; } if (!allWebParts && !allWidgets && !isWebpartInQuery && !isWidgetInQuery) { pnlContent.Visible = false; pnlInfo.Visible = true; } // Check whether at least one category is present if (!DataHelper.DataSourceIsEmpty(cds)) { string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty; // Loop through all web part categories foreach (DataRow cdr in cds.Tables[0].Rows) { // Get all webpart in the categories if (allWebParts) { ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"])); } // Get all widgets in the category else if (allWidgets) { int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]); ds = WidgetInfoProvider.GetWidgets("WidgetCategoryID = " + categoryID.ToString(), null, 0, null); } // Check whether current category contains at least one webpart if (!DataHelper.DataSourceIsEmpty(ds)) { // Generate category name code menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />"; // Loop through all web web parts in categories foreach (DataRow dr in ds.Tables[0].Rows) { // Init isImagePresent = false; undocumentedProperties = 0; documentation = 0; // Webpart (Widget) information string itemDisplayName = String.Empty; string itemDescription = String.Empty; string itemDocumentation = String.Empty; string itemType = String.Empty; int itemID = 0; WebPartInfo wpi = null; WidgetInfo wi = null; // Set webpart info if ((isWebpartInQuery) || (allWebParts)) { wpi = new WebPartInfo(dr); if (wpi != null) { itemDisplayName = wpi.WebPartDisplayName; itemDescription = wpi.WebPartDescription; itemDocumentation = wpi.WebPartDocumentation; itemID = wpi.WebPartID; itemType = PortalObjectType.WEBPART; if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0)) { wpi = null; } } } // Set widget info else if ((isWidgetInQuery) || (allWidgets)) { wi = new WidgetInfo(dr); if (wi != null) { itemDisplayName = wi.WidgetDisplayName; itemDescription = wi.WidgetDescription; itemDocumentation = wi.WidgetDocumentation; itemType = PortalObjectType.WIDGET; itemID = wi.WidgetID; if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0)) { wi = null; } } } // Check whether web part (widget) exists if ((wpi != null) || (wi != null)) { // Link GUID Guid mguid = Guid.NewGuid(); // Whether description is present in webpart bool isDescription = false; // Image url string wimgurl = GetItemImage(itemID, itemType); // Set description text string descriptionText = itemDescription; // Parent webpart info WebPartInfo pwpi = null; // If webpart look for parent's description and documentation if (wpi != null) { // Get parent description if webpart is inherited if (wpi.WebPartParentID > 0) { pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID); if (pwpi != null) { if ((descriptionText == null || descriptionText.Trim() == "")) { // Set description from parent descriptionText = pwpi.WebPartDescription; } // Set documentation text from parent if WebPart is inherited if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == "")) { itemDocumentation = pwpi.WebPartDocumentation; if (!String.IsNullOrEmpty(itemDocumentation)) { documentation = 2; } } } } } // Set description as present if (descriptionText.Trim().Length > 0) { isDescription = true; } // Generate HTML for menu and content menu += " <a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a> "; // Generate webpart header content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + " > " + HTMLHelper.HTMLEncode(itemDisplayName) + "</a></h1></td><td style=\"text-align:right;\"> <a href=\"#top\" class=\"noprint\">top</a></td></tr></table>"; // Generate WebPart content content += @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;""> <tr> <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;""> <img src=""" + wimgurl + @""" alt=""imageTeaser""> </td> <td style=""width: 50%; vertical-align: center;text-align:center;"">" + HTMLHelper.HTMLEncode(descriptionText) + @" </td> </tr> </table>"; // Properties content content += "<div class=\"DocumentationWebPartsProperties\">"; // Generate content if (wpi != null) { GenerateDocContent(CreateFormInfo(wpi)); } else if (wi != null) { GenerateDocContent(CreateFormInfo(wi)); } // Close content area content += "</div>"; // Generate documentation text content content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" + DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") + "</div>"; // Set page break tag for print content += "<br /><p style=\"page-break-after: always;width:100%\"> </p><hr class=\"noprint\" />"; // If development is required - highlight missing description, images and doc. text if (development) { // Check image if (!isImagePresent) { menu += "<span style=\"color:Brown;\">image </span>"; } // Check properties if (undocumentedProperties > 0) { menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ") </span>"; } // Check properties if (!isDescription) { menu += "<span style=\"color:#37627F;\">description </span>"; } // Check documentation text if (String.IsNullOrEmpty(itemDocumentation)) { documentation = 1; } switch (documentation) { // Display information about missing documentation case 1: menu += "<span style=\"color:Green;\">documentation </span>"; break; // Display information about inherited documentation case 2: menu += "<span style=\"color:Green;\">documentation (inherited) </span>"; break; } } menu += "<br />"; } } } } } ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\"> </p><hr class=\"noprint\" />" + content; }
/// <summary> /// Init event handler. /// </summary> 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> /// Load XML with default values (remove keys already overridden in properties tab). /// </summary> /// <param name="wi">Web part info</param> /// <param name="formDef">String XML definition of default values of webpart</param> private XmlDocument LoadDefaultValuesXML(WebPartInfo wi, string formDef) { // Test if there is any default properties set string properties = "<form></form>"; XmlDocument xmlProperties = new XmlDocument(); // If inherited web part load parent properties if (wi.WebPartParentID > 0) { WebPartInfo parentInfo = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentInfo != null) { properties = parentInfo.WebPartProperties; } } else { properties = wi.WebPartProperties; } xmlProperties.LoadXml(properties); // Load default system xml XmlDocument xmlDefault = new XmlDocument(); xmlDefault.LoadXml(formDef); // Filter overridden properties - remove properties with same name as in system XML XmlNodeList defaultList = xmlDefault.SelectNodes(@"//field"); foreach (XmlNode node in defaultList) { string columnName = node.Attributes["column"].Value.ToString(); XmlNodeList propertiesList = xmlProperties.SelectNodes("//field[@column=\"" + columnName + "\"]"); //This property already set in properties tab if (propertiesList.Count > 0) { node.ParentNode.RemoveChild(node); } } // Filter empty categories XmlNodeList nodes = xmlDefault.DocumentElement.ChildNodes; for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; if (node.Name.ToLowerCSafe() == "category") { // Find next category if (i < nodes.Count - 1) { XmlNode nextNode = nodes[i + 1]; if (nextNode.Name.ToLowerCSafe() == "category") { // Delete actual category node.ParentNode.RemoveChild(node); i--; } } } } // Test if last category is not empty nodes = xmlDefault.DocumentElement.ChildNodes; if (nodes.Count > 0) { XmlNode lastNode = nodes[nodes.Count - 1]; if (lastNode.Name.ToLowerCSafe() == "category") { lastNode.ParentNode.RemoveChild(lastNode); } } return xmlDefault; }
/// <summary> /// Button OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Trim text values txtWebPartName.Text = txtWebPartName.Text.Trim(); txtWebPartDisplayName.Text = txtWebPartDisplayName.Text.Trim(); txtWebPartFileName.Text = txtWebPartFileName.Text.Trim(); // Validate the text box fields string errorMessage = new Validator() .NotEmpty(txtWebPartName.Text, rfvWebPartName.ErrorMessage) .NotEmpty(txtWebPartDisplayName.Text, rfvWebPartDisplayName.ErrorMessage) .IsCodeName(txtWebPartName.Text, GetString("WebPart_Clone.InvalidCodeName")) .Result; // Validate file name if(string.IsNullOrEmpty(errorMessage) && chckCloneWebPartFiles.Checked) { errorMessage = new Validator() .NotEmpty(txtWebPartFileName.Text, rfvWebPartFileName.ErrorMessage) .IsFileName(Path.GetFileName(txtWebPartFileName.Text.Trim('~')), GetString("WebPart_Clone.InvalidFileName")).Result; } // Check if webpart with same name exists if (WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text) != null) { errorMessage = GetString(String.Format("Development-WebPart_Clone.WebPartExists", txtWebPartName.Text)); } // Check if webpart is not cloned to the root category WebPartCategoryInfo wci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("/"); if (wci.CategoryID == ValidationHelper.GetInteger(drpWebPartCategories.SelectedValue, -1)) { errorMessage = GetString("Development-WebPart_Clone.cannotclonetoroot"); } if (errorMessage != "") { lblError.Text = errorMessage; lblError.Visible = true; return; } // get web part info object WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webPartId); if (wi == null) { lblError.Text = GetString("WebPart_Clone.InvalidWebPartID"); lblError.Visible = true; return; } // Create new webpart with all properties from source webpart WebPartInfo nwpi = new WebPartInfo(wi, false); nwpi.WebPartID = 0; nwpi.WebPartGUID = Guid.NewGuid(); // Modify clone info nwpi.WebPartName = txtWebPartName.Text; nwpi.WebPartDisplayName = txtWebPartDisplayName.Text; nwpi.WebPartCategoryID = ValidationHelper.GetInteger(drpWebPartCategories.SelectedValue, -1); if (nwpi.WebPartParentID <= 0) { nwpi.WebPartFileName = txtWebPartFileName.Text; } string path = String.Empty; string filename = String.Empty; string inher = String.Empty; try { // Copy file if needed and webpart is not ihnerited if (chckCloneWebPartFiles.Checked && (wi.WebPartParentID == 0)) { // Get source file path string srcFile = GetWebPartPhysicalPath(wi.WebPartFileName); // Get destination file path string dstFile = GetWebPartPhysicalPath(nwpi.WebPartFileName); // Ensure directory DirectoryHelper.EnsureDiskPath(Path.GetDirectoryName(DirectoryHelper.EnsurePathBackSlash(dstFile)), URLHelper.WebApplicationPhysicalPath); // Check if source and target file path are different if (File.Exists(dstFile)) { throw new Exception(GetString("general.fileexists")); } // Get file name filename = Path.GetFileName(dstFile); // Get path to the partial class name replace string wpPath = nwpi.WebPartFileName; if (!wpPath.StartsWith("~/")) { wpPath = WebPartInfoProvider.WebPartsDirectory + "/" + wpPath.TrimStart('/'); } path = Path.GetDirectoryName(wpPath); inher = path.Replace('\\', '_').Replace('/', '_') + "_" + Path.GetFileNameWithoutExtension(filename).Replace('.', '_'); inher = inher.Trim('~'); inher = inher.Trim('_'); // Read .aspx file, replace classname and save as new file string text = File.ReadAllText(srcFile); File.WriteAllText(dstFile, ReplaceASCX(text, DirectoryHelper.CombinePath(path, filename), inher)); // Read .aspx file, replace classname and save as new file if (File.Exists(srcFile + ".cs")) { text = File.ReadAllText(srcFile + ".cs"); File.WriteAllText(dstFile + ".cs", ReplaceASCXCS(text, inher)); } if (File.Exists(srcFile + ".vb")) { text = File.ReadAllText(srcFile + ".vb"); File.WriteAllText(dstFile + ".vb", ReplaceASCXVB(text, inher)); } // Copy web part subfolder string srcDirectory = srcFile.Remove(srcFile.Length - Path.GetFileName(srcFile).Length) + Path.GetFileNameWithoutExtension(srcFile) + "_files"; if (Directory.Exists(srcDirectory)) { string dstDirectory = dstFile.Remove(dstFile.Length - Path.GetFileName(dstFile).Length) + Path.GetFileNameWithoutExtension(dstFile) + "_files"; if (srcDirectory.ToLower() != dstDirectory.ToLower()) { DirectoryHelper.EnsureDiskPath(srcDirectory, URLHelper.WebApplicationPhysicalPath); DirectoryHelper.CopyDirectory(srcDirectory, dstDirectory); } } } } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; return; } // Add new web part to database WebPartInfoProvider.SetWebPartInfo(nwpi); try { // Get and duplicate all webpart layouts associated to webpart DataSet ds = WebPartLayoutInfoProvider.GetWebPartLayouts(webPartId); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { WebPartLayoutInfo wpli = new WebPartLayoutInfo(dr); wpli.WebPartLayoutID = 0; // Create new record wpli.WebPartLayoutWebPartID = nwpi.WebPartID; // Associate layout to new webpart wpli.WebPartLayoutGUID = Guid.NewGuid(); wpli.WebPartLayoutCheckedOutByUserID = 0; wpli.WebPartLayoutCheckedOutFilename = ""; wpli.WebPartLayoutCheckedOutMachineName = ""; // Replace classname and inherits attribut wpli.WebPartLayoutCode = ReplaceASCX(wpli.WebPartLayoutCode, DirectoryHelper.CombinePath(path, filename), inher); WebPartLayoutInfoProvider.SetWebPartLayoutInfo(wpli); } } // Duplicate associated thumbnail MetaFileInfoProvider.CopyMetaFiles(webPartId, nwpi.WebPartID, PortalObjectType.WEBPART, MetaFileInfoProvider.OBJECT_CATEGORY_THUMBNAIL, null); } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; return; } // Close clone window // Refresh web part tree and select/edit new widget string script = String.Empty; string refreshLink = URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Tree.aspx?webpartid=" + nwpi.WebPartID + "&reload=true"); if (QueryHelper.Contains("reloadAll")) { script += "wopener.parent.parent.frames['webparttree'].location.href ='" + refreshLink + "';"; } else { script = "wopener.location = '" + refreshLink + "';"; } script += "window.close();"; ltlScript.Text = ScriptHelper.GetScript(script); }
/// <summary> /// Loads the web part info /// </summary> private void EnsureWebPartInfo() { if (wpi != null) { return; } if (NestedWebPartID > 0) { // Setup the form for data source wpi = WebPartInfoProvider.GetWebPartInfo(NestedWebPartID); form.Mode = FormModeEnum.Update; return; } if (!IsNewWebPart) { // Get web part by code name wpi = WebPartInfoProvider.GetWebPartInfo(webPartInstance.WebPartType); form.Mode = FormModeEnum.Update; } else { // Web part instance wasn't created yet, get by web part ID wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(WebPartID, 0)); form.Mode = FormModeEnum.Insert; } }
/// <summary> /// Creates new web part. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Validate the text box fields string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result; // Check file name if (errorMessage == String.Empty) { string webpartPath = GetWebPartPhysicalPath(FileSystemSelector.Value.ToString()); if (!radInherited.Checked) { errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result; } } if (errorMessage != String.Empty) { lblError.Text = HTMLHelper.HTMLEncode(errorMessage); lblError.Visible = true; return; } WebPartInfo wi = new WebPartInfo(); // Check if new name is unique WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text); if (webpart != null) { lblError.Visible = true; lblError.Text = GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text); return; } string filename = FileSystemSelector.Value.ToString().Trim(); if (filename.ToLower().StartsWith("~/cmswebparts/")) { filename = filename.Substring("~/cmswebparts/".Length); } wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim(); wi.WebPartFileName = filename; wi.WebPartName = txtWebPartName.Text.Trim(); wi.WebPartCategoryID = QueryHelper.GetInteger("parentid", 0); wi.WebPartDescription = ""; wi.WebPartDefaultValues ="<form></form>"; // Inherited webpart if (radInherited.Checked) { // Check if is selected webpart and isn't category item if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0) { lblError.Visible = true; lblError.Text = GetString("WebPartNew.InheritedCategory"); return; } wi.WebPartParentID = ValidationHelper.GetInteger(webpartSelector.Value, 0); // Create empty default values definition wi.WebPartProperties = "<defaultvalues></defaultvalues>"; } else { // Check if filename was added if (!FileSystemSelector.IsValid()) { lblError.Visible = true; lblError.Text = FileSystemSelector.ValidationError; return; } else { wi.WebPartProperties = "<form></form>"; wi.WebPartParentID = 0; } } WebPartInfoProvider.SetWebPartInfo(wi); // Refresh web part tree ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframe", ScriptHelper.GetScript( "parent.frames['webparttree'].location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Tree.aspx") + "?webpartid=" + wi.WebPartID + "');" + "location.replace('" + URLHelper.ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Frameset.aspx") + "?webpartid=" + wi.WebPartID + "')" )); pageTitleTabs[1, 0] = HTMLHelper.HTMLEncode(wi.WebPartDisplayName); this.CurrentMaster.Title.Breadcrumbs = pageTitleTabs; lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); plcTable.Visible = false; }
protected void Page_Load(object sender, EventArgs e) { Title = "Web part layout properties"; // Get the layout layoutId = QueryHelper.GetInteger("layoutId", 0); wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(layoutId); if (wpli != null) { wpi = WebPartInfoProvider.GetWebPartInfo(wpli.WebPartLayoutWebPartID); } // Init GUI mCheckOut = GetString("WebPartLayout.CheckOut"); mCheckIn = GetString("WebPartLayout.CheckIn"); mUndoCheckOut = GetString("WebPartLayout.DiscardCheckOut"); mSave = GetString("General.Save"); lblDisplayName.Text = GetString("WebPartEditLayoutEdit.lblDisplayName"); lblCodeName.Text = GetString("WebPartEditLayoutEdit.lblCodeName"); lblCode.Text = GetString("WebPartEditLayoutEdit.lblCode"); lblDescription.Text = GetString("WebPartEditLayoutEdit.lblDescription"); rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname"); rfvCodeName.ErrorMessage = GetString("webparteditlayoutedit.rfvcodenamerequired"); LoadData(); this.plcCssLink.Visible = String.IsNullOrEmpty(tbCSS.Text.Trim()); }
protected void Page_Load(object sender, EventArgs e) { StringSafeDictionary <object> decodedProperties = new StringSafeDictionary <object>(); foreach (DictionaryEntry param in properties) { // Decode special CK editor char String str = String.Empty; if (param.Value != null) { str = param.Value.ToString().Replace("%25", "%"); } decodedProperties[param.Key] = HttpUtility.UrlDecode(str); } properties = decodedProperties; string widgetName = ValidationHelper.GetString(properties["name"], String.Empty); // Widget name must be specified if (String.IsNullOrEmpty(widgetName)) { AddErrorWebPart("widgets.invalidname", null); return; } WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetName); if (wi == null) { AddErrorWebPart("widget.failedtoload", null); return; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); if (wpi == null) { return; } //no widgets can be used as inline if (!wi.WidgetForInline) { AddErrorWebPart("widgets.cantbeusedasinline", null); return; } try { FormInfo fi = null; DataRow dr = null; using (var cs = new CachedSection <FormInfo>(ref fi, 1440, (PortalContext.ViewMode == ViewModeEnum.LiveSite), null, "inlinewidgetcontrol", wi.WidgetID, wpi.WebPartID)) { if (cs.LoadData) { // Merge widget and it's parent webpart properties string props = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); // Prepare form WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.Editor; FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType); fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), props, zoneTypeDefinition, true, wi.WidgetDefaultValues); // Apply changed values dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.webpart|byid|" + wpi.WebPartID + "\n" + "cms.widget|byid|" + wi.WidgetID); } cs.Data = fi; } } // Get datarow if (dr == null) { dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); } // Incorporate inline parameters to datarow string publicFields = ";containertitle;container;"; if (wi.WidgetPublicFileds != null) { publicFields += ";" + wi.WidgetPublicFileds.ToLowerCSafe() + ";"; } // Load the widget control string url = null; // Set widget layout WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wi.WidgetLayoutID); if (wpli != null) { // Load specific layout through virtual path url = wpli.Generalized.GetVirtualFileRelativePath(WebPartLayoutInfo.EXTERNAL_COLUMN_CODE, wpli.WebPartLayoutVersionGUID); } else { // Load regularly url = WebPartInfoProvider.GetWebPartUrl(wpi, false); } CMSAbstractWebPart control = (CMSAbstractWebPart)Page.LoadUserControl(url); control.PartInstance = new WebPartInstance(); // Use current page placeholder control.PagePlaceholder = PortalHelper.FindParentPlaceholder(this); // Set all form values to webpart foreach (DataColumn column in dr.Table.Columns) { object value = dr[column]; string columnName = column.ColumnName.ToLowerCSafe(); //Resolve set values by user if (properties.Contains(columnName)) { FormFieldInfo ffi = fi.GetFormField(columnName); if ((ffi != null) && ffi.Visible && ((ffi.DisplayIn == null) || !ffi.DisplayIn.Contains(FormInfo.DISPLAY_CONTEXT_DASHBOARD))) { value = properties[columnName]; } } // Resolve macros in defined in default values if (!String.IsNullOrEmpty(value as string)) { // Do not resolve macros for public fields if (publicFields.IndexOfCSafe(";" + columnName + ";") < 0) { // Check whether current column bool avoidInjection = control.SQLProperties.Contains(";" + columnName + ";"); // Resolve macros MacroSettings settings = new MacroSettings() { AvoidInjection = avoidInjection, }; value = control.ContextResolver.ResolveMacros(value.ToString(), settings); } } control.PartInstance.SetValue(column.ColumnName, value); } control.PartInstance.IsWidget = true; // Load webpart content control.OnContentLoaded(); // Add webpart to controls collection Controls.Add(control); // Handle DisableViewstate setting control.EnableViewState = !control.DisableViewState; } catch (Exception ex) { AddErrorWebPart("widget.failedtoload", ex); } }
/// <summary> /// Returns form info with webpart properties. /// </summary> /// <param name="wpi">Web part info</param> protected FormInfo GetWebPartProperties(WebPartInfo wpi) { if (wpi != null) { // Before form string before = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before); FormInfo bfi = new FormInfo(before); // After form string after = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After); FormInfo afi = new FormInfo(after); // Add general category to first items in webpart without category string properties = wpi.WebPartProperties; if (!string.IsNullOrEmpty(properties) && (!properties.StartsWithCSafe("<form><category", true))) { properties = properties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />"); } return PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName, properties, bfi, afi, true); } return null; }
/// <summary> /// Load XML with default values (remove keys already overridden in properties tab). /// </summary> /// <param name="wi">Web part info</param> /// <param name="formDef">String XML definition of default values of webpart</param> private XmlDocument LoadDefaultValuesXML(WidgetInfo wi, string formDef) { // Test if there is any default properties set string properties = "<form></form>"; if (wi.WidgetProperties != String.Empty) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); if (wpi != null) { properties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); } } XmlDocument xmlProperties = new XmlDocument(); xmlProperties.LoadXml(properties); // Load default system xml XmlDocument xmlDefault = new XmlDocument(); xmlDefault.LoadXml(formDef); // Filter overridden properties - remove properties with same name as in system XML XmlNodeList defaultList = xmlDefault.SelectNodes(@"//field"); foreach (XmlNode node in defaultList) { string columnName = node.Attributes["column"].Value.ToString(); XmlNodeList propertiesList = xmlProperties.SelectNodes("//field[@column=\"" + columnName + "\"]"); //This property already set in properties tab if (propertiesList.Count > 0) { node.ParentNode.RemoveChild(node); } } // Filter empty categories XmlNodeList nodes = xmlDefault.DocumentElement.ChildNodes; for (int i = 0; i < nodes.Count; i++) { XmlNode node = nodes[i]; if (node.Name.ToLowerCSafe() == "category") { // Find next category if (i < nodes.Count - 1) { XmlNode nextNode = nodes[i + 1]; if (nextNode.Name.ToLowerCSafe() == "category") { // Delete actual category node.ParentNode.RemoveChild(node); i--; } } } } // Test if last category is not empty nodes = xmlDefault.DocumentElement.ChildNodes; if (nodes.Count > 0) { XmlNode lastNode = nodes[nodes.Count - 1]; if (lastNode.Name.ToLowerCSafe() == "category") { lastNode.ParentNode.RemoveChild(lastNode); } } return(xmlDefault); }