コード例 #1
0
        public Guid AddUnsortedAttachment(TreeNode page, string uploadDirectory, HttpPostedFileWrapper file)
        {
            if (page == null)
            {
                throw new ArgumentNullException(nameof(page));
            }

            if (string.IsNullOrEmpty(uploadDirectory))
            {
                throw new ArgumentException("Upload directory path must be specified.", nameof(uploadDirectory));
            }

            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var directoryPath = EnsureUploadDirectory(uploadDirectory);
            var imagePath     = GetTempFilePath(directoryPath, file.FileName);

            byte[] data = new byte[file.ContentLength];
            file.InputStream.Seek(0, SeekOrigin.Begin);
            file.InputStream.Read(data, 0, file.ContentLength);
            CMS.IO.File.WriteAllBytes(imagePath, data);
            var attachmentGuid = DocumentHelper.AddUnsortedAttachment(page, Guid.NewGuid(), imagePath).AttachmentGUID;

            CMS.IO.File.Delete(imagePath);

            return(attachmentGuid);
        }
        private Guid AddUnsortedAttachment(TreeNode page, string requestFileName)
        {
            if (!(Request.Files[requestFileName] is HttpPostedFileWrapper file))
            {
                return(Guid.Empty);
            }

            return(ImageUploaderHelper.Upload(file, path =>
            {
                return DocumentHelper.AddUnsortedAttachment(page, Guid.Empty, path).AttachmentGUID;
            }));
        }
コード例 #3
0
        private Guid AddAttachment(TreeNode page, string uploadDirectory, HttpPostedFileWrapper file)
        {
            var directoryPath = EnsureUploadDirectory(uploadDirectory);
            var imagePath     = GetTempFilePath(directoryPath, file.FileName);
            var data          = new byte[file.ContentLength];

            file.InputStream.Seek(0, SeekOrigin.Begin);
            file.InputStream.Read(data, 0, file.ContentLength);
            CMS.IO.File.WriteAllBytes(imagePath, data);
            var attachmentGuid = DocumentHelper.AddUnsortedAttachment(page, Guid.NewGuid(), imagePath).AttachmentGUID;

            CMS.IO.File.Delete(imagePath);
            return(attachmentGuid);
        }
コード例 #4
0
    /// <summary>
    /// Inserts an unsorted attachment to the example document. Called when the "Insert unsorted attachment" button is pressed.
    /// Expects the "Create example document" method to be run first.
    /// </summary>
    private bool InsertUnsortedAttachment()
    {
        // Create a new instance of the Tree provider
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Get the document
        TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/API-Example", "en-us");

        // 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");

        if (node != null)
        {
            // Insert the attachment
            return(DocumentHelper.AddUnsortedAttachment(node, Guid.NewGuid(), postedFile, tree, ImageHelper.AUTOSIZE, ImageHelper.AUTOSIZE, ImageHelper.AUTOSIZE) != null);
        }

        return(false);
    }
        private Guid AddUnsortedAttachment(TreeNode page, string requestFileName)
        {
            if (!(Request.Files[requestFileName] is HttpPostedFileWrapper file))
            {
                return(Guid.Empty);
            }

            var directoryPath = EnsureUploadDirectory();
            var imagePath     = GetTempFilePath(directoryPath, file);

            byte[] data = new byte[file.ContentLength];
            file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            file.InputStream.Read(data, 0, file.ContentLength);

            CMS.IO.File.WriteAllBytes(imagePath, data);

            var attachmentGuid = DocumentHelper.AddUnsortedAttachment(page, Guid.Empty, imagePath).AttachmentGUID;

            CMS.IO.File.Delete(imagePath);

            return(attachmentGuid);
        }
コード例 #6
0
    /// <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);
        }
    }
コード例 #7
0
        /// <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();
            }
        }
コード例 #8
0
        private void CreateFile(Node node)
        {
            TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

            //Different folders GUID's
            //Product Images = AC97E28C-98AF-4060-82B7-E3333A5CA7F3
            //Schematics = C9615399-B088-44BE-8C26-C69F70867AEF
            //Selection Guides = 92B1EE7D-3E05-4D2F-9A95-2D1CED7C965E
            //Data Sheets = 7468DB7F-B830-4CC3-8A45-D89E35C52CA7
            //Catalogs = 07127465-2D28-4C26-A73A-E854036D640B


            //TreeNode parentPage = node.Parent.NodeAliasPath;
            TreeNode parentPage = tree.SelectNodes()
                                  .WhereLike("DocumentGUID", "7468DB7F-B830-4CC3-8A45-D89E35C52CA7")
                                  .OnCurrentSite()
                                  .Culture("en-us")
                                  .FirstObject;

            TreeNode newPage  = TreeNode.New(SystemDocumentTypes.File, tree);
            string   nodePath = node.Path.Split('\\').Last();
            int      index    = nodePath.IndexOf(".");

            if (index > 0)
            {
                nodePath = nodePath.Substring(0, index);
            }
            newPage.DocumentName = nodePath;

            //newNode.SetValue("FileDate", DateTime);
            DocumentHelper.InsertDocument(newPage, parentPage);

            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 filePath = MediaLibraryPath + @"\" + mediaFile.FileName + mediaFile.FileExtension;

            // Insert the attachment and update the document with its GUID
            newAttachment = DocumentHelper.AddUnsortedAttachment(newPage, Guid.NewGuid(), node.Path, tree, ImageHelper.AUTOSIZE, ImageHelper.AUTOSIZE, ImageHelper.AUTOSIZE);

            // attach the new attachment to the page/document
            newPage.SetValue("FileAttachment", newAttachment.AttachmentGUID);
            DocumentHelper.UpdateDocument(newPage);
            newPage.Update();



            // Gets the current site's root "/" page, which will serve as the parent page

            //TreeNode thisPage = tree.SelectSingleNode(SiteContext.CurrentSiteName, node.NodeAliasPath.Replace('.', '-'), "en-us");
            //CMS.IO.FileInfo file = CMS.IO.FileInfo.New(node.Path);
            //if (parentPage != null && file != null && thisPage == null)
            //{

            //    // Creates a new page of the "CMS.MenuItem" page type
            //    //TreeNode newPage = TreeNode.New(SystemDocumentTypes.File, tree);

            //    // Sets the properties of the new page
            //    newPage.DocumentName = node.Path.Split('\\').Last().Replace(".", "-");
            //    newPage.DocumentCulture = "en-us";
            //    //newPage.Insert(parentPage);
            //    AttachmentInfo attachment = null;
            //    attachment = DocumentHelper.AddAttachment(newPage, "FileAttachment", node.Path, tree);
            //    // Inserts the new page as a child of the parent page
            //    newPage.Update();

            //}
        }
コード例 #9
0
 private Guid AddUnsortedAttachment(TreeNode page, IFormFile requestFile)
 {
     return(DocumentHelper.AddUnsortedAttachment(page, Guid.Empty, requestFile.ToUploadedFile()).AttachmentGUID);
 }
コード例 #10
0
    /// <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));
            }
        }
    }