Example #1
0
        /// <summary>
        /// Downloads the files associated with the supplied <see cref="objVer"/>
        /// and creates a <see cref="SourceObjectFiles"/> to be used in new object creation.
        /// </summary>
        /// <param name="vault">The vault connection used to download the files.</param>
        /// <param name="objVer">The version of the object to download the files from.</param>
        /// <returns>A copy of the current files, as a <see cref="SourceObjectFiles"/>.</returns>
        private SourceObjectFiles GetNewObjectSourceFiles(Vault vault, ObjVer objVer)
        {
            // Sanity.
            if (null == vault)
            {
                throw new ArgumentNullException(nameof(vault));
            }
            if (null == objVer)
            {
                throw new ArgumentNullException(nameof(objVer));
            }

            // Get the files for the current ObjVer.
            var objectFiles = vault.ObjectFileOperations.GetFiles(objVer)
                              .Cast <ObjectFile>()
                              .ToArray();

            // Create the collection to return.
            var sourceObjectFiles = new SourceObjectFiles();

            // Iterate over the files and download each in turn.
            foreach (var objectFile in objectFiles)
            {
                // Where can we download it?
                var temporaryFilePath = System.IO.Path.Combine(
                    System.IO.Path.GetTempPath(),                                   // The temporary file folder.
                    System.IO.Path.GetTempFileName() + "." + objectFile.Extension); // The name including extension.

                // Download the file to a temporary location.
                vault.ObjectFileOperations.DownloadFile(objectFile.ID, objectFile.Version, temporaryFilePath);

                // Create an object source file for this temporary file
                // and add it to the collection.
                sourceObjectFiles.Add(-1, new SourceObjectFile()
                {
                    Extension      = objectFile.Extension,
                    SourceFilePath = temporaryFilePath,
                    Title          = objectFile.Title
                });
            }

            // Return the collection.
            return(sourceObjectFiles);
        }
        public void SFDAddedToTargetIfAppropriate_True()
        {
            // Create our mock objects.
            var objectCopyCreatorMock = this.GetObjectCopyCreatorMock();

            // Create the source files.
            var sourceObjectFiles = new SourceObjectFiles();
            {
                sourceObjectFiles.Add(1, new SourceObjectFile()
                {
                    Title     = "test file",
                    Extension = ".docx"
                });
            }

            // Create our source object.
            var sourceObject = this.CreateSourceObject
                               (
                sourceObjectFiles,
                new Tuple <int, MFDataType, object>
                (
                    (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefSingleFileObject,
                    MFDataType.MFDatatypeBoolean,
                    true
                )
                               );

            // Execute.
            var copy = sourceObject.CreateCopy
                       (
                new ObjectCopyOptions()
            {
                SetSingleFileDocumentIfAppropriate = true
            },
                objectCopyCreator: objectCopyCreatorMock.Object
                       );

            // Properties should be correct.
            Assert.AreEqual(1, copy.Properties.Count);
            Assert.AreEqual(true, copy.GetProperty((int)MFBuiltInPropertyDef.MFBuiltInPropertyDefSingleFileObject).Value.Value);
        }
        /// <summary>
        /// Locates files to attach using the appropriate file location strategy.
        /// </summary>
        /// <param name="objectSelector">The selector being executed.</param>
        /// <param name="xmlFile">The XML file being imported.</param>
        /// <param name="matchingElement">The current node, the context of which will be used to locate files if appropriate.</param>
        /// <param name="xmlNamespaceManager">Manager used to hold any XML namespace prefixes that are in use.</param>
        /// <returns>The files that should be attached to the object (or attached to the new object).</returns>
        public SourceObjectFiles FindFilesToAttach(
            ObjectSelector objectSelector,
            FileInfo xmlFile,
            XNode matchingElement,
            XmlNamespaceManager xmlNamespaceManager
            )
        {
            // Create a collection for the attached files.
            var sourceObjectFiles = new SourceObjectFiles();

            // Identify the file(s) to attach using the FileLocationStrategy.
            switch (objectSelector.AttachedFileConfiguration.FileLocationStrategy)
            {
            // "Invoice1.xml" should use "Invoice1.pdf".
            case FileLocationStrategy.LookForFileWithSameName:
            {
                // Attempt to find the file.
                var attachedFile = new FileInfo(Path.Combine(
                                                    xmlFile.DirectoryName,
                                                    xmlFile.Name.Substring(0, xmlFile.Name.Length - xmlFile.Extension.Length)
                                                    + objectSelector.AttachedFileConfiguration?.ExpectedFileExtension ?? ".pdf"
                                                    ));

                // Attach it if it exists.
                if (attachedFile.Exists)
                {
                    sourceObjectFiles.Add(-1, new SourceObjectFile()
                        {
                            Extension      = attachedFile.Extension.Substring(1),
                            SourceFilePath = attachedFile.FullName,
                            Title          = attachedFile.Name.Substring(0, attachedFile.Name.IndexOf(attachedFile.Extension))
                        });
                }
            }
            break;

            // Use XPath to find an element or attribute that contains the file name.
            case FileLocationStrategy.UseXPathQueryToLocateFileName:
            {
                // Evaluate the XPath query
                List <string> fileNames = new List <string>();
                var           results   = matchingElement
                                          .XPathEvaluate(objectSelector.AttachedFileConfiguration.XPathQueryToLocateFile, xmlNamespaceManager);
                if (results == null)
                {
                    break;
                }
                if (results is IEnumerable)
                {
                    // Iterate over the items returned.
                    foreach (var item in ((IEnumerable)results).Cast <XObject>())
                    {
                        // If it's an attribute then add the value.
                        if (item is XAttribute)
                        {
                            fileNames.Add(((XAttribute)item).Value);
                        }
                        else if (item is XElement)
                        {
                            fileNames.Add(((XElement)item).Value);
                        }
                        else
                        {
                            throw new InvalidOperationException(
                                      $"The XPath expression {objectSelector.AttachedFileConfiguration.XPathQueryToLocateFile} returned something other than an element or attribute.");
                        }
                    }
                }
                else
                {
                    // It is a simple value; retrieve it as a string.
                    fileNames.Add(results.ToString());
                }

                // Iterate over the file names that match the XPath query.
                foreach (var fileName in fileNames)
                {
                    FileInfo attachedFile = null;
                    // Find the file on disk.
                    if (System.IO.Path.IsPathRooted(fileName))
                    {
                        // It is a full path.
                        attachedFile = new FileInfo(fileName);
                    }
                    else
                    {
                        // It is relative.
                        attachedFile = new FileInfo(System.IO.Path.Combine(
                                                        xmlFile.DirectoryName,
                                                        fileName));
                    }

                    // Attach it if it exists.
                    if (attachedFile.Exists)
                    {
                        sourceObjectFiles.Add(-1, new SourceObjectFile()
                            {
                                Extension      = attachedFile.Extension.Substring(1),
                                SourceFilePath = attachedFile.FullName,
                                Title          = attachedFile.Name.Substring(0, attachedFile.Name.IndexOf(attachedFile.Extension))
                            });
                    }
                }
            }
            break;
            }

            // Return the source files.
            return(sourceObjectFiles);
        }
Example #4
0
        /// <summary>
        /// 接收的邮件写入MFiles
        /// </summary>
        /// <param name="vault">库</param>
        /// <param name="msg">邮件对象</param>
        /// <param name="folderId">文件ID</param>
        public static bool SaveRecvMailToMf(Vault vault, MimeMessage msg, int folderId)
        {
            var verIds   = new List <int>();
            var fileList = new List <string>();

            try
            {
                //保存附件
                var attachments = msg.Attachments.OfType <MimePart>().ToList();
                for (int i = 0; i < attachments.Count; i++)
                {
                    var attach   = attachments[i];
                    var filePath = GetTempFilePath(Path.GetExtension(attach.FileName));
                    MimePartToFile(attach, filePath);
                    fileList.Add(filePath);

                    //保存到MFiles
                    var sourceFiles = new SourceObjectFiles();
                    var sourceFile  = new SourceObjectFile
                    {
                        SourceFilePath = filePath,
                        Title          = attach.FileName.Substring(0, attach.FileName.LastIndexOf('.')),
                        Extension      = attach.FileName.Substring(attach.FileName.LastIndexOf('.') + 1),
                    };
                    sourceFiles.Add(i, sourceFile);

                    var versionAndProperties = vault.ObjectOperations.CreateNewObject(
                        (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
                        GetAttachmentPropertyValues(vault, sourceFile.Title, "ClassMailAttachments"),
                        sourceFiles);
                    vault.ObjectOperations.CheckIn(versionAndProperties.ObjVer);
                    verIds.Add(versionAndProperties.ObjVer.ObjID.ID);
                }

                {
                    //保存邮件
                    var filePath = GetTempFilePath(".html");
                    using (var writer = File.CreateText(filePath))
                    {
                        writer.Write(GetMailHtml(msg));
                        writer.Flush();
                        writer.Close();
                    }
                    fileList.Add(filePath);

                    //保存到MFiles
                    var properties = new List <MfProperty>
                    {
                        new MfProperty("PropMailSender", MFDataType.MFDatatypeLookup, ConvertAddrsToIds(vault, msg.From.Mailboxes)),
                        new MfProperty("PropMailReceiver", MFDataType.MFDatatypeMultiSelectLookup, ConvertAddrsToIds(vault, msg.To.Mailboxes)),
                        new MfProperty("PropMailCc", MFDataType.MFDatatypeMultiSelectLookup, ConvertAddrsToIds(vault, msg.Cc.Mailboxes)),
                        new MfProperty("PropMailSubject", MFDataType.MFDatatypeText, msg.Subject),
                        new MfProperty("PropMailCreatedTime", MFDataType.MFDatatypeDate, msg.Date.DateTime),
                        new MfProperty("PropMailFolders", MFDataType.MFDatatypeLookup, folderId),
                        new MfProperty("PropTags", MFDataType.MFDatatypeText, msg.MessageId),
                        new MfProperty("PropEmailAttachments", MFDataType.MFDatatypeMultiSelectLookup, verIds.ToArray()),
                        new MfProperty("PropIsRead", MFDataType.MFDatatypeBoolean, false)
                    };

                    var sourceFiles = new SourceObjectFiles();
                    var sourceFile  = new SourceObjectFile
                    {
                        SourceFilePath = filePath,
                        Title          = msg.Subject,
                        Extension      = "html"
                    };
                    sourceFiles.Add(0, sourceFile);

                    var versionAndProperties = vault.ObjectOperations.CreateNewObject(
                        (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
                        GetMailContentPropertyValues(vault, "ClassProjMail", properties),
                        sourceFiles);
                    vault.ObjectOperations.CheckIn(versionAndProperties.ObjVer);
                }
            }
            catch (Exception ex)
            {
                Common.Logger.Log.ErrorFormat("exception. save received email to mfiles error: {0}", ex.Message);
                return(false);
            }

            //删除临时文件
            DelFileList(fileList);
            return(true);
        }
Example #5
0
        /// <summary>
        /// 发送的邮件写入MFiles
        /// </summary>
        /// <param name="vault">库</param>
        /// <param name="msg">邮件对象</param>
        /// <param name="folderId">文件夹ID</param>
        public static bool SaveSendMailToMf(Vault vault, MailMessage msg, int folderId)
        {
            var result   = false;
            var verIds   = new List <int>();
            var fileList = new List <string>();

            try
            {
                //保存附件
                var attachs = msg.Attachments;
                if (attachs.Count > 0)
                {
                    for (var i = 0; i < attachs.Count; i++)
                    {
                        //保存到本地
                        var attach     = attachs[i];
                        var filePath   = GetTempFilePath(Path.GetExtension(attach.Name));
                        var fileStream = attach.ContentStream as FileStream;
                        fileList.Add(filePath);

                        //保存到MFiles
                        var sourceFiles = new SourceObjectFiles();
                        if (fileStream != null)
                        {
                            var sourceFile = new SourceObjectFile
                            {
                                SourceFilePath = fileStream.Name,
                                Title          = attach.Name.Substring(0, attach.Name.LastIndexOf('.')),
                                Extension      = attach.Name.Substring(attach.Name.LastIndexOf('.') + 1),
                            };
                            sourceFiles.Add(i, sourceFile);

                            var versionAndProperties = vault.ObjectOperations.CreateNewObject(
                                (int)MFilesAPI.MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
                                GetAttachmentPropertyValues(vault, sourceFile.Title, "ClassMailAttachments"),
                                sourceFiles);
                            vault.ObjectOperations.CheckIn(versionAndProperties.ObjVer);
                            verIds.Add(versionAndProperties.ObjVer.ObjID.ID);
                        }
                    }
                }

                //保存邮件
                var html = CombineHtmlString(msg.Body);
                if (html.Length > 0)
                {
                    //保存到本地
                    var filePath = GetTempFilePath(".html");
                    using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
                    {
                        writer.Write(html);
                        writer.Flush();
                        writer.Close();
                    }
                    fileList.Add(filePath);

                    //保存到MFiles
                    var properties = new List <MfProperty>
                    {
                        new MfProperty("PropMailSender", MFDataType.MFDatatypeLookup, ConvertAddrToId(vault, msg.From)),
                        new MfProperty("PropMailReceiver", MFDataType.MFDatatypeMultiSelectLookup, ConvertAddrsToIds(vault, msg.To)),
                        new MfProperty("PropMailCc", MFDataType.MFDatatypeMultiSelectLookup, ConvertAddrsToIds(vault, msg.CC)),
                        new MfProperty("PropMailSubject", MFDataType.MFDatatypeText, msg.Subject),
                        new MfProperty("PropMailCreatedTime", MFDataType.MFDatatypeDate, DateTime.Now.ToUniversalTime()),
                        new MfProperty("PropMailFolders", MFDataType.MFDatatypeLookup, folderId),
                        new MfProperty("PropTags", MFDataType.MFDatatypeText, msg.Headers.Get("MessageId")),
                        new MfProperty("PropEmailAttachments", MFDataType.MFDatatypeMultiSelectLookup, verIds.ToArray()),
                        new MfProperty("PropIsRead", MFDataType.MFDatatypeBoolean, true)
                    };

                    var sourceFiles = new SourceObjectFiles();
                    var sourceFile  = new SourceObjectFile
                    {
                        SourceFilePath = filePath,
                        Title          = msg.Subject,
                        Extension      = "html"
                    };
                    sourceFiles.Add(0, sourceFile);

                    //
                    var searchObj = SearchMailFromMf(vault, msg.Headers.Get("MessageId"));
                    if (searchObj.Count == 0)
                    {
                        //创建邮件对象
                        result = CreateMailToMf(vault, GetMailContentPropertyValues(vault, "ClassProjMail", properties), sourceFiles);
                    }
                    else
                    {
                        //更新邮件对象
                        result = UpdateMailToMf(vault, searchObj[1], GetMailContentPropertyValues(vault, properties), sourceFiles);
                    }

                    //Todo
                    //发送草稿
                }
            }
            catch (Exception ex)
            {
                Common.Logger.Log.ErrorFormat("exception. save sent email to mfiles error: {0}", ex.Message);
                result = false;
            }

            //删除临时文件
            DelFileList(fileList);
            return(result);
        }