private static AttachmentInfo DownloadAttachmentThumbnail(SKUTreeNode product, string fromUrl) { if (product.SKU == null) { throw new ArgumentNullException(nameof(product.SKU)); } using (var client = new HttpClient()) { using (var request = new HttpRequestMessage(HttpMethod.Get, fromUrl)) { using (var response = client.SendAsync(request).Result) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { var mimetype = response.Content?.Headers?.ContentType?.MediaType ?? string.Empty; if (!mimetype.StartsWith("image/")) { throw new Exception("Thumbnail is not of image MIME type"); } var stream = response.Content.ReadAsStreamAsync().Result; var extension = Path.GetExtension(fromUrl); if (string.IsNullOrEmpty(extension) && mimetype.StartsWith("image/")) { extension = mimetype.Split('/')[1]; } // attach file as page attachment and set it's GUID as ProductThumbnail (of type guid) property of Product var newAttachment = new AttachmentInfo() { InputStream = stream, AttachmentSiteID = product.NodeSiteID, AttachmentDocumentID = product.DocumentID, AttachmentExtension = extension, AttachmentName = $"Thumbnail{product.SKU.GetStringValue("SKUProductCustomerReferenceNumber", product.SKU.SKUNumber)}.{extension}", AttachmentLastModified = DateTime.Now, AttachmentMimeType = mimetype, AttachmentSize = (int)stream.Length }; AttachmentInfoProvider.SetAttachmentInfo(newAttachment); return(newAttachment); } else { throw new Exception("Failed to download thumbnail image"); } } } } }
/// <summary> /// Gets an attachment and modifies its metadata(name, title and description). Called when the "Edit attachment metadata" button is pressed. /// Expects the "Create example document" and "Insert unsorted attachment" methods to be run first. /// </summary> private bool EditMetadata() { // 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) { string where = "AttachmentIsUnsorted = 1"; string orderBy = "AttachmentLastModified DESC"; // Get the document's unsorted attachments with the latest on top DataSet attachments = DocumentHelper.GetAttachments(node, where, orderBy, false, tree); if (!DataHelper.DataSourceIsEmpty(attachments)) { // Create attachment info object from the first DataRow AttachmentInfo attachment = new AttachmentInfo(attachments.Tables[0].Rows[0]); // Edit its metadata attachment.AttachmentName += " - modified"; attachment.AttachmentTitle += "Example title"; attachment.AttachmentDescription += "This is an example of an unsorted attachment."; // Ensure that the attachment can be updated without supplying its binary data. attachment.AllowPartialUpdate = true; // Save the object into database AttachmentInfoProvider.SetAttachmentInfo(attachment); return(true); } else { apiEditMetadata.ErrorMessage = "No attachments were found."; } } 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; } }
/// <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); }