public static OT_Document create_multifile_doc(this OT_Document doc, int?createdby_mfuserid = null, params string[] files)
        {
            Vault             vault       = doc.objVerEx.Vault;
            ObjVerEx          version     = doc.objVerEx;
            SourceObjectFiles sourceFiles = new SourceObjectFiles();

            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);
                sourceFiles.AddFile(fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), fi.FullName);
            }
            ObjectVersionAndProperties obj = vault.ObjectOperations.CreateNewObjectEx(OT_Document.TypeID, version.Properties, sourceFiles, false,
                                                                                      createdby_mfuserid == null);

            if (createdby_mfuserid != null)
            {
                TypedValue created_by = new TypedValue();
                created_by.SetValue(MFDataType.MFDatatypeLookup, createdby_mfuserid.Value);
                obj = doc.objVerEx.Vault.ObjectPropertyOperations.SetCreationInfoAdmin(obj.ObjVer, true, created_by, false, null);
                doc.objVerEx.Vault.ObjectOperations.CheckIn(obj.ObjVer);
            }

            return(new OT_Document()
            {
                objVerEx = new ObjVerEx(obj.Vault, obj)
            });
        }
 protected Common.ObjVerEx CreateSourceObject
 (
     SourceObjectFiles sourceObjectFiles,
     params Tuple <int, MFDataType, object>[] propertyValues
 )
 {
     return(this.CreateSourceObject(null, sourceObjectFiles, propertyValues));
 }
 protected Common.ObjVerEx CreateSourceObjectWithPropertyValues
 (
     SourceObjectFiles sourceObjectFiles,
     params PropertyValue[] propertyValues
 )
 {
     return(this.CreateSourceObjectWithPropertyValues(null, sourceObjectFiles, propertyValues));
 }
        public static void replace_files(this OT_Document document, string singledoc_newfilepath = null, string[] multidoc_newfilespath = null)
        {
            Vault vault        = document.objVerEx.Vault;
            var   obj          = document.objVerEx;
            bool  isSingleFile = vault.ObjectOperations.IsSingleFileObject(obj.ObjVer);

            //singlefile document
            if (isSingleFile && string.IsNullOrEmpty(singledoc_newfilepath))
            {
                throw new Exception("No file supplied for single-file document.");
            }

            //multifile document
            if (!isSingleFile && (multidoc_newfilespath == null || multidoc_newfilespath.Length == 0))
            {
                throw new Exception("No file(s) supplied for multi-file document.");
            }

            ObjectVersion new_version = vault.ObjectOperations.CheckOut(obj.ObjID);

            try {
                ObjVerEx          new_versionex = new ObjVerEx(vault, new_version);
                SourceObjectFiles files         = new SourceObjectFiles();

                if (isSingleFile)
                {
                    FileInfo fi = new FileInfo(singledoc_newfilepath);
                    files.AddFile(fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), fi.FullName);

                    //change the file type
                    IEnumerator obfile_enumerator = vault.ObjectFileOperations.GetFiles(new_version.ObjVer).GetEnumerator();
                    obfile_enumerator.MoveNext();
                    ObjectFile single_fileobj = obfile_enumerator.Current as ObjectFile;
                    if (single_fileobj == null)
                    {
                        throw new Exception("Single file for this document not found.");
                    }
                    vault.ObjectFileOperations.RenameFile(new_versionex.ObjVer, single_fileobj.FileVer, fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), false);
                }
                else
                {
                    foreach (string file in multidoc_newfilespath)
                    {
                        FileInfo fi = new FileInfo(file);
                        files.AddFile(fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), fi.FullName);
                    }
                }
                new_versionex.ReplaceFiles(files);
                new_versionex.CheckIn();
                document.objVerEx = new_versionex;
            } catch {
                if (new_version.ObjectCheckedOut)
                {
                    vault.ObjectOperations.ForceUndoCheckout(new_version.ObjVer);
                }
                throw;
            }
        }
Esempio n. 5
0
        public ObjectVersionAndProperties CreateNewObject(int objectType, PropertyValues propertyValues,
                                                          SourceObjectFiles sourceObjectFiles = null, AccessControlList accessControlList = null)
        {
            vault.MetricGatherer.MethodCalled();

            // TODO: use parameter args
            TestObjectVersionAndProperties ovap = CreateNewTestObject(objectType, propertyValues);

            return(ovap);
        }
        protected Common.ObjVerEx CreateSourceObjectWithPropertyValues
        (
            Mock <Vault> vaultMock,
            SourceObjectFiles sourceObjectFiles,
            params PropertyValue[] propertyValues
        )
        {
            // Create our mock objects.
            vaultMock = vaultMock ?? this.GetVaultMock();

            // Create the property values collection.
            var pvs = new PropertyValues();

            foreach (var pv in propertyValues ?? new PropertyValue[0])
            {
                pvs.Add(-1, pv);
            }

            // Set up the object files.
            var objectFiles = new Mock <ObjectFiles>();

            objectFiles.Setup(m => m.Count).Returns(sourceObjectFiles?.Count ?? 0);
            var converted = new List <ObjectFile>();

            if (null != sourceObjectFiles)
            {
                foreach (SourceObjectFile item in sourceObjectFiles)
                {
                    var file = new Mock <ObjectFile>();
                    file.Setup(m => m.Title).Returns(item.Title);
                    file.Setup(m => m.Extension).Returns(item.Extension);
                    converted.Add(file.Object);
                }
            }
            objectFiles.Setup(m => m.GetEnumerator()).Returns(() => converted.GetEnumerator());
            objectFiles.Setup(m => m[It.IsAny <int>()]).Returns((int index) => converted[index + 1]);

            // Create the source object itself.
            return(new VAF.Common.ObjVerEx
                   (
                       vaultMock.Object,
                       this.CreateObjectVersionAndPropertiesMock
                       (
                           vaultMock.Object,
                           propertyValues: pvs,
                           objectFiles: objectFiles.Object
                       ).Object
                   ));
        }
Esempio n. 7
0
        public static ObjectVersionAndProperties CreateNewObject(this Vault vault, int objType, int classId,
                                                                 PropertyValues pvs, SourceObjectFiles files = null)
        {
            var classPV = MFPropertyUtils.Class(classId);

            pvs.Add(0, classPV);

            if (files == null || files.Count != 0)
            {
                var singleFilePV = MFPropertyUtils.SingleFile(false);
                pvs.Add(-1, singleFilePV);
            }

            return(vault.ObjectOperations.CreateNewObject(objType, pvs, files));
        }
Esempio n. 8
0
 /// <summary>
 /// 创建邮件对象
 /// </summary>
 /// <param name="vault"></param>
 /// <param name="properties"></param>
 /// <param name="sourceFiles"></param>
 private static bool CreateMailToMf(Vault vault, PropertyValues properties, SourceObjectFiles sourceFiles)
 {
     try
     {
         var versionAndProperties = vault.ObjectOperations.CreateNewObject(
             (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
             properties,
             sourceFiles);
         vault.ObjectOperations.CheckIn(versionAndProperties.ObjVer);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 9
0
        internal static void Create(Vault vault, MFObject obj)
        {
            //  Writelog(string.Format("--11--{0},{1},{2}",obj.Id,obj.Properties.Count,obj));
            var objType = MfAlias.GetObjType(vault, obj.ObjDef.TypeAlias);
            //   Writelog("--22--");
            var objClass = MfAlias.GetObjectClass(vault, obj.ObjDef.ClassAlias);
            //   Writelog("--33--");
            var pvs     = new PropertyValues();
            var classPV = MFPropertyUtils.Class(objClass);

            pvs.Add(-1, classPV);
            //   Writelog("--44--");
            SetProperties(vault, pvs, obj);

            var isSingleFile = false;
            //   Writelog("--55--");
            SourceObjectFiles files = null;

            if (obj.Filepaths != null && obj.Filepaths.Count > 0)
            {
                files = new SourceObjectFiles();
                //todo
                if (obj.Filepaths.Count == 1)
                {
                    isSingleFile = true;
                }
                //    Writelog("--66--");
            }
            var singleFilePV = MFPropertyUtils.SingleFile(isSingleFile);

            pvs.Add(-1, singleFilePV);
            //   Writelog("--77--");
            try
            {
                var objVersion = vault.ObjectOperations.CreateNewObject(objType, pvs, files);
                //     Writelog("--88--");
                var newObjVersion = vault.ObjectOperations.CheckIn(objVersion.ObjVer);

                obj.Id = newObjVersion.ObjVer.ID;
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("CreateNewObject error:{0},{1},{2}", objType, pvs.Count, ex.Message));
            }
        }
Esempio n. 10
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);
        }
 /// <summary>
 /// Clears up any temporary files used with the creation of an object.
 /// </summary>
 /// <param name="sourceObjectFiles">The files to clear up.</param>
 private void ClearTemporaryFiles(SourceObjectFiles sourceObjectFiles)
 {
     // Sanity.
     if (null == sourceObjectFiles)
     {
         return;                 // No point throwing; nothing to clear up.
     }
     // Iterate over the files and clear them up.
     foreach (var sourceObjectFile in sourceObjectFiles.Cast <SourceObjectFile>())
     {
         try
         {
             System.IO.File.Delete(sourceObjectFile.SourceFilePath);
         }
         catch (Exception e)
         {
             // TODO: Swallowing exceptions isn't nice.
         }
     }
 }
        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);
        }
Esempio n. 13
0
 /// <summary>
 /// Clears up any temporary files used with the creation of an object.
 /// </summary>
 /// <param name="sourceObjectFiles">The files to clear up.</param>
 private void ClearTemporaryFiles(SourceObjectFiles sourceObjectFiles)
 {
     // Sanity.
     if (null == sourceObjectFiles)
     {
         return;                 // No point throwing; nothing to clear up.
     }
     // Iterate over the files and clear them up.
     foreach (var sourceObjectFile in sourceObjectFiles.Cast <SourceObjectFile>())
     {
         try
         {
             System.IO.File.Delete(sourceObjectFile.SourceFilePath);
         }
         catch (Exception e)
         {
             SysUtils.ReportErrorToEventLog(SysUtils.DefaultEventSourceIdentifier,
                                            $"Exception removing temporary file from {sourceObjectFile.SourceFilePath}.",
                                            e);
         }
     }
 }
 protected Common.ObjVerEx CreateSourceObject
 (
     Mock <Vault> vaultMock,
     SourceObjectFiles sourceObjectFiles,
     params Tuple <int, MFDataType, object>[] propertyValues
 )
 {
     return(this.CreateSourceObjectWithPropertyValues
            (
                vaultMock,
                sourceObjectFiles,
                (propertyValues ?? new Tuple <int, MFDataType, object> [0])
                .Select(t =>
     {
         var pv = new PropertyValue()
         {
             PropertyDef = t.Item1
         };
         pv.TypedValue.SetValue(t.Item2, t.Item3);
         return pv;
     })
                .ToArray()
            ));
 }
Esempio n. 15
0
        /// <summary>
        /// 更新邮件对象
        /// </summary>
        /// <param name="vault"></param>
        /// <param name="objVer"></param>
        /// <param name="properties"></param>
        /// <param name="sourceFiles"></param>
        private static bool UpdateMailToMf(Vault vault, ObjectVersion objVer, PropertyValues properties, SourceObjectFiles sourceFiles)
        {
            //签出对象邮件对象
            ObjectVersion checkOutVn = null;

            if (!objVer.ObjectCheckedOut)
            {
                try
                {
                    checkOutVn = vault.ObjectOperations.CheckOut(objVer.ObjVer.ObjID);
                }
                catch (Exception ex)
                {
                    Common.Logger.Log.ErrorFormat("exception. update email to mfiles error: {0}", ex.Message);
                    return(false);
                }
            }
            else if (objVer.CheckedOutTo == vault.SessionInfo.UserID || objVer.CheckedOutTo == -103)
            {
                checkOutVn = objVer;
            }
            else
            {
                ObjVer oldObjVer = null;
                try
                {
                    oldObjVer = vault.ObjectOperations.ForceUndoCheckout(objVer.ObjVer).ObjVer;
                }
                catch (Exception ex)
                {
                    Common.Logger.Log.ErrorFormat("exception. update email to mfiles error: {0}", ex.Message);
                    return(false);
                }

                try
                {
                    if (oldObjVer != null)
                    {
                        checkOutVn = vault.ObjectOperations.CheckOut(oldObjVer.ObjID);
                    }
                }
                catch (Exception ex)
                {
                    Common.Logger.Log.ErrorFormat("exception. update email to mfiles error: {0}", ex.Message);
                    return(false);
                }
            }

            try
            {
                //更新邮件对象属性
                if (checkOutVn != null)
                {
                    //获取邮件正文文件对象
                    var objFiles = vault.ObjectFileOperations.GetFiles(checkOutVn.ObjVer);
                    vault.ObjectPropertyOperations.SetProperties(checkOutVn.ObjVer, properties);
                    vault.ObjectOperations.SetSingleFileObject(checkOutVn.ObjVer, false);
                    vault.ObjectFileOperations.RemoveFile(checkOutVn.ObjVer, objFiles[1].FileVer);
                    vault.ObjectFileOperations.AddFile(checkOutVn.ObjVer,
                                                       sourceFiles[1].Title,
                                                       sourceFiles[1].Extension,
                                                       sourceFiles[1].SourceFilePath);
                    vault.ObjectOperations.SetSingleFileObject(checkOutVn.ObjVer, true);

                    //签入对象
                    vault.ObjectOperations.CheckIn(checkOutVn.ObjVer);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                if (checkOutVn != null)
                {
                    vault.ObjectOperations.ForceUndoCheckout(checkOutVn.ObjVer);
                }
                Common.Logger.Log.ErrorFormat("exception. update email to mfiles error: {0}", ex.Message);
                return(false);
            }

            return(false);
        }
Esempio n. 16
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);
        }
Esempio n. 17
0
        public int CreateNewObjectExQuick(int objectType, PropertyValues properties, SourceObjectFiles sourceFiles, bool sfd, bool checkIn, AccessControlList accessControlList = null)
        {
            vault.MetricGatherer.MethodCalled();

            throw new NotImplementedException();
        }
Esempio n. 18
0
        public ObjectVersionAndProperties CreateNewObjectEx(int objectType, PropertyValues properties, SourceObjectFiles sourceFiles,
                                                            bool sfd, bool checkIn, AccessControlList accessControlList = null)
        {
            vault.MetricGatherer.MethodCalled();

            // TODO: use parameter args
            TestPropertyValue pv = new TestPropertyValue
            {
                PropertyDef = ( int )MFBuiltInPropertyDef.MFBuiltInPropertyDefSingleFileObject
            };

            pv.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, sfd);
            properties.Add(-1, pv);
            TestObjectVersionAndProperties ovap = CreateNewTestObject(objectType, properties);

            if (!checkIn)
            {
                ovap.versionData.checkedOut = true;
            }
            return(ovap);
        }
        /// <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);
        }
        /// <summary>
        /// Executes the <see cref="ObjectSelector"/> rule against the <see cref="XNode"/>,
        /// importing matching objects.
        /// </summary>
        /// <param name="vault">The vault reference to use for processing the import.</param>
        /// <param name="node">The node to import data from.</param>
        /// <param name="objectSelector">The selector to execute.</param>
        /// <param name="xmlFile">The information about the XML file being imported.</param>
        /// <param name="parent">A parent object to create a relationship to, if appropriate.</param>
        /// <param name="xmlNamespaceManager">A namespace manager for using XML prefixes in XPath statements.</param>
        /// <returns>A list of files which were attached to the object, for deletion.</returns>
        public List <FileInfo> ImportXmlFile(
            Vault vault,
            XNode node,
            ObjectSelector objectSelector,
            FileInfo xmlFile = null,
            ObjVer parent    = null,
            XmlNamespaceManager xmlNamespaceManager = null)
        {
            // Sanity.
            if (vault == null)
            {
                throw new ArgumentNullException(nameof(vault));
            }
            if (null == node)
            {
                throw new ArgumentNullException(nameof(node));
            }
            if (null == objectSelector)
            {
                throw new ArgumentNullException(nameof(objectSelector));
            }
            if (string.IsNullOrWhiteSpace(objectSelector.XPathQuery))
            {
                throw new ArgumentException("The XPath query for the object was empty", nameof(objectSelector));
            }
            if (null == objectSelector.PropertySelectors)
            {
                throw new ArgumentException("The object selector contained no property selectors.", nameof(objectSelector));
            }
            if (false == objectSelector.ObjectType.IsResolved)
            {
                throw new InvalidOperationException("The object selector object type is not resolved");
            }
            if (false == objectSelector.Class.IsResolved)
            {
                throw new InvalidOperationException("The object selector class is not resolved");
            }

            // Create a list of attached files (which can then be deleted later).
            var attachedFilesToDelete = new List <FileInfo>();

            // Create the namespace manager.
            if (null != xmlNamespaceManager)
            {
                // Copy data from the other manager (so we don't accidentally affect other queries).
                var xmlNamespaceManager2 = new XmlNamespaceManager(new NameTable());
                foreach (string prefix in xmlNamespaceManager)
                {
                    // Don't add default.
                    if (string.IsNullOrWhiteSpace(prefix))
                    {
                        continue;
                    }
                    if (prefix == "xsi")
                    {
                        continue;
                    }
                    if (prefix == "xmlns")
                    {
                        continue;
                    }

                    // Add.
                    xmlNamespaceManager2.AddNamespace(prefix, xmlNamespaceManager.LookupNamespace(prefix));
                }
                xmlNamespaceManager = xmlNamespaceManager2;
            }
            else
            {
                xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
            }

            // Populate the namespace manager.
            if (null != objectSelector.XmlNamespaces)
            {
                foreach (var ns in objectSelector.XmlNamespaces)
                {
                    // If the namespace manager already contains a prefix then remove it.
                    string existingPrefix = xmlNamespaceManager.LookupPrefix(ns.Uri);
                    if (false == string.IsNullOrEmpty(existingPrefix))
                    {
                        xmlNamespaceManager.RemoveNamespace(existingPrefix, ns.Uri);
                    }

                    xmlNamespaceManager.AddNamespace(ns.Prefix, ns.Uri);
                }
            }

            // Find matching nodes.
            foreach (var matchingElement in node.XPathSelectElements(objectSelector.XPathQuery, xmlNamespaceManager))
            {
                // Hold all the properties being read.
                var propertyValuesBuilder = new MFPropertyValuesBuilder(vault);

                // Add the class property value.
                propertyValuesBuilder.SetClass(objectSelector.Class.ID);

                // Retrieve the properties.
                foreach (var propertySelector in objectSelector.PropertySelectors)
                {
                    // Sanity.
                    if (string.IsNullOrWhiteSpace(propertySelector.XPathQuery))
                    {
                        throw new ArgumentException("The object selector contained no property selectors.", nameof(objectSelector));
                    }
                    if (false == propertySelector.PropertyDef.IsResolved)
                    {
                        throw new InvalidOperationException("The property value selector property definition is not resolved");
                    }

                    // Retrieve the element for the property value.
                    // var matchingPropertyElement = matchingElement
                    //	.XPathSelectElement(propertySelector.XPathQuery, xmlNamespaceManager);
                    //if (null == matchingPropertyElement)
                    //	continue;

                    // Find the property definition type.
                    var propertyDefType = vault
                                          .PropertyDefOperations
                                          .GetPropertyDef(propertySelector.PropertyDef.ID)
                                          .DataType;

                    // Check if it's lookup or multilookup
                    var isLookup = ((propertyDefType == MFDataType.MFDatatypeMultiSelectLookup) || (propertyDefType == MFDataType.MFDatatypeLookup));

                    #region itterate XAttributes from XPath
                    if (propertySelector.XPathQuery.Contains("@"))
                    {
                        List <int>  listLookup = new List <int>();
                        IEnumerable matchingPropertyAttributes =
                            (IEnumerable)matchingElement.XPathEvaluate(propertySelector.XPathQuery);
                        foreach (System.Xml.Linq.XAttribute matchingPropertyAttribute in matchingPropertyAttributes)
                        {
                            string szValue = matchingPropertyAttribute.Value;

                            if (propertyDefType == MFDataType.MFDatatypeBoolean)
                            {
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    CastToBool(szValue));
                            }
                            else if (propertyDefType == MFDataType.MFDatatypeDate)
                            {
                                szValue = $"{szValue} 00:00:00";
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    szValue);
                            }
                            else if (isLookup)
                            {
                                var iLookupDef = (propertySelector.LookupOrValuelistStrategy == LookupOrValuelistStrategy.SearchLookup ?
                                                  propertySelector.LookupObjectDef.ID :
                                                  propertySelector.LookupValueListDef.ID);

                                var iLookupItem = LookupRef(vault,
                                                            iLookupDef,
                                                            propertyDefType,
                                                            propertySelector.SearchByLookupID,
                                                            szValue,
                                                            propertySelector.LookupOrValuelistStrategy);

                                if (iLookupItem != -1)
                                {
                                    listLookup.Add(iLookupItem);
                                }
                            }
                            else
                            {
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    szValue);
                            }
                        }

                        // Lookup or MultiSelectLookup and found something
                        if ((isLookup) && (listLookup.Count != 0))
                        {
                            int[] arrLookupIDs = listLookup.ToArray();
                            propertyValuesBuilder.Add(
                                propertySelector.PropertyDef.ID,
                                propertyDefType,
                                arrLookupIDs);
                        }
                    }
                    #endregion
                    else
                    #region itterate XElements from XPath
                    {
                        List <int> listLookup = new List <int>();
                        var        matchingPropertyElements =
                            matchingElement.XPathSelectElements(propertySelector.XPathQuery);
                        if (null == matchingPropertyElements)
                        {
                            continue;
                        }

                        // iterate found XElements
                        foreach (var matchingPropertyElement in matchingPropertyElements)
                        {
                            if (null == matchingPropertyElement)
                            {
                                continue;
                            }

                            string szValue = matchingPropertyElement.Value;

                            if (propertyDefType == MFDataType.MFDatatypeBoolean)
                            {
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    CastToBool(szValue));
                            }
                            else if (propertyDefType == MFDataType.MFDatatypeDate)
                            {
                                szValue = $"{szValue} 00:00:00";
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    szValue);
                            }
                            else if (isLookup)
                            {
                                var iLookupDef = (propertySelector.LookupOrValuelistStrategy == LookupOrValuelistStrategy.SearchLookup ?
                                                  propertySelector.LookupObjectDef.ID :
                                                  propertySelector.LookupValueListDef.ID);

                                var iLookupItem = LookupRef(vault,
                                                            iLookupDef,
                                                            propertyDefType,
                                                            propertySelector.SearchByLookupID,
                                                            szValue,
                                                            propertySelector.LookupOrValuelistStrategy);

                                if (iLookupItem != -1)
                                {
                                    listLookup.Add(iLookupItem);
                                }
                                propertyValuesBuilder.AddLookup(
                                    propertySelector.PropertyDef.ID,
                                    szValue);
                            }
                            else
                            {
                                propertyValuesBuilder.Add(
                                    propertySelector.PropertyDef.ID,
                                    propertyDefType,
                                    szValue);
                            }
                        }
                        // Lookup or MultiSelectLookup and found something
                        if ((isLookup) && (listLookup.Count != 0))
                        {
                            int[] arrLookupIDs = listLookup.ToArray();
                            propertyValuesBuilder.Add(
                                propertySelector.PropertyDef.ID,
                                propertyDefType,
                                arrLookupIDs);
                        }
                    }
                    #endregion

                    // Add the property to the builder.
                    //propertyValuesBuilder.Add(
                    //propertySelector.PropertyDef.ID,
                    //propertyDefType,
                    //matchingPropertyElement.Value);
                }

                // Set the static values
                foreach (var staticPropertyValue in objectSelector.StaticPropertyValues ?? new List <StaticPropertyValue>())
                {
                    // Sanity.
                    if (false == staticPropertyValue.PropertyDef.IsResolved)
                    {
                        throw new InvalidOperationException("The property value selector property definition is not resolved");
                    }

                    // Find the property definition type.
                    var propertyDefType = vault
                                          .PropertyDefOperations
                                          .GetPropertyDef(staticPropertyValue.PropertyDef.ID)
                                          .DataType;

                    // Add the property to the builder.
                    propertyValuesBuilder.Add(
                        staticPropertyValue.PropertyDef.ID,
                        propertyDefType,
                        staticPropertyValue.Value);
                }


                // Create a reference to the parent?
                if (null != parent)
                {
                    // If the property definition to use was configured then use that.
                    if (true == objectSelector.ParentRelationshipPropertyDef?.IsResolved)
                    {
                        // Check that this property is a list and is for the correct object type.
                        var parentRelationshipPropertyDef = vault
                                                            .PropertyDefOperations
                                                            .GetPropertyDef(objectSelector.ParentRelationshipPropertyDef.ID);
                        if (false == parentRelationshipPropertyDef.BasedOnValueList ||
                            parentRelationshipPropertyDef.ValueList != parent.Type)
                        {
                            throw new InvalidOperationException(
                                      $"The property def {parentRelationshipPropertyDef.Name} ({parentRelationshipPropertyDef.ID}) is not based on value list {parent.Type}.");
                        }

                        // Use the configured property definition.
                        propertyValuesBuilder.Add(
                            parentRelationshipPropertyDef.ID,
                            parentRelationshipPropertyDef.DataType,
                            parent.ID);
                    }
                    else
                    {
                        // Retrieve data about the parent object type.
                        var parentObjectType = vault
                                               .ObjectTypeOperations
                                               .GetObjectType(parent.Type);

                        // Retrieve data about the child object type.
                        var childObjectType = vault
                                              .ObjectTypeOperations
                                              .GetObjectType(objectSelector.ObjectType.ID);

                        // Is there an owner for this child type?
                        if (childObjectType.HasOwnerType)
                        {
                            // Use the "owner" property definition.
                            propertyValuesBuilder.Add(
                                parentObjectType.OwnerPropertyDef,
                                MFDataType.MFDatatypeLookup,
                                parent.ID);
                        }
                        else
                        {
                            // Use the default property definition.
                            propertyValuesBuilder.Add(
                                parentObjectType.DefaultPropertyDef,
                                MFDataType.MFDatatypeMultiSelectLookup,
                                parent.ID);
                        }
                    }
                }

                // Create a container for any attached files.
                var sourceObjectFiles = new SourceObjectFiles();

                // Should we attach the file to this object?
                if (objectSelector.AttachFileToThisObject)
                {
                    // Locate the files to retrieve.
                    sourceObjectFiles = this.FindFilesToAttach(objectSelector, xmlFile, matchingElement, xmlNamespaceManager);

                    // If we were supposed to attach a file but no files were found then throw an exception.
                    if (objectSelector.AttachedFileConfiguration?.FileNotFoundHandlingStrategy == FileNotFoundHandlingStrategy.Fail &&
                        0 == sourceObjectFiles.Count)
                    {
                        throw new InvalidOperationException("Attached file expected but not found.");
                    }

                    if (objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy
                        == AttachedFileHandlingStrategy.AttachToCurrentObject)
                    {
                        // Retrieve information about the object type from the vault.
                        var objectType = vault
                                         .ObjectTypeOperations
                                         .GetObjectType(objectSelector.ObjectType.ID);

                        // If the object type cannot have files but we are meant to attach a file, then fail.
                        if (false == objectType.CanHaveFiles)
                        {
                            throw new InvalidOperationException(
                                      $"The object type {objectType.NameSingular} cannot have files, but the configuration states to attach a file.");
                        }
                    }
                }

                // Which source object files should we use for the new object?
                var sourceObjectFilesForNewObject = objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy
                                                    == AttachedFileHandlingStrategy.AttachToCurrentObject
                                        ? sourceObjectFiles
                                        : new SourceObjectFiles();

                // Add the object to the vault.
                var createdObject = vault
                                    .ObjectOperations
                                    .CreateNewObjectEx(
                    objectSelector.ObjectType.ID,
                    propertyValuesBuilder.Values,
                    sourceObjectFilesForNewObject,
                    SFD: objectSelector.ObjectType.ID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument &&
                    sourceObjectFilesForNewObject.Count == 1
                    );

                // The files which need to be deleted.
                attachedFilesToDelete.AddRange(
                    sourceObjectFiles
                    .Cast <SourceObjectFile>()
                    .Select(sof => new FileInfo(sof.SourceFilePath))
                    );

                // Are there any related objects (e.g. children) to create?
                foreach (var childObjectSelector in objectSelector.ChildObjectSelectors)
                {
                    attachedFilesToDelete.AddRange(this.ImportXmlFile(vault,
                                                                      matchingElement,
                                                                      childObjectSelector,
                                                                      xmlFile: xmlFile,
                                                                      parent: createdObject.ObjVer,
                                                                      xmlNamespaceManager: xmlNamespaceManager));
                }

                // Clean up the collections we were using.
                propertyValuesBuilder = new MFPropertyValuesBuilder(vault);

                // Handle creating a new object for the file.
                if (
                    objectSelector.AttachFileToThisObject &&
                    objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy
                    == AttachedFileHandlingStrategy.CreateNewObject)
                {
                    // Set the static values
                    foreach (var staticPropertyValue in objectSelector.AttachedFileConfiguration?.StaticPropertyValues ?? new List <StaticPropertyValue>())
                    {
                        // Sanity.
                        if (false == staticPropertyValue.PropertyDef.IsResolved)
                        {
                            throw new InvalidOperationException("The property value selector property definition is not resolved");
                        }

                        // Find the property definition type.
                        var propertyDefType = vault
                                              .PropertyDefOperations
                                              .GetPropertyDef(staticPropertyValue.PropertyDef.ID)
                                              .DataType;

                        // Add the property to the builder.
                        propertyValuesBuilder.Add(
                            staticPropertyValue.PropertyDef.ID,
                            propertyDefType,
                            staticPropertyValue.Value);
                    }

                    // Add the class property value.
                    propertyValuesBuilder.SetClass(objectSelector.AttachedFileConfiguration.Class.ID);

                    // Add a reference from this new object to the one we created earlier.
                    {
                        // Retrieve data about the parent object type.
                        var parentObjectType = vault
                                               .ObjectTypeOperations
                                               .GetObjectType(createdObject.ObjVer.Type);

                        // Set the relationship.
                        propertyValuesBuilder.Add(
                            parentObjectType.DefaultPropertyDef,
                            MFDataType.MFDatatypeMultiSelectLookup,
                            createdObject.ObjVer.ID);
                    }

                    // Add the object to the vault.
                    var createdDocumentObject = vault
                                                .ObjectOperations
                                                .CreateNewObjectEx(
                        objectSelector.AttachedFileConfiguration.ObjectType.ID,
                        propertyValuesBuilder.Values,
                        sourceObjectFiles,
                        SFD: objectSelector.AttachedFileConfiguration.ObjectType.ID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument &&
                        sourceObjectFiles.Count == 1
                        );
                }
            }

            // Return the files to remove.
            return(attachedFilesToDelete);
        }
 public ObjectVersionAndProperties CreateObject(Vault vault, int objectType, PropertyValues propertyValues, SourceObjectFiles sourceObjectFiles, bool singleFileDocument, bool checkIn, AccessControlList accessControlList)
 {
     return((vault ?? throw new ArgumentNullException(nameof(vault)))
            .ObjectOperations
            .CreateNewObjectEx
            (
                objectType,
                propertyValues,
                SourceFiles: sourceObjectFiles,
                SFD: singleFileDocument,
                CheckIn: checkIn,
                AccessControlList: accessControlList
            ));
 }
        public static bool update(this IObjVerEx obj, bool returnUpdatedMetadata = true, bool skipVafCalculation = false, int?modifiedby_userid = null, string[] replace_files = null)
        {
            if (obj == null)
            {
                return(false);
            }
            // Check if the objcet is deleted or destroyed
            if (obj.objVerEx.Deleted() || obj.objVerEx.IsDestroyed)
            {
                return(false);
            }
            ObjectVersionAndProperties checkedInObject =
                obj.objVerEx.Vault.ObjectOperations.GetLatestObjectVersionAndProperties(obj.objVerEx.ObjID, true);

            if (checkedInObject.VersionData.ObjectCheckedOut)
            {
                return(false);
            }
            //
            bool          checkedOutByVAF = false;
            ObjectVersion objVersion      = null;
            PropertyValue prop_modifiedby = null;

            try {
                prop_modifiedby = obj.objVerEx.GetProperty(PD_Last_modified_by.id);
                objVersion      = obj.objVerEx.Vault.ObjectOperations.CheckOut(obj.objVerEx.ObjID);
                checkedOutByVAF = true;
                //
                PropertyValues propsToUpdate = obj.objVerEx.Properties.Clone();
                if (checkedInObject.Properties.Exists(PD_Comment.id) && obj.objVerEx.Properties.Exists(PD_Comment.id) &&
                    obj.objVerEx.VersionComment == checkedInObject.Properties.GetProperty(PD_Comment.id).GetValueAsUnlocalizedText())
                {
                    propsToUpdate.Remove(propsToUpdate.IndexOf(PD_Comment.id));
                }
                if (skipVafCalculation)
                {
                    string keyword = string.Empty;
                    if (propsToUpdate.TryGetProperty(26, out PropertyValue kw))
                    {
                        keyword = kw.GetValueAsUnlocalizedText();
                    }
                    propsToUpdate.SetProperty(26, MFDataType.MFDatatypeText, $"{keyword}SKIP_VAF_CALCULATIONS");
                }
                ObjectVersionAndProperties objVerAndProps =
                    obj.objVerEx.Vault.ObjectPropertyOperations.SetAllProperties(objVersion.ObjVer, false, propsToUpdate);

                if (prop_modifiedby != null)
                {
                    if (modifiedby_userid != null)
                    {
                        prop_modifiedby.TypedValue.SetValue(MFDataType.MFDatatypeLookup, modifiedby_userid);
                    }
                    objVerAndProps = obj.objVerEx.Vault.ObjectPropertyOperations.SetLastModificationInfoAdmin(objVersion.ObjVer, true, prop_modifiedby.TypedValue, false, null);
                }

                //replace files
                if (replace_files?.Length > 0 && objVersion.ObjVer.Type == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument)
                {
                    SourceObjectFiles objFiles = new SourceObjectFiles();
                    foreach (string file_name in replace_files)
                    {
                        FileInfo fi    = new FileInfo(file_name);
                        string   title = fi.Name.Replace(fi.Extension, "");
                        string   ext   = fi.Extension.Replace(".", "");
                        objFiles.AddFile(title, ext, fi.FullName);
                        if (objVersion.SingleFile)
                        {
                            IEnumerator fileEnum = objVersion.Files.GetEnumerator();
                            fileEnum.MoveNext();
                            obj.objVerEx.Vault.ObjectFileOperations.RenameFile(objVersion.ObjVer, (fileEnum.Current as ObjectFile).FileVer, title, ext, false);
                            break;
                        }
                    }
                    ObjVerEx checkedOutVerEx = new ObjVerEx(obj.objVerEx.Vault, objVersion);
                    checkedOutVerEx.ReplaceFiles(objFiles);
                }

                objVersion                  = obj.objVerEx.Vault.ObjectOperations.CheckIn(objVerAndProps.ObjVer);
                checkedOutByVAF             = false;
                obj.objVerEx.ObjVer.Version = objVersion.ObjVer.Version;
                //
                if (returnUpdatedMetadata)
                {
                    objVerAndProps = obj.objVerEx.Vault.ObjectOperations.GetLatestObjectVersionAndProperties(obj.objVerEx.ObjID, false);
                    obj.objVerEx   = new ObjVerEx(obj.objVerEx.Vault, objVerAndProps);
                    obj.ClearAllCachedProperties();
                }
            } catch (Exception ex) {
                throw ex;
            } finally {
                if (objVersion != null && checkedOutByVAF)
                {
                    // Undo checkout and enforces the operation.
                    obj.objVerEx.Vault.ObjectOperations.ForceUndoCheckout(objVersion.ObjVer);
                }
            }

            return(true);
        }
Esempio n. 23
0
    //private int GetObjectTypeId(CsvModel csvModel, Vault vault)
    //{
    //  ObjTypes objectTypes = vault.ObjectTypeOperations.GetObjectTypes();
    //  int objectTypeId = -1;

    //  foreach (ObjType objectType in objectTypes)
    //  {
    //    if (objectType.NameSingular == csvModel.ObjectType)
    //    {
    //      objectTypeId = objectType.ID;
    //      break;
    //    }

    //    Debug.WriteLine(objectType.NameSingular);
    //  }
    //  return objectTypeId;
    //}

    //private int GetClassId(CsvModel csvModel, Vault vault)
    //{
    //  var allObjectClasses = vault.ClassOperations.GetAllObjectClasses();
    //  int classId = -1;
    //  foreach (ObjectClass objectClass in allObjectClasses)
    //  {
    //    if (csvModel.Class == objectClass.Name)
    //    {
    //      classId = objectClass.ID;
    //      break;
    //    }
    //    //Debug.WriteLine(string.Format("Id={0}, Name={1}", objectClass.ID, objectClass.Name));
    //  }
    //  return classId;
    //}

    //private ObjectVersionAndProperties GetObjectVersionAndPropertiesAndCheckin(CsvModel csvModel, Vault vault, PropertyValues propertyValues, SourceObjectFiles sourceObjectFiles, int objectTypeId)
    //{
    //  if (objectTypeId == -1)
    //    throw new ArgumentException(string.Format("could not find objectType with name '{0}'", csvModel.ObjectType));

    //  Debug.WriteLine("objectTypeId: " + objectTypeId);

    //  return vault.ObjectOperations.CreateNewObjectEx(objectTypeId, propertyValues, SourceFiles, false, false)
    //  return vault.ObjectOperations.CreateNewObject(objectTypeId, propertyValues, sourceObjectFiles);
    //}

    private ObjectVersionAndProperties GetObjectVersionAndProperties(CsvModel csvModel, Vault vault, PropertyValues propertyValues, SourceObjectFiles sourceObjectFiles, int objectTypeId)
    {
      if (objectTypeId == -1)
        throw new ArgumentException(string.Format("could not find objectType with name '{0}'", csvModel.ObjectType));

      Debug.WriteLine("objectTypeId: " + objectTypeId);

      //return vault.ObjectOperations.CreateNewObjectEx(objectTypeId, propertyValues, sourceObjectFiles, false, false);
      return vault.ObjectOperations.CreateNewObject(objectTypeId, propertyValues, sourceObjectFiles);
    }
Esempio n. 24
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);
        }