/// <summary> /// Saves the given DataRow data to the web part properties. /// </summary> /// <param name="form">Form to save</param> /// <param name="pti">Page template instance</param> /// <param name="isLayoutWidget">Indicates whether the edited widget is a layout widget</param> private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti, bool isLayoutWidget) { if (form.Visible && (mWidgetInstance != null)) { // Keep the old ID to check the change of the ID string oldId = mWidgetInstance.ControlID.ToLowerCSafe(); DataRow dr = form.DataRow; foreach (DataColumn column in dr.Table.Columns) { mWidgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()]; mWidgetInstance.SetValue(column.ColumnName, dr[column]); // If name changed, move the content // (This can happen when a user overrides the WidgetControlID property to be visible in the widget properties dialog) if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0) { try { string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe(); // Name changed if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0)) { WidgetIdChanged = true; WidgetId = newId; // Move the document content if present string currentContent = CurrentPageInfo.EditableWebParts[oldId]; if (currentContent != null) { TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); // Move the content in the page info CurrentPageInfo.EditableWebParts[oldId] = null; CurrentPageInfo.EditableWebParts[newId] = currentContent; // Update the document node.SetValue("DocumentContent", CurrentPageInfo.GetContentXml()); DocumentHelper.UpdateDocument(node, mTreeProvider); } // Change the underlying zone names if layout widget if (isLayoutWidget) { string prefix = oldId + "_"; foreach (WebPartZoneInstance zone in pti.WebPartZones) { if (zone.ZoneID.StartsWithCSafe(prefix, true)) { // Change the zone prefix to the new one zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length)); } } } } } catch (Exception ex) { EventLogProvider.LogException("Content", "CHANGEWIDGET", ex); } } } } }
private void DocumentManager_OnSaveData(object sender, DocumentManagerEventArgs e) { EditingForms editingForm = (EditingForms)Convert.ToInt32(drpEditControl.SelectedValue); // Get content to save switch (editingForm) { case EditingForms.TextArea: content = txtAreaContent.Text.Trim(); break; case EditingForms.HTMLEditor: content = htmlContent.ResolvedValue; break; case EditingForms.EditableImage: content = imageContent.GetContent(); break; case EditingForms.TextBox: content = txtContent.Text.Trim(); break; } if (!QueryHelper.GetBoolean("imagesaved", false)) { createNew = !node.DocumentContent.EditableWebParts.Contains(keyName) && !node.DocumentContent.EditableRegions.ContainsKey(keyName); } // Code name string codeName = txtName.Text.Trim().ToLowerCSafe(); // Set PageInfo switch (keyType) { case EditableContentType.webpart: if (!createNew) { // If editing -> remove old node.DocumentContent.EditableWebParts.Remove(keyName); } if (!node.DocumentContent.EditableWebParts.ContainsKey(codeName)) { node.DocumentContent.EditableWebParts.Add(codeName, content); } else { ShowError(GetString("EditableContent.ItemExists")); return; } break; case EditableContentType.region: if (!createNew) { // If editing -> remove old node.DocumentContent.EditableRegions.Remove(keyName); } if (!node.DocumentContent.EditableRegions.ContainsKey(codeName)) { node.DocumentContent.EditableRegions.Add(codeName, content); } else { ShowError(GetString("EditableContent.ItemExists")); return; } break; } // Get content content = node.DocumentContent.GetContentXml(); node.UpdateOriginalValues(); node.SetValue("DocumentContent", content); }
private object gridData_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView row = parameter as DataRowView; if (DocumentListingDisplayed) { switch (sourceName.ToLowerCSafe()) { case "skunumber": case "skuavailableitems": case "publicstatusid": case "allowforsale": case "skusiteid": case "typename": case "skuprice": if (ShowSections && (row["NodeSKUID"] == DBNull.Value)) { return(NO_DATA_CELL_VALUE); } break; case "edititem": row = ((GridViewRow)parameter).DataItem as DataRowView; if ((row != null) && ((row["NodeSKUID"] == DBNull.Value) || showProductsInTree)) { CMSGridActionButton btn = sender as CMSGridActionButton; if (btn != null) { int currentNodeId = ValidationHelper.GetInteger(row["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(row["NodeParentID"], 0); if (row["NodeSKUID"] == DBNull.Value) { btn.IconCssClass = "icon-eye"; btn.IconStyle = GridIconStyle.Allow; btn.ToolTip = GetString("com.sku.viewproducts"); } // Go to the selected document btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;"; } } break; } } switch (sourceName.ToLowerCSafe()) { case "skunumber": string skuNumber = ValidationHelper.GetString(row["SKUNumber"], null); return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(skuNumber) ?? "")); case "skuavailableitems": var sku = new SKUInfo(row.Row); int availableItems = sku.SKUAvailableItems; // Inventory tracked by variants if (sku.SKUTrackInventory == TrackInventoryTypeEnum.ByVariants) { return(GetString("com.inventory.trackedbyvariants")); } // Inventory tracking disabled if (sku.SKUTrackInventory == TrackInventoryTypeEnum.Disabled) { return(GetString("com.inventory.nottracked")); } // Ensure correct values for unigrid export if (sender == null) { return(availableItems); } // Tracking by products InlineEditingTextBox inlineAvailableItems = new InlineEditingTextBox(); inlineAvailableItems.Text = availableItems.ToString(); inlineAvailableItems.DelayedReload = DocumentListingDisplayed; inlineAvailableItems.EnableEncode = false; inlineAvailableItems.Formatting += (s, e) => { var reorderAt = sku.SKUReorderAt; // Emphasize the number when product needs to be reordered if (availableItems <= reorderAt) { // Format message informing about insufficient stock level string reorderMsg = string.Format(GetString("com.sku.reorderatTooltip"), reorderAt); string message = string.Format("<span class=\"alert-status-error\" onclick=\"UnTip()\" onmouseout=\"UnTip()\" onmouseover=\"Tip('{1}')\">{0}</span>", availableItems, reorderMsg); inlineAvailableItems.FormattedText = message; } }; // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data. // Update data only if external data bound is called for the first time. if (!forceReloadData) { inlineAvailableItems.Update += (s, e) => { var newNumberOfItems = ValidationHelper.GetInteger(inlineAvailableItems.Text, availableItems); if (ValidationHelper.IsInteger(inlineAvailableItems.Text) && (-1000000000 <= newNumberOfItems) && (newNumberOfItems <= 1000000000)) { CheckModifyPermission(sku); // Ensures that grid will display inserted value sku.SKUAvailableItems = newNumberOfItems; // Document list is used to display products -> document has to be updated to ensure correct sku mapping if (DocumentListingDisplayed) { int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0); // Create an instance of the Tree provider and select edited document with coupled data TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode document = tree.SelectSingleDocument(documentId); if (document == null) { return; } document.SetValue("SKUAvailableItems", newNumberOfItems); document.Update(); forceReloadData = true; } // Stand-alone product -> only product has to be updated else { sku.MakeComplete(true); sku.Update(); gridData.ReloadData(); } } else { inlineAvailableItems.ErrorText = GetString("com.productedit.availableitemsinvalid"); } }; } return(inlineAvailableItems); case "skuprice": SKUInfo product = new SKUInfo(row.Row); // Ensure correct values for unigrid export if (sender == null) { return(product.SKUPrice); } InlineEditingTextBox inlineSkuPrice = new InlineEditingTextBox(); inlineSkuPrice.Text = product.SKUPrice.ToString(); inlineSkuPrice.DelayedReload = DocumentListingDisplayed; inlineSkuPrice.Formatting += (s, e) => { // Format price inlineSkuPrice.FormattedText = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, product.SKUSiteID); }; // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data. // Update data only if external data bound is called for the first time. if (!forceReloadData) { inlineSkuPrice.Update += (s, e) => { CheckModifyPermission(product); // Price must be a double number double price = ValidationHelper.GetDouble(inlineSkuPrice.Text, -1); if (ValidationHelper.IsDouble(inlineSkuPrice.Text) && (price >= 0)) { // Ensures that grid will display inserted price product.SKUPrice = price; // Document list is used to display products -> document has to be updated to ensure correct sku mapping if (DocumentListingDisplayed) { int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0); // Create an instance of the Tree provider and select edited document with coupled data TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode document = tree.SelectSingleDocument(documentId); if (document != null) { document.SetValue("SKUPrice", price); document.Update(); forceReloadData = true; } } // Stand-alone product -> only product has to be updated else { product.MakeComplete(true); product.Update(); gridData.ReloadData(); } } else { inlineSkuPrice.ErrorText = GetString("com.productedit.priceinvalid"); } }; } return(inlineSkuPrice); case "publicstatusid": int id = ValidationHelper.GetInteger(row["SKUPublicStatusID"], 0); PublicStatusInfo publicStatus = PublicStatusInfoProvider.GetPublicStatusInfo(id); if (publicStatus != null) { // Localize and encode return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName))); } return(string.Empty); case "allowforsale": // Get "on sale" flag return(UniGridFunctions.ColoredSpanYesNo(ValidationHelper.GetBoolean(row["SKUEnabled"], false))); case "typename": string docTypeName = ValidationHelper.GetString(row["ClassDisplayName"], null); // Localize class display name if (!string.IsNullOrEmpty(docTypeName)) { return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(docTypeName))); } return(string.Empty); } return(parameter); }
/// <summary> /// Saves modified image data. /// </summary> /// <param name="name">Image name</param> /// <param name="extension">Image extension</param> /// <param name="mimetype">Image mimetype</param> /// <param name="title">Image title</param> /// <param name="description">Image description</param> /// <param name="binary">Image binary data</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (ai != null) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "attach.actiondenied"; SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.namenotunique"; SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWithCSafe(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization and search task for the document if (node != null) { // Update search index for given document if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && node != null) { VersionManager.CheckIn(node, null, null); } } } } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { CurrentUserInfo currentUser = CMSContext.CurrentUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, CMSContext.CurrentUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; SavingFailed = true; } } break; } }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return(false); } } // Save the data if ((CurrentPageInfo != null) && (mTemplateInstance != null) && SaveForm(formCustom)) { ViewModeEnum viewMode = PortalContext.ViewMode; // Check manage permission for non-livesite version if (!viewMode.IsLiveSite() && (viewMode != ViewModeEnum.DashboardWidgets)) { if (CurrentUser.IsAuthorizedPerDocument(CurrentPageInfo.NodeID, CurrentPageInfo.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { DisplayError("general.modifynotallowed"); return(false); } // Check design permissions if (PortalContext.IsDesignMode(viewMode, false) && !PortalContext.CurrentUserIsDesigner) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = mTemplateInstance.ParentPageTemplate; if (PortalContext.IsDesignMode(viewMode) && SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName)); return(false); } // Get the zone mWebPartZoneInstance = mTemplateInstance.EnsureZone(ZoneId); if (mWebPartZoneInstance != null) { mWebPartZoneInstance.WidgetZoneType = ZoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance mWidgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, mTemplateInstance); } // Ensure handling of the currently edited object (if not exists -> redirect) UIContext.EditedObject = mWidgetInstance; mWidgetInstance.XMLVersion = 1; if (IsNewVariant) { mWidgetInstance = mWidgetInstance.Clone(); // Check whether the editor widgets have been already customized if (CurrentPageInfo.DocumentTemplateInstance.WebPartZones.Count == 0) { // There are no customized editor widgets yet => copy the default editor widgets from the page template under the document (to enable customization) // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); // Extract and set the document web parts node.SetValue("DocumentWebParts", mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, mTreeProvider); } } bool isLayoutWidget = ((mWebPartInfo != null) && ((WebPartTypeEnum)mWebPartInfo.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, mTemplateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(mWidgetInfo.WidgetName); if (!string.IsNullOrEmpty(controlId)) { mWidgetInstance.ControlID = controlId; } else { DisplayError("Unable to generate unique widget id."); return(false); } } // Allow set dashboard in design mode if ((ZoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { viewMode = ViewModeEnum.Design; PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes if ((viewMode.IsEdit(true) || viewMode.IsEditLive()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { if (DocumentManager.AllowSave) { // Store the editor widgets in the temporary interlayer PortalContext.SaveEditorWidgets(CurrentPageInfo.DocumentID, mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); } } else { // Save the changes CMSPortalManager.SaveTemplateChanges(CurrentPageInfo, mTemplateInstance, ZoneType, viewMode, mTreeProvider); } } else if ((viewMode.IsEdit()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; VariantHelper.SaveWebPartVariantChanges(mWidgetInstance, VariantID, 0, VariantMode, properties); // Clear the document template mTemplateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, mTreeProvider); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Display info message ShowChangesSaved(); // Clear the cached web part CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); return(true); } return(false); }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return(false); } } // Save the data if ((pi != null) && (templateInstance != null) && SaveForm(formCustom)) { // Check manage permission for non-livesite version if ((PortalContext.ViewMode != ViewModeEnum.LiveSite) && (PortalContext.ViewMode != ViewModeEnum.DashboardWidgets)) { CurrentUserInfo cui = MembershipContext.AuthenticatedUser; // Check document permissions if (cui.IsAuthorizedPerDocument(pi.NodeID, pi.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { return(false); } // Check design permissions if ((PortalContext.ViewMode == ViewModeEnum.Design) && !(cui.IsGlobalAdministrator || (cui.IsAuthorizedPerResource("cms.design", "Design") && cui.IsAuthorizedPerUIElement("CMS.Content", "Design.WebPartProperties")))) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = templateInstance.ParentPageTemplate; if ((PortalContext.ViewMode == ViewModeEnum.Design) && SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.ObjectType, pti.DisplayName, userName)); return(false); } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = zoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance widgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, templateInstance, null); } widgetInstance.XMLVersion = 1; if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); if (pi.DocumentTemplateInstance.WebPartZones.Count == 0) { // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } bool isLayoutWidget = ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, templateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(wi.WidgetName); if (!string.IsNullOrEmpty(controlId)) { widgetInstance.ControlID = controlId; } else { DisplayError("Unable to generate unique widget id."); return(false); } } // Allow set dashboard in design mode if ((zoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, templateInstance, zoneType, PortalContext.ViewMode, tree); } else if ((PortalContext.ViewMode == ViewModeEnum.Edit) && (zoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; PortalHelper.SaveWebPartVariantChanges(widgetInstance, VariantID, 0, VariantMode, properties); // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); } return(true); } return(false); }
/// <summary> /// Updates the current Group or creates new if no GroupID is present. /// </summary> public void SaveData() { if (!CheckPermissions("cms.groups", PERMISSION_MANAGE, GroupID)) { return; } // Trim display name and code name string displayName = txtDisplayName.Text.Trim(); string codeName = txtCodeName.Text.Trim(); // Validate form entries string errorMessage = ValidateForm(displayName, codeName); if (errorMessage == "") { GroupInfo group = null; try { bool newGroup = false; // Update existing item if ((GroupID > 0) && (gi != null)) { group = gi; } else { group = new GroupInfo(); newGroup = true; } if (group != null) { if (displayName != group.GroupDisplayName) { // Refresh a breadcrumb if used in the tabs layout ScriptHelper.RefreshTabHeader(Page, string.Empty); } if (DisplayAdvanceOptions) { // Update Group fields group.GroupDisplayName = displayName; group.GroupName = codeName; group.GroupNodeGUID = ValidationHelper.GetGuid(groupPageURLElem.Value, Guid.Empty); } if (AllowChangeGroupDisplayName && IsLiveSite) { group.GroupDisplayName = displayName; } group.GroupDescription = txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = SiteID; group.GroupApproveMembers = GetGroupApproveMembers(); group.GroupSendJoinLeaveNotification = chkJoinLeave.Checked; group.GroupSendWaitingForApprovalNotification = chkWaitingForApproval.Checked; groupPictureEdit.UpdateGroupPicture(group); // If new group was created if (newGroup) { // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user CurrentUserInfo user = CMSContext.CurrentUser; if (user != null) { group.GroupCreatedByUserID = user.UserID; group.GroupApprovedByUserID = user.UserID; group.GroupApproved = true; } } if (!IsLiveSite && (group.GroupNodeGUID == Guid.Empty)) { plcStyleSheetSelector.Visible = false; } // Save theme int selectedSheetID = ValidationHelper.GetInteger(ctrlSiteSelectStyleSheet.Value, 0); if (plcStyleSheetSelector.Visible) { if (group.GroupNodeGUID != Guid.Empty) { // Save theme for every site culture var cultures = CultureInfoProvider.GetSiteCultureCodes(CMSContext.CurrentSiteName); if (cultures != null) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Return class name of selected tree node TreeNode treeNode = tree.SelectSingleNode(group.GroupNodeGUID, TreeProvider.ALL_CULTURES, CMSContext.CurrentSiteName); if (treeNode != null) { // Return all culture version of node DataSet ds = tree.SelectNodes(CMSContext.CurrentSiteName, null, TreeProvider.ALL_CULTURES, false, treeNode.NodeClassName, "NodeGUID ='" + group.GroupNodeGUID + "'", String.Empty, -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { // Loop through all nodes foreach (DataRow dr in ds.Tables[0].Rows) { // Create node and set tree provider for user validation TreeNode node = TreeNode.New(dr, ValidationHelper.GetString(dr["className"], String.Empty)); node.TreeProvider = tree; // Update stylesheet id if set if (selectedSheetID == 0) { node.SetValue("DocumentStylesheetID", -1); } else { node.DocumentStylesheetID = selectedSheetID; } node.Update(); } } } } } } if (!IsLiveSite && (group.GroupNodeGUID != Guid.Empty)) { plcStyleSheetSelector.Visible = true; } if (plcOnline.Visible) { // On-line marketing setting is visible => set flag according to checkbox group.GroupLogActivity = chkLogActivity.Checked; } else { // On-line marketing setting is not visible => set flag to TRUE as default value group.GroupLogActivity = true; } // Save Group in the database GroupInfoProvider.SetGroupInfo(group); groupPictureEdit.GroupInfo = group; txtDisplayName.Text = group.GroupDisplayName; txtCodeName.Text = group.GroupName; // Flush cached information CMSContext.CurrentDocument = null; CMSContext.CurrentPageInfo = null; CMSContext.CurrentDocumentStylesheet = null; // Display information on success ShowChangesSaved(); // If new group was created if (newGroup) { GroupID = group.GroupID; RaiseOnSaved(); } } } catch (Exception ex) { // Display error message ShowError(GetString("general.saveerror"), ex.Message, null); } } else { // Display error message ShowError(errorMessage); } }
/// <summary> /// Generate control output. /// </summary> public void GenerateContent() { string templatePath = DepartmentTemplatePath; if (String.IsNullOrEmpty(templatePath)) { ltlContent.Text = ResHelper.GetString("departmentsectionsmanager.notemplate"); ltlContent.Visible = true; } else { if (!DataHelper.DataSourceIsEmpty(TemplateDocuments)) { int counter = 0; Table tb = new Table(); string value = ValidationHelper.GetString(mSelectedValue, ""); string docAliases = ";" + value.ToLowerCSafe() + ";"; TreeNode editedNode = (TreeNode)Form.EditedObject; if (Form.IsInsertMode) { // Alias path for new department has to have special 'child node path' because of correct check for document type scopes editedNode.SetValue("NodeAliasPath", ((TreeNode)Form.ParentObject).NodeAliasPath + "/department"); } TableRow tr = new TableRow(); foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows) { // For each section td element is generated string docAlias = ValidationHelper.GetString(drDoc["NodeAlias"], ""); TableCell td = new TableCell(); CMSCheckBox cbCell = new CMSCheckBox(); cbCell.ID = "chckSection" + counter; cbCell.Text = docAlias; cbCell.Attributes.Add("Value", docAlias); // Check if child allowed int sourceClassId = ValidationHelper.GetInteger(drDoc["NodeClassID"], 0); if (!DocumentHelper.IsDocumentTypeAllowed(editedNode, sourceClassId)) { cbCell.Enabled = false; cbCell.ToolTip = ResHelper.GetString("departmentsectionsmanager.notallowedchild"); } // Disable default hidden documents if (HIDDEN_DOCUMENT_ALIAS.Contains(";" + docAlias.ToLowerCSafe() + ";")) { cbCell.Checked = cbCell.Enabled; cbCell.Enabled = false; } // Check for selected value if (docAliases.Contains(";" + docAlias.ToLowerCSafe() + ";") || ((mSelectedValue == null) && (Form.Mode == FormModeEnum.Insert))) { if (cbCell.Enabled) { cbCell.Checked = true; } } // If editing existing document register alert script if ((Form.Mode != FormModeEnum.Insert) && cbCell.Checked) { cbCell.Attributes.Add("OnClick", "if(!this.checked){alert(" + ScriptHelper.GetString(ResHelper.GetString("departmentsectionsmanagerformcontrol.removesectionwarning")) + ");}"); } // Add reference to checkbox arraylist CheckboxReferences.Add(cbCell); counter++; td.Controls.Add(cbCell); tr.Cells.Add(td); // If necessary create new row if ((counter % ITEMS_PER_ROW) == 0) { tr.CssClass = "Row"; tb.Rows.Add(tr); tr = new TableRow(); } } // If last row contains data add it if (counter > 0) { tb.Rows.Add(tr); } pnlContent.Controls.Add(tb); } else { ltlContent.Text = ResHelper.GetString("departmentsectionsmanager.notemplate"); ltlContent.Visible = true; } } }
private void DocumentManager_OnSaveData(object sender, DocumentManagerEventArgs e) { TreeNode node = e.Node; // OWNER group is displayed by UI profile if (!pnlUIOwner.IsHidden) { // Set owner int ownerId = ValidationHelper.GetInteger(usrOwner.Value, 0); node.SetValue("NodeOwner", (ownerId > 0) ? usrOwner.Value : null); } // DESIGN group is displayed by UI profile if (!pnlUIDesign.IsHidden) { node.SetValue("DocumentStylesheetID", -1); if (!chkCssStyle.Checked) { // Set style sheet int selectedCssId = ValidationHelper.GetInteger(ctrlSiteSelectStyleSheet.Value, 0); if (selectedCssId < 1) { node.SetValue("DocumentStylesheetID", null); } else { node.SetValue("DocumentStylesheetID", selectedCssId); } ctrlSiteSelectStyleSheet.Enabled = true; } else { ctrlSiteSelectStyleSheet.Enabled = false; } } // CACHE group is displayed by UI profile if (!pnlUICache.IsHidden) { // Cache minutes int cacheMinutes = 0; if (radNo.Checked) { cacheMinutes = 0; txtCacheMinutes.Text = ""; } else if (radYes.Checked) { cacheMinutes = ValidationHelper.GetInteger(txtCacheMinutes.Text, -5); if (cacheMinutes <= 0) { e.IsValid = false; } } else if (radInherit.Checked) { cacheMinutes = currentPage.NodeCacheMinutes = -1; if ((currentPage != null) && (currentPage.NodeCacheMinutes > 0)) { txtCacheMinutes.Text = currentPage.NodeCacheMinutes.ToString(); } } // Set cache minutes if (cacheMinutes != node.NodeCacheMinutes) { node.NodeCacheMinutes = cacheMinutes; clearCache = true; } // Allow file system cache int allowFs = Node.NodeAllowCacheInFileSystem; if (radFSYes.Checked) { allowFs = 1; } else if (radFSNo.Checked) { allowFs = 0; } else if (radInherit.Checked) { allowFs = -1; } Node.NodeAllowCacheInFileSystem = allowFs; } if (e.IsValid) { // Check UI element permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "General.OnlineMarketing")) { node.DocumentLogVisitActivity = (chkPageVisitInherit.Checked ? (bool?)null : chkLogPageVisit.Checked); } } else { // Show error message e.ErrorMessage = GetString("GeneralProperties.BadCacheMinutes"); } }
private void ReloadData() { if (node != null) { bool isRoot = (node.NodeAliasPath == "/"); // Check read permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { hasModifyPermission = false; pnlForm.Enabled = false; tagSelectorElem.Enabled = false; } TreeNode tmpNode = node.Clone(); // If values are inherited set nulls tmpNode.SetValue("DocumentPageTitle", DBNull.Value); tmpNode.SetValue("DocumentPageKeyWords", DBNull.Value); tmpNode.SetValue("DocumentPageDescription", DBNull.Value); tmpNode.SetValue("DocumentTagGroupID", DBNull.Value); // Load the inherited values SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { tmpNode.LoadInheritedValues(new string[] { "DocumentPageTitle", "DocumentPageKeyWords", "DocumentPageDescription", "DocumentTagGroupID" }, SiteInfoProvider.CombineWithDefaultCulture(si.SiteName)); } if (!pnlUIPage.IsHidden) { // Page title if (node.GetValue("DocumentPageTitle") != null) { txtTitle.Text = node.GetValue("DocumentPageTitle").ToString(); } else { if (!isRoot) { txtTitle.Enabled = false; chkTitle.Checked = true; txtTitle.Text = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageTitle"), ""); } } // Page key words if (node.GetValue("DocumentPageKeyWords") != null) { txtKeywords.Text = node.GetValue("DocumentPageKeyWords").ToString(); } else { if (!isRoot) { txtKeywords.Enabled = false; chkKeyWords.Checked = true; txtKeywords.Text = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageKeyWords"), ""); } } // Page description if (node.GetValue("DocumentPageDescription") != null) { txtDescription.Text = node.GetValue("DocumentPageDescription").ToString(); } else { if (!isRoot) { txtDescription.Enabled = false; chkDescription.Checked = true; txtDescription.Text = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageDescription"), ""); } } } if (!pnlUITags.IsHidden) { // Tag group if (node.GetValue("DocumentTagGroupID") != null) { object tagGroupId = node.GetValue("DocumentTagGroupID"); tagGroupSelectorElem.Value = tagGroupId; } else { if (!isRoot) { // Get the inherited tag group int tagGroup = ValidationHelper.GetInteger(tmpNode.GetValue("DocumentTagGroupID"), 0); if (tagGroup > 0) { tagGroupSelectorElem.Value = tagGroup; } else { tagGroupSelectorElem.AddNoneItemsRecord = true; } tagGroupSelectorElem.Enabled = false; chkTagGroupSelector.Checked = true; } else { // Add 'none' option to Root document tagGroupSelectorElem.AddNoneItemsRecord = true; } } // Tags tagSelectorElem.Value = node.DocumentTags; } } }