Пример #1
0
    /// <summary>
    /// Ensures the info objects.
    /// </summary>
    private void LoadInfos()
    {
        switch (baseImageEditor.ImageType)
        {
        case ImageHelper.ImageTypeEnum.Metafile:

            if (mf == null)
            {
                mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true);
            }
            break;

        case ImageHelper.ImageTypeEnum.PhysicalFile:
            // Skip loading info for physical files
            break;

        default:
            if (ai == null)
            {
                baseImageEditor.Tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                // If using workflow then get versioned attachment
                if (VersionHistoryID != 0)
                {
                    ai = DocumentHelper.GetAttachment(attachmentGuid, VersionHistoryID);
                }
                // Else get file without binary data
                else
                {
                    ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
                }
            }
            break;
        }
    }
    /// <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);
    }
Пример #3
0
    /// <summary>
    /// Action button handler.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(drpAction.SelectedValue))
        {
            List <string> items = null;

            if (drpWhat.SelectedValue == "all")
            {
                // Get only the appropriate set of items
                string where = siteWhere;
                switch (drpAction.SelectedValue)
                {
                case "deleteindatabase":
                case "copytofilesystem":
                    // Only process those where binary is available in DB
                    where = SqlHelper.AddWhereCondition(where, "AttachmentBinary IS NOT NULL");
                    break;

                case "copytodatabase":
                    // Only copy those where the binary is missing
                    where = SqlHelper.AddWhereCondition(where, "AttachmentBinary IS NULL");
                    break;
                }

                // Get all, build the list of items
                DataSet ds = AttachmentInfoProvider.GetAttachments(where, gridFiles.SortDirect, false, 0, "AttachmentID");
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    items = new List <string>();

                    // Process all rows
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        int attachmentId = ValidationHelper.GetInteger(dr["AttachmentID"], 0);
                        items.Add(attachmentId.ToString());
                    }
                }
            }
            else
            {
                // Take selected items
                items = gridFiles.SelectedItems;
            }

            if ((items != null) && (items.Count > 0))
            {
                // Setup the async log
                pnlLog.Visible     = true;
                pnlContent.Visible = false;

                ctlAsyncLog.TitleText = drpAction.SelectedItem.Text;

                CurrentError = string.Empty;

                // Process the file asynchronously
                var parameter = new object[] { items, drpAction.SelectedValue };
                ctlAsyncLog.RunAsync(p => ProcessFiles(parameter), WindowsIdentity.GetCurrent());
            }
        }
    }
Пример #4
0
    private bool IsAttachmentNameUnique()
    {
        if (attachment != null)
        {
            // Use correct identifier if attachment is under workflow
            int identifier = VersionHistoryID > 0 ? GetAttachmentHistoryId() : attachment.AttachmentID;

            // Check that the name is unique in the document or version context
            Guid attachmentFormGuid = QueryHelper.GetGuid("formguid", Guid.Empty);
            bool nameIsUnique;
            if ((attachment.AttachmentFormGUID == Guid.Empty) || (attachmentFormGuid == Guid.Empty))
            {
                // Get the node
                nameIsUnique = DocumentHelper.AttachmentHasUniqueName(node, attachment);
            }
            else
            {
                nameIsUnique = AttachmentInfoProvider.IsUniqueTemporaryAttachmentName(attachmentFormGuid, attachment.AttachmentName, attachment.AttachmentExtension, identifier);
            }

            return(nameIsUnique);
        }

        return(false);
    }
Пример #5
0
        private void PageMoving(object sender, DocumentEventArgs e)
        {
            var node   = e.Node;
            var target = e.TargetParentNode;

            bool isAtSynchronizedSite       = _pageSync.IsAtSynchronizedSite(node);
            bool targetIsAtSynchronizedSite = _pageSync.IsAtSynchronizedSite(target);

            if (isAtSynchronizedSite != targetIsAtSynchronizedSite)
            {
                if (!targetIsAtSynchronizedSite)
                {
                    // Delete subtree when moving away from synchronized site
                    var subtree = _pageSync.GetSourceDocuments()
                                  .OnSite(node.NodeSiteName)
                                  .Path(node.NodeAliasPath, PathTypeEnum.Section)
                                  .AllCultures()
                                  .TypedResult
                                  .ToList();

                    var documentIds = subtree.Select(n => n.DocumentID).ToList();
                    var attachments = AttachmentInfoProvider.GetAttachments()
                                      .WhereIn("AttachmentDocumentID", documentIds)
                                      .BinaryData(false)
                                      .ExceptVariants()
                                      .TypedResult
                                      .ToList();

                    RunSynchronization(async() =>
                    {
                        var info = node.NodeAliasPath + "%";

                        await _pageSync.DeletePages(null, subtree, info);
                        await _assetSync.DeleteAttachments(null, attachments, info);
                    });
                }
                else
                {
                    // Sync subtree when moving to synchronized site
                    e.CallWhenFinished(() =>
                    {
                        var subtree = _pageSync.GetSourceDocuments()
                                      .OnSite(node.NodeSiteName)
                                      .Path(node.NodeAliasPath, PathTypeEnum.Section)
                                      .AllCultures()
                                      .WithCoupledColumns()
                                      .TypedResult
                                      .ToList();

                        RunSynchronization(async() =>
                        {
                            foreach (var page in subtree)
                            {
                                await _pageSync.SyncPageWithAllData(null, page);
                            }
                        });
                    });
                }
            }
        }
    /// <summary>
    /// Checks whether the name is unique.
    /// </summary>
    /// <param name="name">New attachment name</param>
    /// <param name="extension">New attachment extension. If null current is used.</param>
    private bool IsNameUnique(string name, string extension)
    {
        if (ai != null)
        {
            // Ensure extension is set
            extension = extension ?? ai.AttachmentExtension;

            // Use correct identifier if attachment is under workflow
            int identifier = VersionHistoryID > 0 ? AttachmentHistoryID : ai.AttachmentID;

            // Check that the name is unique in the document or version context
            Guid attachmentFormGuid = QueryHelper.GetGuid("formguid", Guid.Empty);
            bool nameIsUnique;
            if ((ai.AttachmentFormGUID == Guid.Empty) || (attachmentFormGuid == Guid.Empty))
            {
                // Get the node
                TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree);
                nameIsUnique = DocumentHelper.IsUniqueAttachmentName(node, name, extension, identifier, baseImageEditor.Tree);
            }
            else
            {
                nameIsUnique = AttachmentInfoProvider.IsUniqueTemporaryAttachmentName(attachmentFormGuid, name, extension, identifier);
            }

            return(nameIsUnique);
        }

        return(false);
    }
Пример #7
0
    /// <summary>
    /// Updates parameters used by Edit button when displaying image editor.
    /// </summary>
    /// <param name="attachmentGuidString">GUID identifying attachment</param>
    private void UpdateEditParameters(string attachmentGuidString)
    {
        if (ShowTooltip)
        {
            // Try to get attachment GUID
            Guid attGuid = ValidationHelper.GetGuid(attachmentGuidString, Guid.Empty);
            if (attGuid != null)
            {
                // Get attachment
                AttachmentInfo attInfo = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attGuid, SiteName);
                if (attInfo != null)
                {
                    // Get attachment URL
                    string attachmentUrl = null;
                    if (Node != null)
                    {
                        attachmentUrl = CMSContext.ResolveUIUrl(TreePathUtils.GetAttachmentUrl(attGuid, URLHelper.GetSafeFileName(attInfo.AttachmentName, CMSContext.CurrentSiteName), VersionHistoryID, null));
                    }
                    else
                    {
                        attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attGuid, VersionHistoryID));
                    }
                    attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                    // Ensure correct URL
                    if (OriginalNodeSiteName != CMSContext.CurrentSiteName)
                    {
                        attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName);
                    }

                    // Generate new tooltip command
                    string newToolTip  = null;
                    string title       = attInfo.AttachmentTitle;
                    string description = attInfo.AttachmentDescription;
                    // Optionally trim attachment name
                    string attachmentName = TextHelper.LimitLength(attInfo.AttachmentName, ATTACHMENT_NAME_LIMIT, "...");
                    int    imageWidth     = attInfo.AttachmentImageWidth;
                    int    imageHeight    = attInfo.AttachmentImageHeight;
                    bool   isImage        = ImageHelper.IsImage(attInfo.AttachmentExtension);

                    int    tooltipWidth = 300;
                    string url          = isImage ? attachmentUrl : null;

                    string tooltipBody = UIHelper.GetTooltip(url, imageWidth, imageHeight, title, attachmentName, description, null, ref tooltipWidth);
                    if (!string.IsNullOrEmpty(tooltipBody))
                    {
                        newToolTip = String.Format("Tip('{0}', WIDTH, -300)", tooltipBody);
                    }

                    // Get update script
                    string updateScript = String.Format("$j(\"#{0}\").attr('onmouseover', '').unbind('mouseover').mouseover(function(){{ {1} }});", attGuid, newToolTip);

                    // Execute update
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "AttachmentUpdateEdit", ScriptHelper.GetScript(updateScript));
                }
            }
        }
    }
        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");
                        }
                    }
                }
            }
        }
 protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e)
 {
     switch (e.CommandName)
     {
     case "clearcache":
         AttachmentInfoProvider.ClearSearchCache();
         ShowConfirmation(GetString("srch.attachmentcachedcleared"));
         break;
     }
 }
Пример #10
0
 protected PageModel GetPageModel()
 {
     return(new PageModel
     {
         TotalAttachments = AttachmentInfoProvider.GetCount(),
         TotalAttachmentHistories = AttachmentHistoryInfoProvider.GetCount(),
         AttachmentHistoryRemoverIsRunning = AttachmentHistoryRemover.Running,
         AttachmentMoverIsRunning = AttachmentMover.Running,
     });
 }
Пример #11
0
    /// <summary>
    /// Returns URL of the media item according site settings.
    /// </summary>
    /// <param name="nodeGuid">Node GUID of the current attachment node</param>
    /// <param name="documentUrlPath">URL path of the current attachment document</param>
    /// <param name="nodeAlias">Node alias of the current attachment node</param>
    /// <param name="nodeAliasPath">Node alias path of the current attachment node</param>
    /// <param name="nodeIsLink">Indicates if node is linked node.</param>
    /// <param name="height">Height of the attachment</param>
    /// <param name="width">Width of the attachment</param>
    /// <param name="maxSideSize">Maximum dimension for images displayed for thumbnails view</param>
    /// <param name="notAttachment">Indicates if item is not attachment</param>
    /// <param name="documentExtension">Document extension</param>
    public string GetContentItemUrl(Guid nodeGuid, string documentUrlPath, string nodeAlias, string nodeAliasPath, bool nodeIsLink, int height, int width, int maxSideSize, bool notAttachment, string documentExtension)
    {
        string result;

        if (documentExtension.Contains(";"))
        {
            documentExtension = documentExtension.Split(';')[0];
        }

        // Generate URL
        if (UsePermanentUrls)
        {
            bool isLink = ((OutputFormat == OutputFormatEnum.BBLink) || (OutputFormat == OutputFormatEnum.HTMLLink)) ||
                          ((OutputFormat == OutputFormatEnum.URL) && (SelectableContent == SelectableContentEnum.AllContent));

            if (String.IsNullOrEmpty(nodeAlias))
            {
                nodeAlias = "default";
            }

            if (notAttachment || isLink)
            {
                result = DocumentURLProvider.GetPermanentDocUrl(nodeGuid, nodeAlias, SiteObj.SiteName, null, documentExtension);
            }
            else
            {
                result = AttachmentInfoProvider.GetPermanentAttachmentUrl(nodeGuid, nodeAlias, documentExtension);
            }
        }
        else
        {
            string docUrlPath = nodeIsLink ? null : documentUrlPath;

            // Ensure live site view mode for URLs edited in on-site edit mode
            if (PortalContext.ViewMode.IsEditLive())
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.LiveSite);
            }

            result = DocumentURLProvider.GetUrl(nodeAliasPath, docUrlPath, SiteObj.SiteName, null, documentExtension);
        }

        // Make URL absolute if required
        int currentSiteId = SiteContext.CurrentSiteID;

        if (Config.UseFullURL || (currentSiteId != SiteObj.SiteID) || (currentSiteId != GetCurrentSiteId()))
        {
            result = URLHelper.GetAbsoluteUrl(result, SiteObj.DomainName, URLHelper.GetApplicationUrl(SiteObj.DomainName), null);
        }

        return(AddURLDimensionsAndResolve(result, height, width, maxSideSize));
    }
Пример #12
0
    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);
        }
    }
        protected void RunInternal(int daysBeforeLastModified, int maxAllowedVersions)
        {
            try
            {
                RunningInternal = true;

                ProgressMessageBuffer.Add("Starting attachment history removal process...");
                ProgressMessageBuffer.Add(string.Format(
                                              "Limiting attachments older than {0} days to no more than {1} versions",
                                              daysBeforeLastModified,
                                              maxAllowedVersions
                                              ));

                var cutoffDate = DateTime.Today.AddDays(-daysBeforeLastModified);

                var cutoffDateString = string.Format("{0}-{1}-{2}", cutoffDate.Year, cutoffDate.Month + 1, cutoffDate.Day);

                var where = string.Format("AttachmentLastModified < '{0}'", cutoffDateString);

                ProgressMessageBuffer.Add(where);

                var attachments = AttachmentInfoProvider.GetAttachments(where, "AttachmentName", false, 0);

                ProgressMessageBuffer.Add(string.Format("Found {0} attachments last modified before {1}.", attachments.Count, cutoffDateString));

                foreach (var att in attachments)
                {
                    if (Cancelled)
                    {
                        ProgressMessageBuffer.Add("Attachment history removal process cancelled.");
                        return;
                    }

                    TruncateAttachmentHistory(att, maxAllowedVersions);
                }

                ProgressMessageBuffer.Add("Attachment history removal process complete.");

                RunningInternal = false;
            }
            catch (Exception e)
            {
                ProgressMessageBuffer.Add("Removal stopped after encountering error.");
                ProgressMessageBuffer.Add(e.StackTrace);
                ProgressMessageBuffer.Add(e.Message);
                ProgressMessageBuffer.Add("ERROR --------------------------");

                EventLogProvider.LogEvent(new EventLogInfo("SPRING CLEANING", e.StackTrace, "REMOVE ATTACHMENT HISTORY"));

                RunningInternal = false;
            }
        }
        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);
                }
            }
        }
Пример #15
0
        private IList <Guid> GetAttachmentGuids(TreeNode node, FormFieldInfo attachmentsField)
        {
            var guidsQuery = AttachmentInfoProvider.GetAttachments(node.DocumentID, false)
                             .ExceptVariants()
                             .Columns("AttachmentGUID")
                             .OrderBy("AttachmentOrder");

            var narrowedQuery = (attachmentsField != null)
                ? guidsQuery.WhereEquals("AttachmentGroupGUID", attachmentsField.Guid)
                : guidsQuery.WhereTrue("AttachmentIsUnsorted");

            var guids = narrowedQuery
                        .GetListResult <Guid>();

            return(guids);
        }
    /// <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;
    }
Пример #17
0
        public async Task SyncAllAttachments(CancellationToken?cancellation, TreeNode node)
        {
            try
            {
                SyncLog.LogEvent(EventType.INFORMATION, "KenticoKontentPublishing", "SYNCALLATTACHMENTS", node.NodeAliasPath);

                var attachments = AttachmentInfoProvider.GetAttachments(node.DocumentID, false);

                await SyncAttachments(cancellation, attachments);
            }
            catch (Exception ex)
            {
                SyncLog.LogException("KenticoKontentPublishing", "SYNCALLATTACHMENTS", ex);
                throw;
            }
        }
Пример #18
0
        /// <summary>
        /// Gets search items filled with all necessary properties from SearchContext.CurrentSearchResults and mRawResults collection.
        /// </summary>
        /// <returns>Search items collection</returns>
        private IEnumerable <SearchResultItem> GetSearchItems()
        {
            var searchItems = new List <SearchResultItem>();

            if (DataHelper.DataSourceIsEmpty(SearchContext.CurrentSearchResults) || (mRawResults == null) || (SearchContext.CurrentSearchResults == null))
            {
                return(null);
            }

            var attachmentIdentifiers = new List <Guid>();

            foreach (DataRow row in mRawResults.Tables[0].Rows)
            {
                string date, pageTypeDisplayName, pageTypeCodeName;
                int    nodeId;
                var    documentNodeId = GetDocumentNodeId(row["type"], row["id"]);
                var    guid           = ((row["image"] as string) == null) ? Guid.Empty : new Guid(row["image"].ToString());
                attachmentIdentifiers.Add(guid);

                GetAdditionalData(row["type"], documentNodeId, out date, out nodeId, out pageTypeDisplayName, out pageTypeCodeName);

                var searchItem = new SearchResultItem
                {
                    NodeId             = nodeId,
                    Title              = row["title"].ToString(),
                    Content            = row["content"].ToString(),
                    Date               = date,
                    PageTypeDispayName = pageTypeDisplayName,
                    PageTypeCodeName   = pageTypeCodeName
                };

                searchItems.Add(searchItem);
            }

            var attachments = AttachmentInfoProvider.GetAttachments().OnSite(mSiteName).BinaryData(false).WhereIn("AttachmentGUID", attachmentIdentifiers).ToDictionary(x => x.AttachmentGUID);

            for (int i = 0; i < searchItems.Count; i++)
            {
                AttachmentInfo attachment = null;
                if (attachments.TryGetValue(attachmentIdentifiers[i], out attachment))
                {
                    searchItems[i].ImageAttachment = new Attachment(attachment);
                }
            }

            return(searchItems);
        }
    /// <summary>
    /// Ensures the info objects.
    /// </summary>
    private void LoadInfos()
    {
        switch (baseImageEditor.ImageType)
        {
        default:
        case ImageHelper.ImageTypeEnum.Attachment:

            if (ai == null)
            {
                baseImageEditor.Tree = new TreeProvider(CMSContext.CurrentUser);

                // If using workflow then get versioned attachment
                if (VersionHistoryID != 0)
                {
                    AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid);
                    if (attachmentVersion == null)
                    {
                        ai = null;
                    }
                    else
                    {
                        ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
                        ai.AttachmentID = attachmentVersion.AttachmentHistoryID;
                    }
                }
                // else get file without binary data
                else
                {
                    ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
                }
            }
            break;

        case ImageHelper.ImageTypeEnum.Metafile:

            if (mf == null)
            {
                mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true);
            }
            break;

        case ImageHelper.ImageTypeEnum.PhysicalFile:
            // Skip loading info for physical files
            break;
        }
    }
Пример #20
0
    /// <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);
    }
Пример #21
0
        private void PageDeleting(object sender, DocumentEventArgs e)
        {
            var node = e.Node;

            if (_pageSync.IsAtSynchronizedSite(node))
            {
                var attachments = AttachmentInfoProvider.GetAttachments(node.DocumentID, false)
                                  .ExceptVariants()
                                  .TypedResult
                                  .ToList();

                RunSynchronization(async() => {
                    await _pageSync.DeletePage(node);
                    await _assetSync.DeleteAttachments(null, attachments, node.NodeAliasPath);
                });
            }
        }
Пример #22
0
        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>
    /// Checks whether the name is unique.
    /// </summary>
    private bool IsAttachmentNameUnique(DocumentAttachment attachment)
    {
        // Check that the name is unique in the document or version context
        Guid attachmentFormGuid = QueryHelper.GetGuid("formguid", Guid.Empty);
        bool nameIsUnique;

        if (attachmentFormGuid == Guid.Empty)
        {
            // Get the node
            nameIsUnique = DocumentHelper.AttachmentHasUniqueName(Node, attachment);
        }
        else
        {
            nameIsUnique = AttachmentInfoProvider.IsUniqueTemporaryAttachmentName(attachmentFormGuid, attachment.AttachmentName, attachment.AttachmentExtension, attachment.AttachmentID);
        }

        return(nameIsUnique);
    }
    /// <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;
    }
Пример #25
0
        public async Task SyncAllAttachments(CancellationToken?cancellation)
        {
            try
            {
                SyncLog.Log("Synchronizing page attachments");

                SyncLog.LogEvent(EventType.INFORMATION, "KenticoKontentPublishing", "SYNCALLATTACHMENTS");

                var attachments = AttachmentInfoProvider.GetAttachments()
                                  .OnSite(Settings.Sitename);

                await SyncAttachments(cancellation, attachments);
            }
            catch (Exception ex)
            {
                SyncLog.LogException("KenticoKontentPublishing", "SYNCALLATTACHMENTS", ex);
                throw;
            }
        }
Пример #26
0
    /// <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>
    /// 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;
    }
Пример #28
0
    /// <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);
    }
        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);
                    }
                }
            }
        }
Пример #30
0
    /// <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);
    }