private void OpenAttachment()
        {
            if (_selectedAttachmentIndex == -1)
            {
                return;
            }

            LEADDocument currentDocument = _documentViewer.Document;

            // The attachment has a document ID if it is already saved into the cache, if so, just load it
            int attachmentIndex           = _selectedAttachmentIndex;
            DocumentAttachment attachment = currentDocument.Attachments[attachmentIndex];

            if (!string.IsNullOrEmpty(attachment.DocumentId))
            {
                LoadDocumentFromCache(attachment.DocumentId);
            }
            else
            {
                // If our document is cached, then save the attachment to cache and open it from there
                // Otherwise, load it into a stream as a brand new document

                if (IsDocumentInCache(currentDocument))
                {
                    CreateAttachmentDocumentFromCache(currentDocument, attachment);
                }
                else
                {
                    CreateAttachmentDocument(currentDocument, attachment);
                }
            }
        }
        private DocumentAttachment ParseDocAttachment(JObject _jDoc)
        {
            try
            {
                if (_jDoc[PAttachmentsDocument] is JObject jDoc)
                {
                    var docAttachment = new DocumentAttachment();

                    docAttachment.Id        = jDoc[PId].Value <int>();
                    docAttachment.OwnerId   = jDoc[PAttachmentOwnerId].Value <int>();
                    docAttachment.Title     = jDoc[PTitle]?.Value <string>();
                    docAttachment.Date      = EpochTimeConverter.ConvertToDateTime(jDoc[PDate].Value <long>());
                    docAttachment.Url       = jDoc[PUrl].Value <string>();
                    docAttachment.AccessKey = jDoc[PAttachmentAccessKey]?.Value <string>();

                    return(docAttachment);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to parse doc attachment \n {_jDoc.ToString()}", ex);
            }

            throw new DeserializerException($"Failed recognize jObject as document attachment \n {_jDoc?.ToString()}");
        }
 private static void SaveAttachmentToStream(LEADDocument document, DocumentAttachment attachment, Stream stream)
 {
     using (var inputStream = document.Attachments.CreateAttachmentStream(attachment.AttachmentNumber, null))
     {
         inputStream.CopyTo(stream);
     }
 }
Beispiel #4
0
        protected void ctlRemove_OnClick(object sender, ImageClickEventArgs e)
        {
            #region Old Code Comment By AO 5-Mar-2009
            //IList<DocumentAttachment> documentAttachmentList = new List<DocumentAttachment>();
            //foreach (GridViewRow row in ctlAttachmentGrid.Rows)
            //{
            //    if ((row.RowType == DataControlRowType.DataRow) && (((CheckBox)row.FindControl("ctlSelect")).Checked))
            //    {
            //        long attachmentID = UIHelper.ParseLong(ctlAttachmentGrid.DataKeys[row.RowIndex].Values["AttachmentID"].ToString());

            //        // Remove from transaction service.
            //    }
            //}
            #endregion

            foreach (GridViewRow row in ctlAttachmentGrid.Rows)
            {
                if ((row.RowType == DataControlRowType.DataRow) && (((CheckBox)row.FindControl("ctlSelect")).Checked))
                {
                    long attachmentID = UIHelper.ParseLong(ctlAttachmentGrid.DataKeys[row.RowIndex].Values["AttachmentID"].ToString());

                    // Remove from transaction.
                    DocumentAttachment documentAttachment = new DocumentAttachment(attachmentID);
                    DocumentAttachmentService.DeleteAttachmentFromTransaction(this.TransactionID, documentAttachment);
                }
            }

            this.BindControl();
            ctlUpdateAttachmentGrid.Update();
        }
#pragma warning restore 1998

        private void DownloadAttachment(DocumentAttachment attachment, IExecutionContext context)
        {
            var fileName    = $"{StatiqHelper.AttachmentPath}/{attachment.AttachmentName}";
            var destination = context.FileSystem.GetOutputFile(fileName);

            if (!destination.Exists)
            {
                var thread = new CMSThread(() =>
                {
                    try
                    {
                        var binary = AttachmentBinaryHelper.GetAttachmentBinary(attachment);
                        using (Stream fileStream = destination.OpenWrite(true))
                        {
                            long initialPosition = fileStream.Position;
                            fileStream.Write(binary, 0, binary.Length);
                            long length = fileStream.Position - initialPosition;
                            fileStream.SetLength(length);
                        }
                    }
                    catch (Exception e) {
                        Console.WriteLine(e.Message);
                    }
                });
                thread.Start();
            }
        }
Beispiel #6
0
        public ActionResult SoftwareUploadClick(string version, string type, string plistUrl)
        {
            var result          = new DirectResult();
            var fileUploadField = this.GetCmp <FileUploadField>("fileUploadField");

            if (fileUploadField.HasFile)
            {
                try
                {
                    string postedFileName = GetPostedFileName(fileUploadField.PostedFile.FileName);
                    postedFileName = ChinesePinYin.GetPinYin(postedFileName);
                    var    documentAttachment = new DocumentAttachment(GetFilePath(type, GetSoftwareBaseFolder()));
                    string filePath           = documentAttachment.GetFileName(postedFileName);
                    string url = GetUrl(type, GetSoftwareMuLu(), postedFileName);
                    fileUploadField.PostedFile.SaveAs(filePath);
                    SaveSoftwareFilePathToDbstring(version, type, url, plistUrl);
                    X.Msg.Show(MessageBoxConfig(Success, TiShi, MessageBox.Icon.INFO));
                }
                catch (Exception ex)
                {
                    X.Msg.Show(MessageBoxConfig(ex.ToString(), Fail, MessageBox.Icon.INFO));
                }
                finally
                {
                    PushMessageToTag(type.ToLower(), version, "all", 1, -1, string.Empty, string.Empty, 0);
                }
            }
            else
            {
                result.IsUpload = true;
                X.Msg.Show(MessageBoxConfig(NoFile, TiShi, MessageBox.Icon.ERROR));
            }
            return(result);
        }
Beispiel #7
0
        // Returns the relative path to the first attachment selected via the page attachment selector component
        private string GetAttachmentUrl(IEnumerable <AttachmentSelectorItem> attachments)
        {
            Guid attachmentGuid = attachments.FirstOrDefault()?.FileGuid ?? Guid.Empty;

            DocumentAttachment attachment = DocumentHelper.GetAttachment(attachmentGuid, siteService.CurrentSite.SiteName);

            return(attachmentUrlRetriever.Retrieve(attachment).RelativePath);
        }
        private static string GetFileTypeFromContentTypeValue(DocumentAttachment control)
        {
            if (control.FileType.Equals("application/vnd.openxmlformats-officedocument.presentationml.presentation"))
            {
                return("ppx");
            }

            return(control.FileType.Substring(control.FileType.IndexOf("/") + 1));
        }
Beispiel #9
0
        /// <summary>
        /// Generates an IMG tag for an attachment.
        /// </summary>
        /// <param name="htmlHelper">HTML helper.</param>
        /// <param name="attachment">Attachment object.</param>
        /// <param name="title">Title.</param>
        /// <param name="cssClassName">CSS class.</param>
        /// <param name="constraint">Size constraint.</param>
        public static MvcHtmlString AttachmentImage(this HtmlHelper htmlHelper, DocumentAttachment attachment, string title = "", string cssClassName = "", SizeConstraint?constraint = null)
        {
            if (attachment == null)
            {
                return(MvcHtmlString.Empty);
            }

            return(Image(htmlHelper, attachment.GetPath(), title, cssClassName, constraint));
        }
    private static string GetDisplayedName(DocumentAttachment attachment)
    {
        var displayedName = TextHelper.LimitLength(attachment.AttachmentName, AttachmentsControl.ATTACHMENT_NAME_LIMIT);

        if (!String.IsNullOrEmpty(attachment.AttachmentVariantDefinitionIdentifier))
        {
            displayedName = ResHelper.GetAPIString("AttachmentVariant." + attachment.AttachmentVariantDefinitionIdentifier, attachment.AttachmentVariantDefinitionIdentifier);
        }

        return(displayedName);
    }
        private ActionResult AuthenticationCallback()
        {
            Session[EXACT_AUTH_STATE] = client.ProcessUserAuthorization(this.Request);

            // Call ExactOnline SDK
            ExactOnlineClient exact = new ExactOnlineClient(ConfigurationManager.AppSettings["exactOnlineUrl"], AccessTokenManager);

            UserLogin token = Session[DropboxController.DROPBOX_ACCESS_TOKEN] as UserLogin;

            List <DocumentCategory> categories = exact.For <DocumentCategory>().Select(new string[] { "ID", "Description" }).Get();

            Dropbox dropbox = new Dropbox(token, true);
            IEnumerable <string>      fileNames     = dropbox.GetNewDocumentNames();
            Dictionary <Guid, string> newReferences = new Dictionary <Guid, string>();

            foreach (string fileName in fileNames)
            {
                byte[] file = dropbox.GetFileBytes(fileName);
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);

                Document document = new Document()
                {
                    Subject      = fileNameWithoutExtension,
                    Body         = fileNameWithoutExtension,
                    Type         = 55,
                    DocumentDate = DateTime.Now.Date,
                    Category     = categories[3].ID
                };

                bool createdDocument = exact.For <Document>().Insert(ref document);

                DocumentAttachment attachment = new DocumentAttachment()
                {
                    Document   = document.ID,
                    FileName   = fileName,
                    FileSize   = (double)file.Length,
                    Attachment = file
                };

                bool createdAttachment = exact.For <DocumentAttachment>().Insert(ref attachment);

                newReferences.Add(document.ID, fileName);
            }

            Dictionary <Guid, string> existingReferences = dropbox.GetExactOnlineReferences();

            dropbox.UpdateExactOnlineReferences(existingReferences, newReferences);

            return(View());
            // Later, if necessary:
            // bool success = client.RefreshAuthorization(auth);
        }
Beispiel #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);
        }
    }
Beispiel #13
0
        public void ConnectToExactOnline2Upload(string srcFolder, string srcFilename)
        {
            try
            {
                // To make this work set the authorisation properties of your test app in the testapp.config.
                var testApp = new TestApp();

                var connector = new Connector(testApp.ClientId.ToString(), testApp.ClientSecret, testApp.CallbackUrl);
                var client    = new ExactOnlineClient(connector.EndPoint, connector.GetAccessToken);

                //Create document which to relate documentattachment to
                ExactOnline.Client.Models.Documents.Document document = new ExactOnline.Client.Models.Documents.Document
                {
                    Subject      = Path.GetFileNameWithoutExtension(srcFilename),
                    Body         = Path.GetFileNameWithoutExtension(srcFilename),
                    Category     = GeneralCategory,
                    Type         = MiscDocType,
                    DocumentDate = DateTime.Now.Date
                };

                bool created = client.For <ExactOnline.Client.Models.Documents.Document>().Insert(ref document);

                if (created)
                {
                    //convert attachment into byte array
                    byte[] attachment = System.IO.File.ReadAllBytes(srcFolder + "/" + srcFilename);

                    //Create DocumentAttachment
                    DocumentAttachment documentAttachment = new DocumentAttachment
                    {
                        Document   = document.ID, //relate DocumentAttachment to previously created document
                        Attachment = attachment,
                        FileName   = srcFilename
                    };

                    created = client.For <DocumentAttachment>().Insert(ref documentAttachment);
                    Console.WriteLine("Saved to ExactOnline {0} attachmentID {1}", srcFilename, documentAttachment.ID);
                }
                else
                {
                    Console.WriteLine("Unable to create document");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured: {0}", ex.Message);
            }
        }
        public void InsertOrUpdate(DocumentAttachment docattach)
        {
            //ToDo Context initialization

            if (docattach.DocAttachId == default(int))
            {
                // New entity

                _context.DocumentAttachment.Add(docattach);
            }
            else
            {
                // Update existing entity
                _context.Entry(docattach).State = EntityState.Modified;
            }
        }
Beispiel #15
0
        public void Is_Passed_An_Object_Of_Attachment_Then_Render_Returns_The_Html(AttachmentControlRenderer renderer)
        {
            var attachment = new DocumentAttachment()
            {
                Url         = "http://image.url",
                Description = "description",
                Title       = "title",
                FileSize    = 1000,
                FileType    = "application/pdf"
            };

            var actual = renderer.Render(attachment);

            actual.Value.Should().NotBeNullOrWhiteSpace();
            actual.Value.Should().Be("<div class=\"fiu-attachment\"><h2 class=\"govuk-heading-m fiu-attachment__heading\">title</h2><dl class=\"fiu-attachment__meta\"><dt class=\"fiu-attachment__meta-title\">File type</dt><dd class=\"fiu-attachment__meta-description\">pdf</dd><dt class=\"fiu-attachment__meta-title\">File size</dt><dd class=\"fiu-attachment__meta-description\">1KB</dd></dl><p class=\"govuk-body fiu-attachment__description\">description</p><p class=\"govuk-body fiu-attachment__link-wrap\"><a href=\"http://image.url\" class=\"govuk-link fiu-attachment__link\" target=\"_blank\">Download <span class=\"fiu-vh\">title</span></a></p><span class=\"fiu-attachment__icon\"><span class=\"fiu-attachment__icon-label\">pdf</span></span></div>");
        }
Beispiel #16
0
    private void LoadAttachment()
    {
        if (attachment == null)
        {
            baseImageEditor.Tree = new TreeProvider(MembershipContext.AuthenticatedUser);

            attachment = DocumentHelper.GetAttachment(attachmentGuid, CurrentSiteName, true, out node);

            if ((attachment != null) && (attachment.AttachmentFormGUID != Guid.Empty))
            {
                // Get parent node ID in case attachment is edited for document not created yet (temporary attachment)
                int parentNodeId = QueryHelper.GetInteger("parentId", 0);

                node = baseImageEditor.Tree.SelectSingleNode(parentNodeId);
            }
        }
    }
        private void ShowAttachmentProperties()
        {
            if (_selectedAttachmentIndex == -1)
            {
                return;
            }

            int attachmentIndex = _selectedAttachmentIndex;

            LEADDocument       currentDocument = this._documentViewer.Document;
            DocumentAttachment attachment      = currentDocument.Attachments[attachmentIndex];

            using (var dlg = new UI.AttachmentPropertiesDialog())
            {
                dlg.Attachment = attachment;
                dlg.ShowDialog(this);
            }
        }
Beispiel #18
0
 /// <summary>Builds a custom token dictionary for a document attachment.</summary>
 /// <param name="attachment">The attachment.</param>
 /// <returns>The custom token dictinoary for a document attachment.</returns>
 private Dictionary <string, string> BuildAttachmentTokenDictionary(DocumentAttachment attachment)
 {
     return(new Dictionary <string, string>
     {
         { "Attachment:DocumentAttachmentKey", attachment.DocumentAttachmentKey.ToString() },
         { "Attachment:DocumentKey", attachment.DocumentKey.ToString() },
         { "Attachment:FileName", attachment.FileName },
         { "Attachment:UploadedByContact", attachment.UploadedByContact.ToString() },
         { "Attachment:CreatedOn", attachment.CreatedOn.ToString(this.DateFormat, CultureInfo.CurrentCulture) },
         { "Attachment:FileExtension", attachment.FileExtension },
         { "Attachment:FileSizeInBytes", attachment.FileSizeInBytes.ToString() },
         { "Attachment:Width", attachment.Width.ToString() },
         { "Attachment:Height", attachment.Height.ToString() },
         { "Attachment:DurationSeconds", attachment.DurationSeconds.ToString() },
         { "Attachment:DownloadUrl", attachment.DownloadUrl },
         { "Attachment:IconUrl", attachment.IconUrl },
     });
 }
    /// <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);
    }
    private static string GetTooltip(DocumentAttachment attachment, string attachmentUrl, string name)
    {
        string title       = null;
        string description = null;

        var imageWidth  = attachment.AttachmentImageWidth;
        var imageHeight = attachment.AttachmentImageHeight;

        if (String.IsNullOrEmpty(attachment.AttachmentVariantDefinitionIdentifier))
        {
            title       = attachment.AttachmentTitle;
            description = attachment.AttachmentDescription;
        }

        var tooltip = UIHelper.GetTooltipAttributes(attachmentUrl, imageWidth, imageHeight, title, name, attachment.AttachmentExtension, description, null, 300);

        return(tooltip);
    }
        private void CreateAttachmentDocumentFromCache(LEADDocument currentDocument, DocumentAttachment attachment)
        {
            try
            {
                // Save it int the cache
                var options = new SaveAttachmentToCacheOptions();
                options.AttachmentNumber            = attachment.AttachmentNumber;
                options.UploadDocumentOptions.Cache = this._cache;
                // This will update DocumentAttachment.DocumentId
                currentDocument.SaveAttachmentToCache(options);

                string attachmentDocumentId = attachment.DocumentId;
                this.LoadDocumentFromCache(attachmentDocumentId);
            }
            catch (Exception ex)
            {
                UI.Helper.ShowError(this, ex);
            }
        }
Beispiel #22
0
        public ActionResult Index()
        {
            // Retrieves the GUID of the first selected attachment from the 'Attachments' property
            Guid guid = propertiesRetriever.Retrieve <CustomWidgetProperties>().Attachments.FirstOrDefault()?.FileGuid ?? Guid.Empty;
            // Retrieves the DocumentAttachment object that corresponds to the selected attachment GUID
            DocumentAttachment attachment = DocumentHelper.GetAttachment(guid, siteService.CurrentSite.SiteID);

            string url = String.Empty;

            if (attachment != null)
            {
                // Retrieves the relative URL of the selected attachment
                url = attachmentUrlRetriever.Retrieve(attachment).RelativePath;
            }

            // Custom logic...

            return(View());
        }
        public ActionResult AttachDocument(DocumentAttachmentViewModel vm)
        {
            if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
            {
                UploadDocument ud        = new UploadDocument();
                string         FileNames = "";
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    string FileName   = "";
                    string FolderName = "";

                    ud.UploadFile(i, new Dictionary <string, string>(), vm.DocTypeId + "_" + vm.DocId, Constants.FileTypeConstants.Other, out FolderName, out FileName);

                    DocumentAttachment da = new DocumentAttachment();

                    da.DocId          = vm.DocId;
                    da.DocTypeId      = vm.DocTypeId;
                    da.FileFolderName = FolderName;
                    da.FileName       = FileName;
                    da.CreatedBy      = User.Identity.Name;
                    da.CreatedDate    = DateTime.Now;
                    da.ModifiedBy     = User.Identity.Name;
                    da.ModifiedDate   = DateTime.Now;
                    da.ObjectState    = Model.ObjectState.Added;
                    db.DocumentAttachment.Add(da);

                    FileNames += da.FileName + ", ";
                }

                db.SaveChanges();

                //LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                //{
                //    DocTypeId = vm.DocTypeId,
                //    DocId = vm.DocId,
                //    ActivityType = (int)ActivityTypeContants.FileAdded,
                //    DocNo = FileNames,
                //}));
            }

            return(RedirectToAction("AttachDocument", new { DocId = vm.DocId, DocTypeId = vm.DocTypeId }));
        }
Beispiel #24
0
        protected override void PerformRunCommand(string[] args)
        {
            var newMsg = NewMessage.ReadFromConsole();
            var msg    = new MessageToPost
            {
                FromBoxId = ConsoleContext.CurrentBoxId,
                ToBoxId   = InputHelpers.AutocompleteBoxId(ConsoleContext, newMsg.ToBoxId),
            };

            msg.DocumentAttachments.AddRange(newMsg.DocumentsToPost
                                             .Select(e =>
            {
                var document = new DocumentAttachment
                {
                    TypeNamedId   = e.TypeNamedId,
                    Function      = e.Function,
                    Version       = e.Version,
                    SignedContent = new SignedContent
                    {
                        Content   = e.Content,
                        Signature = ConsoleContext.Crypt.Sign(e.Content, ConsoleContext.CurrentCert.RawData)
                    },
                    Comment = e.Comment,
                    NeedRecipientSignature = e.NeedRecipientSignature,
                };

                foreach (var m in e.Metadata)
                {
                    document.AddMetadataItem(new MetadataItem
                    {
                        Key   = m.Key,
                        Value = m.Value
                    });
                }

                return(document);
            }));
            var messagePosted = ConsoleContext.DiadocApi.PostMessage(ConsoleContext.CurrentToken, msg, Guid.NewGuid().ToString("N"));

            System.Console.WriteLine("Было отправлено следующее письмо:");
            messagePosted.WriteToConsole();
        }
 private void CreateAttachmentDocument(LEADDocument currentDocument, DocumentAttachment attachment)
 {
     try
     {
         // Load it as a document
         var loadAttachmentOptions = new LoadAttachmentOptions();
         loadAttachmentOptions.AttachmentNumber                            = attachment.AttachmentNumber;
         loadAttachmentOptions.UpdateAttachmentDocumentId                  = false;
         loadAttachmentOptions.LoadDocumentOptions.RenderAnnotations       = _preferences.LastRenderAnnotations;
         loadAttachmentOptions.LoadDocumentOptions.LoadAttachmentsMode     = _preferences.LastLoadAttachmentsMode;
         loadAttachmentOptions.LoadDocumentOptions.LoadEmbeddedAnnotations = _preferences.LastFileLoadEmbeddedAnnotations;
         loadAttachmentOptions.LoadDocumentOptions.Cache                   = _cache;
         loadAttachmentOptions.LoadDocumentOptions.Name                    = attachment.DisplayName;
         this.LoadDocumentFromAttachment(currentDocument, loadAttachmentOptions);
     }
     catch (Exception ex)
     {
         UI.Helper.ShowError(this, ex);
     }
 }
Beispiel #26
0
        public override void Do(UploadAttachmentEvent events)
        {
            UploadData d      = JsonConvert.DeserializeObject <UploadData>(events.Data);
            long       _id    = Convert.ToInt64(d.Id);
            Document   entity = Db.Document.Find(_id);

            if (entity == null)
            {
                throw new Exception("保存附件时查无此Document信息");
            }

            DocumentAttachment _attachment = new DocumentAttachment();

            _attachment.DocumentId  = entity.Id;
            _attachment.FileName    = events.FileName;
            _attachment.DisplayName = events.DisplayName;

            Db.DocumentAttachment.Add(_attachment);
            Db.SaveChanges();
        }
        /// <summary>
        /// Creates a DocumentAttachment with the provided binary content and adds it the existing attchments of the given Document ID.
        /// </summary>
        /// <param name="documentId">The Document ID for which to add the Attachment to it.</param>
        /// <param name="fileName">The name to be disolayed as the original File name.</param>
        /// <param name="content">The binary data representing the content of uploaded file as the attachment.</param>
        /// <returns>The created DocumentAttachment.</returns>
        public DocumentAttachment Add(Guid documentId, string fileName, byte[] content)
        {
            var attachment = new DocumentAttachment
            {
                Document   = documentId,
                Attachment = content,
                FileName   = fileName,
                FileSize   = content.Length
            };

            var operationResult = Client.For <DocumentAttachment>().Insert(ref attachment);

            if (operationResult)
            {
                return(attachment);
            }
            else
            {
                throw new Exception("DocumentAttachment failed to create.");
            }
        }
        public Response UpdateDocumentAttachment(int id, List<string> fileName, List<byte[]> files)
        {

            try
            {
                using (DGAMilDocEntities ctx = new DGAMilDocEntities())
                {


                    foreach (var file in fileName.Where(o => !o.Contains("mainFile")))
                    {
                        var i = 0;
                        DocumentAttachment att = new DocumentAttachment()
                        {
                            DocumentId = id,
                            AttachmentName = file,
                            AttachmentBinary = files[i],
                            MimeCode = Util.ConvertContentType(System.IO.Path.GetExtension(file)),
                            State = "บันทึก",
                            Type = "1",
                            FileSize = Util.ConvertBytesToMegabytes(files[i].Length).ToString("N5") + " mb",
                        };
                        ctx.DocumentAttachment.Add(att);
                        i++;
                    }


                    ctx.SaveChanges();
                    resp.Status = true;

                }
            }
            catch (Exception ex)
            {
                resp.Status = false;
                resp.Description = ex.Message;
            }

            return resp;
        }
Beispiel #29
0
        protected override void OnLoad(EventArgs e)
        {
            if (!DesignMode)
            {
                DocumentAttachment attachment = this.Attachment;

                if (attachment != null)
                {
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "Document ID", attachment.DocumentId }));
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "File name", attachment.FileName }));
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "Display name", attachment.DisplayName }));
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "File length", attachment.FileLength.ToString() }));
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "Mime type", attachment.MimeType }));
                    _propertiesListView.Items.Add(new ListViewItem(new string[] { "Is embedded", attachment.IsEmbedded ? "Yes" : "No" }));

                    var sortedMetadata = new SortedDictionary <string, string>(attachment.Metadata);

                    foreach (var item in sortedMetadata)
                    {
                        string value = item.Value;

                        if (item.Key == "TimeCreated" || item.Key == "TimeModified")
                        {
                            DateTime time;
                            if (DateTime.TryParse(item.Value, out time))
                            {
                                value = time.ToString();
                            }
                        }
                        _propertiesListView.Items.Add(new ListViewItem(new string[] { item.Key, value }));
                    }

                    _propertiesListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    _propertiesListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
                }
            }

            base.OnLoad(e);
        }
    protected string GetAttachmentHtml(DocumentAttachment attachment, DocumentAttachment mainAttachment, int versionHistoryId)
    {
        if (mainAttachment == null)
        {
            mainAttachment = attachment;
        }

        var attachmentUrl = GetAttachmentUrl(attachment, mainAttachment, versionHistoryId);
        var displayedName = GetDisplayedName(attachment);
        var tooltip       = GetTooltip(attachment, attachmentUrl, displayedName);
        var fileIcon      = UIHelper.GetFileIcon(Page, attachment.AttachmentExtension);

        if (ImageHelper.IsImage(mainAttachment.AttachmentExtension))
        {
            return(String.Format("<a class=\"cms-icon-link\" href=\"#\" onclick=\"javascript: window.open('{0}'); return false;\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, mainAttachment.AttachmentGUID, tooltip, fileIcon, displayedName));
        }

        attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "disposition", "attachment");

        // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
        return(String.Format("<a class=\"cms-icon-link\" onclick=\"javascript: {5}\" href=\"{0}\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, mainAttachment.AttachmentGUID, tooltip, fileIcon, displayedName, ScriptHelper.GetDisableProgressScript()));
    }
Beispiel #31
0
 public void FromCashe(XElement element)
 {
     CasheStatus = CasheStatus.FromCashe;
     XAttribute attr;
     if ((attr = element.Attribute(TypePropertyName)) != null)
         Type = attr.Value;
     XElement attachmentElement;
     switch (AttachmentType)
     {
         case AttachmentType.Photo:
             if ((attachmentElement = element.Element(PhotoAttachment.ElementNameStatic)) != null)
             {
                 if (Photo == null)
                     Photo = new PhotoAttachment();
                 Photo.FromCashe(attachmentElement);
             }
             break;
         case AttachmentType.Doc:
             if ((attachmentElement = element.Element(DocumentAttachment.ElementNameStatic)) != null)
             {
                 if (Document == null)
                     Document = new DocumentAttachment();
                 Document.FromCashe(attachmentElement);
             }
             break;
         case AttachmentType.Video:
             break;
         case AttachmentType.Audio:
             break;
         case AttachmentType.Map:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
Beispiel #32
0
 public void FromService(object obj)
 {
     CasheStatus = CasheStatus.Sync;
     Attachment attachment = (Attachment) obj;
     Type = attachment.Type;
     switch (AttachmentType)
     {
         case AttachmentType.Photo:
             if (Photo == null)
                 Photo = new PhotoAttachment();
             Photo.FromService(attachment.Photo);
             break;
         case AttachmentType.Doc:
             if (Document == null)
                 Document = new DocumentAttachment();
             Document.FromService(attachment.Document);
             break;
         case AttachmentType.Video:
             break;
         case AttachmentType.Audio:
             break;
         case AttachmentType.Map:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }