/// <summary> /// Deletes the file binary from the file system. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool DeleteFromFileSystem(int attachmentId, ref string name) { // Delete the file in file system AttachmentInfo ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, false); if (ai != null) { name = ai.AttachmentName; // Ensure the binary column first (check if exists) DataSet ds = AttachmentInfoProvider.GetAttachments("AttachmentID = " + attachmentId, null, true, 0, "CASE WHEN AttachmentBinary IS NULL THEN 0 ELSE 1 END AS HasBinary"); if (!DataHelper.DataSourceIsEmpty(ds)) { bool hasBinary = ValidationHelper.GetBoolean(ds.Tables[0].Rows[0][0], false); if (!hasBinary) { // Copy the binary data to database ai.AttachmentBinary = AttachmentInfoProvider.GetFile(ai, GetSiteName(ai.AttachmentSiteID)); ai.Generalized.UpdateData(); } // Delete the file from the disk AttachmentInfoProvider.DeleteFile(ai.AttachmentGUID, GetSiteName(ai.AttachmentSiteID), true, false); return(true); } } return(false); }
private void SaveDocumentAttachment() { // Ensure automatic check-in/ check-out bool autoCheck = false; var wm = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info var wi = wm.GetNodeWorkflow(node); if (wi != null) { autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { var nextStep = node.VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; if (IsWorkflowFinished(nextStep)) { attachment = (DocumentAttachment)AttachmentInfoProvider.GetAttachmentInfo(attachmentGuid, CurrentSiteName); } } var extension = attachment.AttachmentExtension; // If extension changed update file extension if (node.IsFile() && (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); } } DocumentHelper.UpdateAttachment(node, attachment); // Check in the document if (autoCheck && (VersionHistoryID > 0)) { node.VersionManager.CheckIn(node, null); } }
private static void RemoveTumbnail(SKUTreeNode product) { var oldAttachmentGuid = product.GetGuidValue("ProductThumbnail", Guid.Empty); var siteName = (product.Site ?? SiteInfoProvider.GetSiteInfo(product.NodeSiteID)).SiteName; if (oldAttachmentGuid != Guid.Empty) { var oldAttachment = AttachmentInfoProvider.GetAttachmentInfo(oldAttachmentGuid, siteName); if (oldAttachment != null) { AttachmentInfoProvider.DeleteAttachmentInfo(oldAttachment); } } }
/// <summary> /// Copies the file binary to the file system. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool CopyToFileSystem(int attachmentId, ref string name) { // Copy the file from database to the file system AttachmentInfo ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, true); if (ai != null) { name = ai.AttachmentName; // Ensure the physical file AttachmentInfoProvider.EnsurePhysicalFile(ai, GetSiteName(ai.AttachmentSiteID)); return true; } return false; }
/// <summary> /// Copies the file binary to the file system. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool CopyToFileSystem(int attachmentId, ref string name) { // Copy the file from database to the file system var ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, true); if (ai != null) { name = ai.AttachmentName; // Ensure the physical file AttachmentBinaryHelper.EnsurePhysicalFile((DocumentAttachment)ai); return(true); } return(false); }
public ActionResult GetFile() { File Page = _DynamicRouteHelper.GetPage <File>(); var Attachment = AttachmentInfoProvider.GetAttachmentInfo(Page.FileAttachment, SiteContext.CurrentSiteName); if (Attachment != null) { return(new FileStreamResult(new MemoryStream(Attachment.AttachmentBinary), Attachment.AttachmentMimeType) { FileDownloadName = Attachment.AttachmentName }); } else { return(HttpNotFound()); } }
/// <summary> /// Deletes the file binary from the database. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool DeleteFromDatabase(int attachmentId, ref string name) { // Delete the file in database and ensure it in the file system AttachmentInfo ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, false); if (ai != null) { name = ai.AttachmentName; AttachmentInfoProvider.EnsurePhysicalFile(ai, GetSiteName(ai.AttachmentSiteID)); // Clear the binary data ai.AttachmentBinary = null; ai.Generalized.UpdateData(); return true; } return false; }
/// <summary> /// Deletes the file binary from the database. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool DeleteFromDatabase(int attachmentId, ref string name) { // Delete the file in database and ensure it in the file system var ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, false); if (ai != null) { name = ai.AttachmentName; AttachmentBinaryHelper.EnsurePhysicalFile((DocumentAttachment)ai); // Clear the binary data ai.AttachmentBinary = null; ai.Generalized.UpdateData(); return(true); } return(false); }
/// <summary> /// Copies the file binary to the database. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool CopyToDatabase(int attachmentId, ref string name) { // Copy the file from file system to the database AttachmentInfo ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, true); if (ai != null) { name = ai.AttachmentName; if (ai.AttachmentBinary == null) { // Ensure the binary data ai.AttachmentBinary = AttachmentInfoProvider.GetFile(ai, GetSiteName(ai.AttachmentSiteID)); ai.Generalized.UpdateData(); return true; } } return false; }
private void AttachmentOnBeforeSave(object sender, ObjectEventArgs e) { if (e.Object == null) { return; } // If workflow enabled if (e.Object is AttachmentHistoryInfo attachmentVersion) { var latestAttachmentVersion = AttachmentHistoryInfoProvider.GetAttachmentHistories() .WhereEquals("AttachmentGUID", attachmentVersion.AttachmentGUID) .OrderByDescending("AttachmentLastModified") .TopN(1) .FirstOrDefault(); if (latestAttachmentVersion == null || latestAttachmentVersion.AttachmentSize != attachmentVersion.AttachmentSize) { var optimizer = new TinyPngImageOptimizer(SiteContext.CurrentSiteName); optimizer.Optimize(attachmentVersion); } } // If workflow disabled if (e.Object is AttachmentInfo attachment) { var document = DocumentHelper.GetDocument(attachment.AttachmentDocumentID, new TreeProvider()); if (document.WorkflowStep == null) { var currentAttachment = AttachmentInfoProvider.GetAttachmentInfo(attachment.AttachmentID, true); if (currentAttachment == null || currentAttachment.AttachmentSize != attachment.AttachmentSize) { var optimizer = new TinyPngImageOptimizer(SiteContext.CurrentSiteName); optimizer.Optimize(attachment); } } } }
/// <summary> /// Copies the file binary to the database. /// </summary> /// <param name="attachmentId">Attachment ID</param> /// <param name="name">Returning the attachment name</param> protected bool CopyToDatabase(int attachmentId, ref string name) { // Copy the file from file system to the database var ai = AttachmentInfoProvider.GetAttachmentInfo(attachmentId, true); if (ai != null) { name = ai.AttachmentName; if (ai.AttachmentBinary == null) { // Ensure the binary data ai.AttachmentBinary = AttachmentBinaryHelper.GetAttachmentBinary((DocumentAttachment)ai); ai.Generalized.UpdateData(); return(true); } } return(false); }
/// <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 (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.ShowError(GetString("attach.actiondenied")); SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.ShowError(GetString("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 (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null)) { VersionManager.CheckIn(node, null); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { var currentUser = MembershipContext.AuthenticatedUser; 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.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("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, MembershipContext.AuthenticatedUser)) { 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.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; } }
protected void RunInternal() { try { RunningInternal = true; ProgressMessageBuffer.Add("Starting cleaning process..."); var attachmentIDs = AttachmentInfoProvider .GetAttachments(null, "AttachmentName", false) .Select(att => att.AttachmentID); if (attachmentIDs == null) { return; } var sites = SiteInfoProvider.GetSites(); // Configure attachment storage setting keys. Mover won't work without this: SettingsKeyInfoProvider.SetValue("CMSStoreFilesInFileSystem", "True", false); SettingsKeyInfoProvider.SetValue("CMSStoreFilesInDatabase", "False", false); foreach (var aID in attachmentIDs) { if (Cancelled) { RunningInternal = false; Cancelled = false; return; } var att = AttachmentInfoProvider.GetAttachmentInfo(aID, false); var attSite = sites.FirstOrDefault(s => s.SiteID == att.AttachmentSiteID); if (attSite == null) { continue; } AttachmentInfoProvider.EnsurePhysicalFile(att, attSite.SiteName); att.AttachmentBinary = null; att.Generalized.UpdateData(); ProgressMessageBuffer.Add(att.AttachmentName + " copied to file system."); } ProgressMessageBuffer.Add("Cleaning Process Complete"); RunningInternal = false; } catch (Exception e) { ProgressMessageBuffer.Add("ERROR --------------------------"); ProgressMessageBuffer.Add(e.Message); ProgressMessageBuffer.Add(e.StackTrace); RunningInternal = false; } }
/// <summary> /// Saves metadata and file name of attachment. /// </summary> /// <param name="newFileName">New attachment file name</param> /// <returns>Returns True if attachment was successfully saved.</returns> private bool SaveAttachment(string newFileName) { bool saved = false; // Save new data try { DocumentAttachment attachment = InfoObject as DocumentAttachment; if (attachment != null) { // Set new file name if (!string.IsNullOrEmpty(newFileName)) { string name = newFileName + attachment.AttachmentExtension; attachment.AttachmentName = name; if (!IsAttachmentNameUnique(attachment)) { // Attachment already exists. ShowError(GetString("img.errors.fileexists")); return(false); } } // Ensure automatic check-in/ check-out bool autoCheck = false; var wm = WorkflowManager.GetInstance(TreeProvider); if (!nodeIsParent && (Node != null)) { var wi = wm.GetNodeWorkflow(Node); if (wi != null) { autoCheck = !wi.UseCheckInCheckOut(SiteName); } // Check out the document if (autoCheck) { var nextStep = VersionManager.CheckOut(Node, Node.IsPublished, true); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; if (IsWorkflowFinished(nextStep)) { attachment = (DocumentAttachment)AttachmentInfoProvider.GetAttachmentInfo(attachment.AttachmentGUID, SiteName); } } } if (attachment != null) { // Set filename title and description attachment.AttachmentTitle = ObjectTitle; attachment.AttachmentDescription = ObjectDescription; attachment.AllowPartialUpdate = true; DocumentHelper.UpdateAttachment(Node, attachment); if (!nodeIsParent && (Node != null)) { // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && (Node != null)) { VersionManager.CheckIn(Node, null); } } } } saved = true; string fullRefresh = "false"; if (autoCheck || (Node == null)) { fullRefresh = "true"; } // Refresh parent update panel LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachment.AttachmentGUID + "', 'refresh')"); } } } catch (Exception ex) { ShowError(GetString("metadata.errors.processing")); EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex); } return(saved); }
/// <summary> /// Saves metadata and file name of attachment. /// </summary> /// <param name="newFileName">New attachment file name</param> /// <returns>Returns True if attachment was successfully saved.</returns> private bool SaveAttachment(string newFileName) { bool saved = false; // Save new data try { AttachmentInfo attachmentInfo = InfoObject as AttachmentInfo; if (attachmentInfo != null) { // Set new file name if (!string.IsNullOrEmpty(newFileName)) { string name = newFileName + attachmentInfo.AttachmentExtension; if (IsAttachmentNameUnique(attachmentInfo, name)) { attachmentInfo.AttachmentName = name; } else { // Attachment already exists. ShowError(GetString("img.errors.fileexists")); return(false); } } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(TreeProvider); if (!nodeIsParent && (Node != null)) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(Node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(SiteName); } // 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)) { attachmentInfo = AttachmentInfoProvider.GetAttachmentInfo(attachmentInfo.AttachmentGUID, SiteName); } } if (attachmentInfo != null) { // Set filename title and description attachmentInfo.AttachmentTitle = ObjectTitle; attachmentInfo.AttachmentDescription = ObjectDescription; // Document uses workflow and document is already saved (attachment is not temporary) if (!nodeIsParent && (VersionHistoryID > 0)) { attachmentInfo.AllowPartialUpdate = true; VersionManager.SaveAttachmentVersion(attachmentInfo, VersionHistoryID); } else { // Update without binary attachmentInfo.AllowPartialUpdate = true; AttachmentInfoProvider.SetAttachmentInfo(attachmentInfo); // Log the synchronization and search task for the document if (!nodeIsParent && (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, TreeProvider); } } if (!nodeIsParent && (Node != null)) { // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && (Node != null)) { VersionManager.CheckIn(Node, null, null); } } } } saved = true; string fullRefresh = "false"; if (autoCheck || (Node == null)) { fullRefresh = "true"; } // Refresh parent update panel LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachmentInfo.AttachmentGUID + "', 'refresh')"); } } } catch (Exception ex) { ShowError(GetString("metadata.errors.processing")); EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex); } return(saved); }