/// <summary> /// Inserts an attachment into the Teaser image field. Called when the "Insert field attachment" button is pressed. /// Expects the "Create example document" method to be run first. /// </summary> private bool InsertFieldAttachment() { // Create a new instance of the Tree provider TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Get the example document TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/API-Example", "en-us"); if (node != null) { AttachmentInfo newAttachment = null; // Path to the file to be inserted. This example uses an explicitly defined file path. However, you can use an object of the HttpPostedFile type (uploaded via an upload control). string postedFile = Server.MapPath("Files/file.png"); // Insert the attachment and update the document with its GUID newAttachment = DocumentHelper.AddAttachment(node, "MenuItemTeaserImage", postedFile, tree); node.Update(); if (newAttachment != null) { return(true); } apiInsertFieldAttachment.ErrorMessage = "Couldn't insert the attachment."; } return(false); }
protected void ProcessFileUploader() { TreeNode node = DocumentManager.Node; // Create new document string fileName = Path.GetFileNameWithoutExtension(FileUpload.FileName); int maxFileNameLength = FileNameFieldInfo.Size; if (fileName.Length > maxFileNameLength) { fileName = fileName.Substring(0, maxFileNameLength); } node.DocumentName = fileName; if (node.ContainsColumn("FileDescription")) { node.SetValue("FileDescription", txtFileDescription.Text); } node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.SetDefaultPageTemplateID(DataClass.ClassDefaultPageTemplateID); // Ensures documents consistency (blog post hierarchy etc.) DocumentManager.EnsureDocumentsConsistency(); // Insert the document DocumentHelper.InsertDocument(node, DocumentManager.ParentNodeID, DocumentManager.Tree); // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", FileUpload.PostedFile, DocumentManager.Tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); }
protected TreeNode ProcessFileUploader(TreeProvider tree) { TreeNode node = null; // Create new document string fileName = Path.GetFileNameWithoutExtension(FileUpload.FileName); int maxFileNameLength = FileNameFieldInfo.Size; if (fileName.Length > maxFileNameLength) { fileName = fileName.Substring(0, maxFileNameLength); } node = TreeNode.New("CMS.File", tree); node.DocumentCulture = CMSContext.PreferredCultureCode; node.DocumentName = fileName; // Load default values FormHelper.LoadDefaultValues(node); if (node.ContainsColumn("FileDescription")) { node.SetValue("FileDescription", txtFileDescription.Text); } //node.SetValue("FileName", fileName); node.SetValue("FileAttachment", Guid.Empty); // Set default template ID if (templateId > 0) { node.DocumentPageTemplateID = templateId; } else { node.DocumentPageTemplateID = DataClass.ClassDefaultPageTemplateID; } // Insert the document DocumentHelper.InsertDocument(node, nodeId, tree); // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", FileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); return(node); }
private void InsertAttachment(Node node) { // Creates a new instance of the Tree provider TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Gets a page TreeNode page = tree.SelectNodes() .WhereLike("NodeAliasPath", node.NodeAliasPath) .FirstObject; if (page != null) { AttachmentInfo attachment = null; // Prepares the path of the file string file = System.Web.HttpContext.Current.Server.MapPath(node.Path); // Inserts the attachment into the "MenuItemTeaserImage" field and updates the page attachment = DocumentHelper.AddAttachment(page, "FileAttachment", file, tree); page.Update(); } }
/// <summary> /// Provides operations necessary to create and store new content file. /// </summary> private void HandleContentUpload() { string message = string.Empty; bool newDocumentCreated = false; try { if (NodeParentNodeID == 0) { throw new Exception(GetString("dialogs.document.parentmissing")); } // Check license limitations if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert)) { throw new LicenseException(GetString("cmsdesk.documentslicenselimits")); } // Check if class exists DataClassInfo ci = DataClassInfoProvider.GetDataClassInfo(SystemDocumentTypes.File); if (ci == null) { throw new Exception(string.Format(GetString("dialogs.newfile.classnotfound"), SystemDocumentTypes.File)); } #region "Check permissions" // Get the node TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, LocalizationContext.PreferredCultureCode, true); if (parentNode != null) { // Check whether node class is allowed on site and parent node if (!DocumentHelper.IsDocumentTypeAllowed(parentNode, ci.ClassID) || (ClassSiteInfoProvider.GetClassSiteInfo(ci.ClassID, parentNode.NodeSiteID) == null)) { throw new Exception(GetString("Content.ChildClassNotAllowed")); } } // Check user permissions if (!RaiseOnCheckPermissions("Create", this)) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(parentNode, SystemDocumentTypes.File)) { throw new Exception(string.Format(GetString("dialogs.newfile.notallowed"), NodeClassName)); } } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Create new document string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName); string ext = Path.GetExtension(ucFileUpload.FileName); if (IncludeExtension) { fileName += ext; } // Make sure the file name with extension respects maximum file name fileName = TreePathUtils.EnsureMaxFileNameLength(fileName, ci.ClassName); node = TreeNode.New(SystemDocumentTypes.File, TreeProvider); node.DocumentCulture = LocalizationContext.PreferredCultureCode; node.DocumentName = fileName; if (NodeGroupID > 0) { node.SetValue("NodeGroupID", NodeGroupID); } // Load default values FormHelper.LoadDefaultValues(node.NodeClassName, node); node.SetValue("FileDescription", ""); node.SetValue("FileName", fileName); node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID); // Insert the document DocumentHelper.InsertDocument(node, parentNode, TreeProvider); newDocumentCreated = true; // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update the document DocumentHelper.UpdateDocument(node, TreeProvider); // Get workflow info wi = node.GetWorkflow(); // Check if auto publish changes is allowed if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(SiteContext.CurrentSiteName)) { // Automatically publish document node.MoveToPublishedStep(null); } } catch (Exception ex) { // Delete the document if something failed if (newDocumentCreated && (node != null) && (node.DocumentID > 0)) { DocumentHelper.DeleteDocument(node, TreeProvider, false, true); } message = ex.Message; } finally { // Create node info string string nodeInfo = ""; if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo)) { nodeInfo = node.NodeID.ToString(); } // Ensure message text message = TextHelper.EnsureLineEndings(message, " "); string containerId = QueryHelper.GetString("containerid", ""); // Call function to refresh parent window string afterSaveScript = null; if (!string.IsNullOrEmpty(AfterSaveJavascript)) { afterSaveScript = String.Format( @" if (window.{0} != null){{ window.{0}(files); }} else if ((window.parent != null) && (window.parent.{0} != null)){{ window.parent.{0}(files); }}", AfterSaveJavascript ); } afterSaveScript += String.Format( @" if (typeof(parent.DFU) !== 'undefined') {{ parent.DFU.OnUploadCompleted({0}); }} if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{ window.parent.InitRefresh_{1}({2}, false, false{3}{4}); }} ", ScriptHelper.GetString(containerId), ParentElemID, ScriptHelper.GetString(message.Trim()), ((nodeInfo != "") ? ", '" + nodeInfo + "'" : ""), (InsertMode ? ", 'insert'" : ", 'update'") ); ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript)); } }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { // New attachment DocumentAttachment newAttachment = null; string message = string.Empty; bool fullRefresh = false; bool refreshTree = false; try { // Get the existing document if (DocumentID != 0) { // Get document node = DocumentHelper.GetDocument(DocumentID, TreeProvider); if (node == null) { throw new Exception("Given page doesn't exist!"); } } #region "Check permissions" if (CheckPermissions) { CheckNodePermissions(node); } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Standard attachments if (DocumentID != 0) { // Check out the document if (AutoCheck) { // Get original step Id int originalStepId = node.DocumentWorkflowStepID; // Get current step info WorkflowStepInfo si = WorkflowManager.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed bool automaticPublish = wi.WorkflowAutoPublishChanges; // Document is published or archived or uses automatic publish or step is different than original (document was updated) fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID); } using (CMSActionContext ctx = new CMSActionContext() { LogEvents = false }) { VersionManager.CheckOut(node, node.IsPublished, true); } } // Handle field attachment if (fieldAttachment) { // Extension of CMS file before saving string oldExtension = node.DocumentType; newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, TreeProvider); // Different extension if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true)) { refreshTree = true; } } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Log synchronization task if not under workflow if (wi == null) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider); } } // Check in the document if (AutoCheck) { using (CMSActionContext ctx = new CMSActionContext() { LogEvents = false }) { VersionManager.CheckIn(node, null, null); } } } // Temporary attachments if (FormGUID != Guid.Empty) { newAttachment = (DocumentAttachment)AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, SiteContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Ensure properties update if ((newAttachment != null) && !InsertMode) { AttachmentGUID = newAttachment.AttachmentGUID; } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { // Log the exception EventLogProvider.LogException("Content", "UploadAttachment", ex); message = ex.Message; } finally { string afterSaveScript = string.Empty; // Call aftersave javascript if exists if (!String.IsNullOrEmpty(AfterSaveJavascript)) { if ((message == string.Empty) && (newAttachment != null)) { string url = null; string safeName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { bool usePermanent = DocumentURLProvider.UsePermanentUrls(si.SiteName); if (usePermanent) { url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName)); } else { url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(safeName, node.NodeAliasPath)); } } } else { url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName)); } // Calling javascript function with parameters attachments url, name, width, height if (!string.IsNullOrEmpty(AfterSaveJavascript)) { Hashtable obj = new Hashtable(); if (ImageHelper.IsImage(newAttachment.AttachmentExtension)) { obj[DialogParameters.IMG_URL] = url; obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName; obj[DialogParameters.IMG_WIDTH] = newAttachment.AttachmentImageWidth; obj[DialogParameters.IMG_HEIGHT] = newAttachment.AttachmentImageHeight; } else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "audiovideo"; obj[DialogParameters.AV_URL] = url; obj[DialogParameters.AV_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.AV_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.AV_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else { obj[DialogParameters.LINK_URL] = url; obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName; } // Calling javascript function with parameters attachments url, name, width, height afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5} if (window.{0}) {{ window.{0}('{1}', '{2}', '{3}', '{4}', obj); }} else if((window.parent != null) && window.parent.{0}) {{ window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj); }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj))); } } else { afterSaveScript += ScriptHelper.GetAlertScript(message); } } // Create attachment info string string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : ""; // Ensure message text message = TextHelper.EnsureLineEndings(message, " "); // Call function to refresh parent window afterSaveScript += ScriptHelper.GetScript(String.Format(@" if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ window.parent.InitRefresh_{0}({1}, {2}, {3}, {4}); }}", ParentElemID, ScriptHelper.GetString(message.Trim()), (fullRefresh ? "true" : "false"), (refreshTree ? "true" : "false"), attachmentInfo + (InsertMode ? "'insert'" : "'update'"))); ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript); } }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> /// <param name="args">Upload arguments.</param> /// <param name="context">HttpContext instance.</param> private void HandleAttachmentUpload(UploaderHelper args, HttpContext context) { AttachmentInfo newAttachment = null; bool refreshTree = false; try { args.IsExtensionAllowed(); // Get existing document if (args.AttachmentArgs.DocumentID != 0) { node = DocumentHelper.GetDocument(args.AttachmentArgs.DocumentID, TreeProvider); if (node == null) { throw new Exception("Given document doesn't exist!"); } else { #region "Check permissions" // For new document if (args.AttachmentArgs.FormGuid != Guid.Empty) { if (args.AttachmentArgs.ParentNodeID == 0) { throw new Exception(ResHelper.GetString("attach.document.parentmissing")); } if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.AttachmentArgs.ParentNodeID, args.AttachmentArgs.NodeClassName)) { throw new Exception(ResHelper.GetString("attach.actiondenied")); } } // For existing document else if (args.AttachmentArgs.DocumentID > 0) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { throw new Exception(ResHelper.GetString("attach.actiondenied")); } } #endregion args.IsExtensionAllowed(); // Check out the document if (AutoCheck) { // Get current step info WorkflowStepInfo si = WorkflowManager.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed string stepName = si.StepName.ToLower(); args.FullRefresh = (stepName == "published") || (stepName == "archived"); } VersionManager.CheckOut(node, node.IsPublished, true); } // Handle field attachment if (args.AttachmentArgs.FieldAttachment) { // Extension of CMS file before saving string oldExtension = node.DocumentType; newAttachment = DocumentHelper.AddAttachment(node, args.AttachmentArgs.AttachmentGuidColumnName, Guid.Empty, Guid.Empty, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); DocumentHelper.UpdateDocument(node, TreeProvider); // Different extension if ((oldExtension != null) && !oldExtension.Equals(node.DocumentType, StringComparison.InvariantCultureIgnoreCase)) { refreshTree = true; } } else { // Handle grouped and unsorted attachments if (args.AttachmentArgs.AttachmentGroupGuid != Guid.Empty) { // Grouped attachment newAttachment = DocumentHelper.AddGroupedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } else { // Unsorted attachment newAttachment = DocumentHelper.AddUnsortedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } // Log synchronization task if not under workflow if (wi == null) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider); } } // Check in the document if (AutoCheck) { VersionManager.CheckIn(node, null, null); } } } else if (args.AttachmentArgs.FormGuid != Guid.Empty) { newAttachment = AttachmentManager.AddTemporaryAttachment(args.AttachmentArgs.FormGuid, args.AttachmentArgs.AttachmentGuidColumnName, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, CMSContext.CurrentSiteID, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { // Log the exception EventLogProvider.LogException("Content", "UploadAttachment", ex); // Store exception message args.Message = ex.Message; } finally { // Call aftersave javascript if exists if (!string.IsNullOrEmpty(args.AfterSaveJavascript)) { if ((args.Message == string.Empty) && (newAttachment != null)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { url = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs") ? URLHelper.ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)) : URLHelper.ResolveUrl(AttachmentManager.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } else { url = URLHelper.ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } Hashtable obj = new Hashtable(); if (ImageHelper.IsImage(newAttachment.AttachmentExtension)) { obj[DialogParameters.IMG_URL] = url; obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName; obj[DialogParameters.IMG_WIDTH] = newAttachment.AttachmentImageWidth; obj[DialogParameters.IMG_HEIGHT] = newAttachment.AttachmentImageHeight; } else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "flash"; obj[DialogParameters.FLASH_URL] = url; obj[DialogParameters.FLASH_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.FLASH_TITLE] = newAttachment.AttachmentName; obj[DialogParameters.FLASH_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "audiovideo"; obj[DialogParameters.AV_URL] = url; obj[DialogParameters.AV_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.AV_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.AV_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else { obj[DialogParameters.LINK_URL] = url; obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName; } // Calling javascript function with parameters attachments url, name, width, height args.AfterScript += string.Format(@"{5} if (window.{0}) {{ window.{0}('{1}', '{2}', '{3}', '{4}', obj); }} else if((window.parent != null) && window.parent.{0}) {{ window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj); }}", args.AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)); } else { args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false); } } // Create attachment info string string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (args.IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : ""; // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end args.AfterScript += string.Format(@" if (window.InitRefresh_{0}) {{ window.InitRefresh_{0}('{1}', {2}, {3}, {4}); }} else {{ if ('{1}' != '') {{ alert('{1}'); }} }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), args.FullRefresh.ToString().ToLower(), refreshTree.ToString().ToLower(), attachmentInfo + (args.IsInsertMode ? "'insert'" : "'update'")); args.AddEventTargetPostbackReference(); context.Response.Write(args.AfterScript); context.Response.Flush(); } }
/// <summary> /// Provides operations necessary to create and store new cms file. /// </summary> /// <param name="args">Upload arguments.</param> /// <param name="context">HttpContext instance.</param> private void HandleContentUpload(UploaderHelper args, HttpContext context) { bool newDocumentCreated = false; string name = args.Name; try { if (args.FileArgs.NodeID == 0) { throw new Exception(ResHelper.GetString("dialogs.document.parentmissing")); } // Check license limitations if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert)) { throw new Exception(ResHelper.GetString("cmsdesk.documentslicenselimits")); } // Check user permissions if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.FileArgs.NodeID, "CMS.File")) { throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), "CMS.File")); } // Check if class exists DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File"); if (ci == null) { throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.classnotfound"), "CMS.File")); } #region "Check permissions" // Get the node using (TreeNode parentNode = TreeProvider.SelectSingleNode(args.FileArgs.NodeID, args.FileArgs.Culture, true)) { if (parentNode != null) { if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID)) { throw new Exception(ResHelper.GetString("Content.ChildClassNotAllowed")); } } // Check user permissions if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File")) { throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), args.AttachmentArgs.NodeClassName)); } } #endregion args.IsExtensionAllowed(); if (args.FileArgs.IncludeExtension) { name += args.Extension; } // Make sure the file name with extension respects maximum file name name = TextHelper.LimitFileNameLength(name, TreePathUtils.MaxNameLength); node = TreeNode.New("CMS.File", TreeProvider); node.DocumentCulture = args.FileArgs.Culture; node.DocumentName = name; if (args.FileArgs.NodeGroupID > 0) { node.SetValue("NodeGroupID", args.FileArgs.NodeGroupID); } // Load default values FormHelper.LoadDefaultValues(node); node.SetValue("FileDescription", ""); node.SetValue("FileName", name); node.SetValue("FileAttachment", Guid.Empty); node.SetValue("DocumentType", args.Extension); node.DocumentPageTemplateID = ci.ClassDefaultPageTemplateID; // Insert the document DocumentHelper.InsertDocument(node, args.FileArgs.NodeID, TreeProvider); newDocumentCreated = true; // Add the attachment data DocumentHelper.AddAttachment(node, "FileAttachment", args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); // Create default SKU if configured if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)) { node.CreateDefaultSKU(); } DocumentHelper.UpdateDocument(node, TreeProvider); // Get workflow info wi = WorkflowManager.GetNodeWorkflow(node); // Check if auto publish changes is allowed if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { // Automatically publish document WorkflowManager.AutomaticallyPublish(node, wi, null); } } catch (Exception ex) { // Delete the document if something failed if (newDocumentCreated && (node != null) && (node.DocumentID > 0)) { DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true); } args.Message = ex.Message; } finally { // Create node info string string nodeInfo = ((node != null) && (node.NodeID > 0) && args.IncludeNewItemInfo) ? String.Format("'{0}', ", node.NodeID) : ""; // Ensure message text args.Message = HTMLHelper.EnsureLineEnding(args.Message, " "); // Call function to refresh parent window if (!string.IsNullOrEmpty(args.AfterSaveJavascript)) { // Calling javascript function with parameters attachments url, name, width, height args.AfterScript += string.Format(@" if (window.{0} != null) {{ window.{0}(); }} else if((window.parent != null) && (window.parent.{0} != null)) {{ window.parent.{0}(); }}", args.AfterSaveJavascript); } // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end args.AfterScript += string.Format(@" if (window.InitRefresh_{0} != null) {{ window.InitRefresh_{0}('{1}', false, false, {2}); }} else {{ if ('{1}' != '') {{ alert('{1}'); }} }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), nodeInfo + (args.IsInsertMode ? "'insert'" : "'update'")); args.AddEventTargetPostbackReference(); context.Response.Write(args.AfterScript); context.Response.Flush(); } }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { TreeProvider tree = null; TreeNode node = null; // New attachment AttachmentInfo newAttachment = null; string message = string.Empty; bool fullRefresh = false; try { // Get the existing document if (DocumentID != 0) { // Get document tree = new TreeProvider(CMSContext.CurrentUser); node = DocumentHelper.GetDocument(DocumentID, tree); if (node == null) { throw new Exception("Given document doesn't exist!"); } } #region "Check permissions" if (CheckPermissions) { CheckNodePermissions(node); } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Standard attachments if (DocumentID != 0) { // Ensure automatic check-in/check-out bool useWorkflow = false; bool autoCheck = false; bool checkin = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(tree); VersionManager vm = null; // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName); } // Check out the document if (autoCheck) { // Get original step Id int originalStepId = node.DocumentWorkflowStepID; // Get current step info WorkflowStepInfo si = workflowMan.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed bool automaticPublish = wi.WorkflowAutoPublishChanges; // Document is published or archived or uses automatic publish or step is different than original (document was updated) fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID); } vm = VersionManager.GetInstance(tree); var step = vm.CheckOut(node, node.IsPublished, true); checkin = (step != null); } // Handle field attachment if (fieldAttachment) { newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, tree); } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } } // Check in the document if (autoCheck) { if ((vm != null) && checkin) { vm.CheckIn(node, null, null); } } // Log synchronization task if not under workflow if (!useWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Temporary attachments if (FormGUID != Guid.Empty) { newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Ensure properties update if ((newAttachment != null) && !InsertMode) { AttachmentGUID = newAttachment.AttachmentGUID; } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { message = ex.Message; lblError.Text = message; } finally { // Call aftersave javascript if exists if ((string.IsNullOrEmpty(message)) && (newAttachment != null)) { string closeString = "CloseDialog();"; // Register wopener script ScriptHelper.RegisterWOpenerScript(Page); if (!String.IsNullOrEmpty(AfterSaveJavascript)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs"); if (usePermanent) { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } else { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } } else { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } // Calling javascript function with parameters attachments url, name, width, height string jsParams = "('" + url + "', '" + newAttachment.AttachmentName + "', '" + newAttachment.AttachmentImageWidth + "', '" + newAttachment.AttachmentImageHeight + "');"; string script = "if ((wopener.parent != null) && (wopener.parent." + AfterSaveJavascript + " != null)){wopener.parent." + AfterSaveJavascript + jsParams + "}"; script += "else if (wopener." + AfterSaveJavascript + " != null){wopener." + AfterSaveJavascript + jsParams + "}"; ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString)); } // Create attachment info string string attachmentInfo = ""; if ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) { attachmentInfo = newAttachment.AttachmentGUID.ToString(); } // Ensure message text message = HTMLHelper.EnsureLineEnding(message, " "); // Call function to refresh parent window ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString)); } } }
/// <summary> /// Provides operations necessary to create and store new content file. /// </summary> private void HandleContentUpload() { TreeNode node = null; TreeProvider tree = null; string message = string.Empty; bool newDocumentCreated = false; try { if (NodeParentNodeID == 0) { throw new Exception(GetString("dialogs.document.parentmissing")); } // Check license limitations if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert)) { throw new Exception(GetString("cmsdesk.documentslicenselimits")); } // Check if class exists DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File"); if (ci == null) { throw new Exception("Class 'CMS.File' not found."); } #region "Check permissions" // Get the node tree = new TreeProvider(CMSContext.CurrentUser); TreeNode parentNode = tree.SelectSingleNode(NodeParentNodeID, TreeProvider.ALL_CULTURES); if (parentNode != null) { if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID)) { throw new Exception(GetString("Content.ChildClassNotAllowed")); } } // Check user permissions if (!RaiseOnCheckPermissions("Create", this)) { if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName)) { throw new Exception("You aren not allowed to create document of type '" + NodeClassName + "' in required location."); } } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Create new document string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName); node = TreeNode.New("CMS.File", tree); node.DocumentCulture = CMSContext.PreferredCultureCode; node.DocumentName = fileName; // Load default values FormHelper.LoadDefaultValues(node.NodeClassName, node); node.SetValue("FileDescription", ""); node.SetValue("FileName", fileName); node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID); // Insert the document DocumentHelper.InsertDocument(node, parentNode, tree); newDocumentCreated = true; // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Create default SKU if configured if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)) { node.CreateDefaultSKU(); } // Update the document DocumentHelper.UpdateDocument(node, tree); // Get workflow info WorkflowInfo workflowInfo = node.GetWorkflow(); // Check if auto publish changes is allowed if ((workflowInfo != null) && workflowInfo.WorkflowAutoPublishChanges && !workflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { // Automatically publish document node.MoveToPublishedStep(null); } } catch (Exception ex) { // Delete the document if something failed if (newDocumentCreated && (node != null) && (node.DocumentID > 0)) { DocumentHelper.DeleteDocument(node, tree, false, true, true); } message = ex.Message; lblError.Text = message; } finally { if (string.IsNullOrEmpty(message)) { // Create node info string string nodeInfo = ""; if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo)) { nodeInfo = node.NodeID.ToString(); } // Ensure message text message = HTMLHelper.EnsureLineEnding(message, " "); // Register wopener script ScriptHelper.RegisterWOpenerScript(Page); // Call function to refresh parent window ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false" + ((nodeInfo != "") ? ", '" + nodeInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}CloseDialog();")); } } }