示例#1
0
        /// <summary>
        /// Creates a document.
        /// </summary>
        /// <returns>The document.</returns>
        /// <param name="folder">Parent folder.</param>
        /// <param name="name">Name of the document.</param>
        /// <param name="content">If content is not null, a content stream containing the given content will be added.</param>
        /// <param name="checkedOut">If true, the new document will be created in checked out state.</param>
        public static IDocument CreateDocument(this IFolder folder, string name, string content, bool checkedOut = false)
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, name);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());

            if (string.IsNullOrEmpty(content))
            {
                return(folder.CreateDocument(properties, null, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null));
            }

            ContentStream contentStream = new ContentStream();

            contentStream.FileName = name;
            contentStream.MimeType = MimeType.GetMIMEType(name);
            contentStream.Length   = content.Length;
            IDocument doc = null;

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                contentStream.Stream = stream;
                doc = folder.CreateDocument(properties, contentStream, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null);
            }

            return(doc);
        }
示例#2
0
        private static void UploadTest()
        {
            AuthInfo authInfo = AuthInfo.ReadAuthInfo();
            ISession session  = SessionUtils.CreateSession(authInfo.serviceUrl, authInfo.username, authInfo.password);
            //IFolder rootFolder = session.GetRootFolder();
            IFolder userHomeFolder = GetUserFolder(session, authInfo.username);

            // document name
            string formattedName = "Home Page.pdf";

            // define dictionary
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, formattedName);

            // define object type as document, as we wanted to create document
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

            // read a empty document with empty bytes
            // fileUpload1: is a .net file upload control
            byte[]        datas         = File.ReadAllBytes("C:\\Users\\KVM\\Home Page.pdf");
            ContentStream contentStream = new ContentStream
            {
                FileName = formattedName,
                MimeType = "application/pdf",
                Length   = datas.Length,
                Stream   = new MemoryStream(datas)
            };

            // this statment would create document in default repository
            userHomeFolder.CreateDocument(properties, contentStream, null);
            Debug.WriteLine("OK");
        }
示例#3
0
        public void RemoteDocumentCreation(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                           string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Remote file creations
            string[] remoteFilenames = { "document.txt", "いろんなカタチが、見えてくる。", "مشاور", "コンサルティングपरामर्शदाता컨설턴트" };
            foreach (string remoteFilename in remoteFilenames)
            {
                // Create remote file
                IDictionary <string, object> properties = new Dictionary <string, object>();
                properties[PropertyIds.Name]         = remoteFilename;
                properties[PropertyIds.ObjectTypeId] = "cmis:document";
                byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes("Hello World!");
                ContentStream creationContentStream = new ContentStream();
                creationContentStream.FileName = remoteFilename;
                creationContentStream.MimeType = "text/plain";
                creationContentStream.Length   = creationContent.Length;
                creationContentStream.Stream   = new MemoryStream(creationContent);
                remoteBaseFolder.CreateDocument(properties, creationContentStream, null);

                // Wait for a few seconds so that sync gets a chance to sync things.
                Thread.Sleep(20 * 1000);

                // Check locally
                Assert.True(File.Exists(Path.Combine(sync.Folder(), (String)properties[PropertyIds.Name])));
            }
        }
示例#4
0
        public void GetContentStreamHash(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            Regex    entryRegex = new Regex(@"^\{.+\}[0-9a-fA-F]+$");
            ISession session    = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);
            IFolder  folder     = (IFolder)session.GetObjectByPath(remoteFolderPath);
            string   filename   = "hashedfile.txt";

            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            using (var oneByteStream = new MemoryStream(new byte[1])) {
                ContentStream contentStream = new ContentStream();
                contentStream.MimeType = MimeType.GetMIMEType(filename);
                contentStream.Length   = 1;
                contentStream.Stream   = oneByteStream;
                var       emptyDoc     = folder.CreateDocument(properties, contentStream, null);
                var       context      = new OperationContext();
                IDocument requestedDoc = session.GetObject(emptyDoc, context) as IDocument;
                foreach (var prop in requestedDoc.Properties)
                {
                    if (prop.Id == "cmis:contentStreamHash")
                    {
                        Assert.That(prop.IsMultiValued, Is.True);
                        if (prop.Values != null)
                        {
                            foreach (string entry in prop.Values)
                            {
                                Assert.That(entryRegex.IsMatch(entry));
                            }
                        }
                    }
                }

                byte[] remoteHash = requestedDoc.ContentStreamHash();
                if (remoteHash != null)
                {
                    Assert.That(remoteHash, Is.EqualTo(SHA1.Create().ComputeHash(new byte[1])));
                }

                requestedDoc.Delete(true);
            }
        }
示例#5
0
        private IDocument CreateNewFile(IFolder folder, string file)
        {
            try
            {
                var fi = new FileInfo(file);
                IDictionary <string, object> properties = new Dictionary <string, object>();
                properties[PropertyIds.Name]         = fi.Name;
                properties[PropertyIds.ObjectTypeId] = "cmis:document";

                var content = File.ReadAllBytes(fi.FullName);

                var contentStream = new ContentStream
                {
                    FileName = fi.Name,
                    MimeType = "application/pdf",
                    Length   = content.Length,
                    Stream   = new MemoryStream(content)
                };

                var doc = folder.CreateDocument(properties, contentStream, null);

                Log.Information("Uploaded new document");
                return(doc);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(null);
        }
示例#6
0
        public void RemovingRemoteFolderAndAddingADocumentToItShouldThrowException(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            string   subFolderName = "subFolder";
            ISession session       = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            try {
                IFolder dir = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + subFolderName) as IFolder;
                if (dir != null)
                {
                    dir.DeleteTree(true, null, true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            IFolder folder                = (IFolder)session.GetObjectByPath(remoteFolderPath);
            IFolder subFolder             = folder.CreateFolder(subFolderName);
            IFolder subFolderInstanceCopy = (IFolder)session.GetObject(subFolder.Id);

            subFolder.DeleteTree(true, null, true);

            Assert.Throws <CmisObjectNotFoundException>(() => subFolderInstanceCopy.CreateDocument("testFile.bin", "testContent"));
        }
示例#7
0
        private static void UploadRandomDocumentTo(IFolder folder)
        {
            string filename = "file_" + Guid.NewGuid() + ".bin";

            //byte[] content = UTF8Encoding.UTF8.GetBytes("Hello World!");
            int sizeInMb = 40;
            byte[] data = new byte[sizeInMb * 1024 * 1024];
            Random rng = new Random();
            rng.NextBytes(data);

            IDictionary<string, object> properties = new Dictionary<string, object>();
            properties[PropertyIds.Name] = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            ContentStream contentStream = new ContentStream();
            contentStream.FileName = filename;
            contentStream.MimeType = "application/octet-stream";
            contentStream.Length = data.Length;
            contentStream.Stream = new MemoryStream(data);

            Console.Write("Uploading " + filename + " ... ");
            folder.CreateDocument(properties, contentStream, null);
            Console.WriteLine(" Done.");

            contentStream.Stream.Close();
            contentStream.Stream.Dispose();
        }
示例#8
0
        public void GetSyncPropertyFromFile(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            session.EnsureSelectiveIgnoreSupportIsAvailable();
            IFolder folder   = (IFolder)session.GetObjectByPath(remoteFolderPath);
            string  filename = "testfile.txt";

            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            IList <string> devices = new List <string>();

            devices.Add("*");
            properties.Add("gds:ignoreDeviceIds", devices);
            IList <string> ids = new List <string>();

            ids.Add("gds:sync");
            properties.Add(PropertyIds.SecondaryObjectTypeIds, ids);

            IDocument emptyDoc = folder.CreateDocument(properties, null, null);

            Assert.That(emptyDoc.ContentStreamLength == 0 || emptyDoc.ContentStreamLength == null);
            var       context       = new OperationContext();
            IDocument requestedDoc  = session.GetObject(emptyDoc, context) as IDocument;
            bool      propertyFound = false;

            foreach (var prop in requestedDoc.Properties)
            {
                if (prop.Id == "gds:ignoreDeviceIds")
                {
                    propertyFound = true;
                    Assert.AreEqual("*", prop.FirstValue as string);
                }
            }

            Assert.IsTrue(propertyFound);
            emptyDoc.DeleteAllVersions();
        }
示例#9
0
        public void AppendContentStreamTest(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId)
        {
            // var watch = Stopwatch.StartNew();
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId);

            // watch.Stop();
            // Console.WriteLine(String.Format("Created Session in {0} msec",watch.ElapsedMilliseconds));
            // watch.Restart();
            IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath);

            // watch.Stop();
            // Console.WriteLine(String.Format("Requested folder in {0} msec", watch.ElapsedMilliseconds));
            string filename = "testfile.txt";
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");
            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (Exception) {
            }

            // watch.Restart();
            IDocument emptyDoc = folder.CreateDocument(properties, null, null);

            // watch.Stop();
            // Console.WriteLine(String.Format("Created empty doc in {0} msec", watch.ElapsedMilliseconds));
            Assert.That(emptyDoc.ContentStreamLength == 0 || emptyDoc.ContentStreamLength == null, "returned document shouldn't got any content");
            string content = "test";

            for (int i = 0; i < 10; i++)
            {
                ContentStream contentStream = new ContentStream();
                contentStream.FileName = filename;
                contentStream.MimeType = MimeType.GetMIMEType(filename);
                contentStream.Length   = content.Length;
                using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                    contentStream.Stream = memstream;
                    emptyDoc.AppendContentStream(contentStream, i == 9, true);
                }

                Assert.AreEqual(content.Length * (i + 1), emptyDoc.ContentStreamLength);
            }

            emptyDoc.DeleteAllVersions();
        }
示例#10
0
        public void _CurrentlyFailing_RemoteDocumentModification(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                                                 string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Create remote file
            string filename = "document.txt";
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes("Hello World!");
            ContentStream creationContentStream = new ContentStream();

            creationContentStream.FileName = filename;
            creationContentStream.MimeType = "text/plain";
            creationContentStream.Length   = creationContent.Length;
            creationContentStream.Stream   = new MemoryStream(creationContent);

            IDocument doc = remoteBaseFolder.CreateDocument(properties, creationContentStream, null);

            // Wait for a few seconds so that sync gets a chance to sync things.
            Thread.Sleep(20 * 1000);

            // Check locally
            Assert.True(File.Exists(Path.Combine(sync.Folder(), (String)properties[PropertyIds.Name])));

            // Modify remote document.
            doc = (IDocument)CreateSession(url, user, password, repositoryId)
                  .GetObjectByPath(remoteFolderPath + "/" + filename, true);

            string contentString = "Hello World, edited.";

            byte[]        content       = UTF8Encoding.UTF8.GetBytes(contentString);
            ContentStream contentStream = new ContentStream();

            contentStream.FileName = filename;
            contentStream.MimeType = "text/plain";
            contentStream.Length   = content.Length;
            contentStream.Stream   = new MemoryStream(content);

            doc.SetContentStream(contentStream, true);

            // Wait so that sync gets a chance to sync things.
            Thread.Sleep(30 * 1000);

            // Check local file
            string remoteContent = File.ReadAllText(Path.Combine(sync.Folder(), filename));

            Assert.AreEqual(contentString, remoteContent);
        }
示例#11
0
        public void SetJPEGContentStream(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session  = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);
            IFolder  folder   = (IFolder)session.GetObjectByPath(remoteFolderPath);
            string   filename = "testfile.jpg";
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            }
            catch (CmisObjectNotFoundException) {
            }

            IDocument emptyDoc = folder.CreateDocument(properties, null, null);

            Assert.That(emptyDoc.ContentStreamLength == null || emptyDoc.ContentStreamLength == 0, "returned document shouldn't got any content");
            int contentLength = 1024;

            byte[] content = new byte[contentLength];
            using (RandomNumberGenerator random = RandomNumberGenerator.Create()) {
                random.GetBytes(content);
            }

            ContentStream contentStream = new ContentStream();

            contentStream.FileName = filename;
            contentStream.MimeType = MimeType.GetMIMEType(filename);
            contentStream.Length   = content.Length;

            using (var memstream = new MemoryStream(content)) {
                contentStream.Stream = memstream;
                emptyDoc.SetContentStream(contentStream, true, true);
            }

            Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength, "Setting content failed");
            IDocument randomDoc = session.GetObjectByPath(emptyDoc.Paths[0]) as IDocument;

            Assert.That(randomDoc != null);
            Assert.AreEqual(content.Length, randomDoc.ContentStreamLength, "Getting content on new object failed");
            emptyDoc.DeleteAllVersions();
        }
示例#12
0
        public IDocument CreateTextDocument(IFolder parent, string name, string content)
        {
            IDictionary <string, object> props = new Dictionary <string, object>();

            props[PropertyIds.Name]         = name;
            props[PropertyIds.ObjectTypeId] = "cmis:document";

            IContentStream contentStream = ContentStreamUtils.CreateTextContentStream(name, content);

            return(parent.CreateDocument(props, contentStream, VersioningState.None));
        }
示例#13
0
        public void AppendContentStreamTest(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);
            IFolder  folder  = (IFolder)session.GetObjectByPath(remoteFolderPath);

            string filename = "testfile.txt";
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            IDocument doc = null;

            try {
                doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (Exception) {
            }

            string content         = "test";
            string expectedContent = string.Empty;

            doc             = folder.CreateDocument(filename, content);
            expectedContent = content;
            Assert.That(doc.ContentStreamLength == content.Length, "returned document should have got content");
            for (int i = 0; i < 10; i++)
            {
                doc              = doc.AppendContent(content, i == 9) ?? doc;
                expectedContent += content;
                Assert.AreEqual(expectedContent.Length, doc.ContentStreamLength);
            }

            doc.AssertThatIfContentHashExistsItIsEqualTo(expectedContent);

            for (int i = 0; i < 10; i++)
            {
                doc              = doc.AppendContent(content) ?? doc;
                expectedContent += content;
                Assert.AreEqual(expectedContent.Length, doc.ContentStreamLength);
                doc.AssertThatIfContentHashExistsItIsEqualTo(expectedContent);
            }

            doc.DeleteAllVersions();
        }
示例#14
0
        public void _CurrentlyFailing_RemoteFolderRename(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                                         string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Create remote folder
            string foldername = "folder1";
            IDictionary <string, object> folderProperties = new Dictionary <string, object>();

            folderProperties[PropertyIds.Name]         = foldername;
            folderProperties[PropertyIds.ObjectTypeId] = "cmis:folder";
            IFolder folder = remoteBaseFolder.CreateFolder(folderProperties);

            // Create remote file inside that folder.
            string filename = "document.txt";
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";
            string contentString = "Hello World!";

            byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes(contentString);
            ContentStream creationContentStream = new ContentStream();

            creationContentStream.FileName = filename;
            creationContentStream.MimeType = "text/plain";
            creationContentStream.Length   = creationContent.Length;
            creationContentStream.Stream   = new MemoryStream(creationContent);
            IDocument doc = folder.CreateDocument(properties, creationContentStream, null);

            // Check locally
            Thread.Sleep(20 * 1000);
            string syncedContent = File.ReadAllText(Path.Combine(sync.Folder(), foldername, filename));

            Assert.AreEqual(contentString, syncedContent);
            Assert.True(Directory.Exists(Path.Combine(sync.Folder(), foldername)));

            // Rename folder
            string newFoldername = "renamed folder";

            folder.Rename(newFoldername);

            // Check locally
            Thread.Sleep(20 * 1000);
            Assert.True(File.Exists(Path.Combine(sync.Folder(), newFoldername, filename)), "File not present where it should be");
            syncedContent = File.ReadAllText(Path.Combine(sync.Folder(), foldername, filename));
            Assert.AreEqual(contentString, syncedContent);
            Assert.False(File.Exists(Path.Combine(sync.Folder(), foldername, filename)), "File present where it should not be");
        }
示例#15
0
        /// <summary>
        /// Creates a document.
        /// </summary>
        /// <returns>The document.</returns>
        /// <param name="folder">Parent folder.</param>
        /// <param name="name">Name of the document.</param>
        /// <param name="content">If content is not null, a content stream containing the given content will be added.</param>
        public static IDocument CreateDocument(this IFolder folder, string name, string content)
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, name);
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

            if (string.IsNullOrEmpty(content))
            {
                return(folder.CreateDocument(properties, null, null));
            }

            ContentStream contentStream = new ContentStream();

            contentStream.FileName = name;
            contentStream.MimeType = MimeType.GetMIMEType(name);
            contentStream.Length   = content.Length;
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
                contentStream.Stream = stream;
                return(folder.CreateDocument(properties, contentStream, null));
            }
        }
示例#16
0
            /// <summary>
            /// Upload a single file to the CMIS server.
            /// </summary>
            private bool UploadFile(string filePath, IFolder remoteFolder)
            {
                sleepWhileSuspended();

                Logger.Info("Uploading: " + filePath);

                try
                {
                    IDocument remoteDocument = null;
                    byte[]    filehash       = { };

                    // Prepare properties
                    string fileName = Path.GetFileName(filePath);
                    Dictionary <string, object> properties = new Dictionary <string, object>();
                    properties.Add(PropertyIds.Name, fileName);
                    properties.Add(PropertyIds.ObjectTypeId, "cmis:document");
                    properties.Add(PropertyIds.CreationDate, File.GetCreationTime(filePath));
                    properties.Add(PropertyIds.LastModificationDate, File.GetLastWriteTime(filePath));

                    // Prepare content stream
                    using (Stream file = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        using (SHA1 hashAlg = new SHA1Managed())
                            using (CryptoStream hashstream = new CryptoStream(file, hashAlg, CryptoStreamMode.Read))
                            {
                                ContentStream contentStream = new ContentStream();
                                contentStream.FileName = fileName;
                                contentStream.MimeType = MimeType.GetMIMEType(fileName);
                                contentStream.Length   = file.Length;
                                contentStream.Stream   = hashstream;

                                remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null);
                                filehash       = hashAlg.Hash;
                            }

                    // Metadata.
                    Logger.Info("Uploaded: " + filePath);

                    // Get metadata. Some metadata has probably been automatically added by the server.
                    Dictionary <string, string[]> metadata = metadata = FetchMetadata(remoteDocument);

                    // Create database entry for this file.
                    database.AddFile(filePath, remoteDocument.LastModificationDate, metadata, filehash);
                    Logger.Info("Added file to database: " + filePath);
                    return(true);
                }
                catch (Exception e)
                {
                    ProcessRecoverableException("Could not upload file: " + filePath, e);
                    return(false);
                }
            }
示例#17
0
        public void RemoteDocumentDeletionThenSameNameFolderCreation(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                                                     string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Remote file creation

            string remoteObjectName = "document.or.folder";
            // Create remote file
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = remoteObjectName;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes("Hello World!");
            ContentStream creationContentStream = new ContentStream();

            creationContentStream.FileName = remoteObjectName;
            creationContentStream.MimeType = "text/plain";
            creationContentStream.Length   = creationContent.Length;
            creationContentStream.Stream   = new MemoryStream(creationContent);

            IDocument document = remoteBaseFolder.CreateDocument(properties, creationContentStream, null);

            // Wait for 10 seconds so that sync gets a chance to sync things.
            Thread.Sleep(10 * 1000);

            // Check locally
            Assert.True(File.Exists(Path.Combine(sync.Folder(), remoteObjectName)));

            // Delete remote document
            document.DeleteAllVersions();

            // Immediately create remote folder with exact same name
            IDictionary <string, object> folderProperties = new Dictionary <string, object>();

            folderProperties[PropertyIds.Name]         = remoteObjectName;
            folderProperties[PropertyIds.ObjectTypeId] = "cmis:folder";
            IFolder folder = remoteBaseFolder.CreateFolder(folderProperties);

            // Wait for 10 seconds so that sync gets a chance to sync things.
            Thread.Sleep(10 * 1000);

            // Check locally
            Assert.True(Directory.Exists(Path.Combine(sync.Folder(), remoteObjectName)));
        }
示例#18
0
        public void CheckoutTest(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            string subFolderName = "subFolder";
            string fileName      = "testFile.bin";
            string subFolderPath = remoteFolderPath.TrimEnd('/') + "/" + subFolderName;
            string filePath      = subFolderPath + "/" + fileName;

            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            if (!session.ArePrivateWorkingCopySupported())
            {
                Assert.Ignore("PWCs are not supported");
            }

            try {
                IFolder dir = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + subFolderName) as IFolder;
                if (dir != null)
                {
                    dir.DeleteTree(true, null, true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            IFolder folder    = (IFolder)session.GetObjectByPath(remoteFolderPath);
            IFolder subFolder = folder.CreateFolder(subFolderName);

            IDocument doc         = subFolder.CreateDocument(fileName, "testContent", checkedOut: true);
            IObjectId checkoutId  = doc.CheckOut();
            IDocument docCheckout = (IDocument)session.GetObject(checkoutId);

            Assert.AreEqual(doc.ContentStreamLength, docCheckout.ContentStreamLength);
            doc.Refresh();
            Assert.IsTrue(doc.IsVersionSeriesCheckedOut.GetValueOrDefault());
            Assert.AreEqual(checkoutId.Id, doc.VersionSeriesCheckedOutId);

            docCheckout.CancelCheckOut();
            doc.Refresh();
            Assert.IsFalse(doc.IsVersionSeriesCheckedOut.GetValueOrDefault());
            Assert.IsNull(doc.VersionSeriesCheckedOutId);
        }
        private IDocument Upload(IFolder uploadFolder, MakuraDocument document)
        {
            var cmisDocumentStream = document.ContentStream.ConvertCmis();
            var existDoc = uploadFolder.GetChildren().OfType<IDocument>().FirstOrDefault(p => p.Name == document.Name);

            if (existDoc == null) {
                var properties = new Dictionary<string, object>();
                properties[PropertyIds.Name] = document.Name;
                properties[PropertyIds.ObjectTypeId] = "cmis:document";

                return uploadFolder.CreateDocument(properties, cmisDocumentStream, DotCMIS.Enums.VersioningState.Minor);
            } else {
                existDoc.SetContentStream(cmisDocumentStream,true);
                return existDoc;
            }
        }
示例#20
0
        protected IDocument CreateRemoteDocument(IFolder folder, string name, string content)
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, name);
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

            ContentStream contentStream = new ContentStream();

            contentStream.FileName = name;
            contentStream.MimeType = MimeType.GetMIMEType(name);
            contentStream.Length   = content.Length;
            contentStream.Stream   = new MemoryStream(Encoding.UTF8.GetBytes(content));

            return(folder.CreateDocument(properties, contentStream, null));
        }
示例#21
0
        public static AlfResult UploadFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    AuthInfo authInfo = AuthInfo.ReadAuthInfo();
                    //IFolder rootFolder = session.GetRootFolder();
                    IFolder userHomeFolder = (IFolder)Session.GetObjectByPath("/" + AlfDefs.DEFAULT_DIR_NAME_USER_HOMES + "/" + authInfo.username);

                    // document name
                    string formattedName = Path.GetFileName(filePath);

                    // define dictionary
                    IDictionary <string, object> properties = new Dictionary <string, object>();
                    properties.Add(PropertyIds.Name, formattedName);

                    // define object type as document, as we wanted to create document
                    properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

                    // read a empty document with empty bytes
                    // fileUpload1: is a .net file upload control
                    byte[]        datas         = File.ReadAllBytes(filePath);
                    string        mimeType      = MimeTypeMap.GetMimeType(Path.GetExtension(filePath));
                    ContentStream contentStream = new ContentStream
                    {
                        FileName = formattedName,
                        MimeType = mimeType,
                        Length   = datas.Length,
                        Stream   = new MemoryStream(datas)
                    };

                    // this statment would create document in default repository
                    userHomeFolder.CreateDocument(properties, contentStream, null);

                    return(new AlfResult(AlfResult.STATUS_OK, "Success"));
                }
                else
                {
                    return(new AlfResult(AlfResult.STATUS_FILE_NOT_FOUND, "File not found"));
                }
            }
            catch (Exception e)
            {
                return(new AlfResult(AlfResult.STATUS_EXCEPTION, e.StackTrace));
            }
        }
        public IDocument Post(string DocumentName, string DocumentType, byte[] File, string FolderName)
        {
            //IFolder folder = session.GetRootFolder();
            Master = (IFolder)session.GetObject("8a4fec83-a7db-4636-8e84-9ed0babac107");

            var Exists = Master.GetChildren(operationContext).Any(child => child.Name.Equals(FolderName));

            if (Exists)
            {
                IItemEnumerable <ICmisObject> Children = Master.GetChildren();

                foreach (var child in Children)
                {
                    if (child.Name == FolderName)
                    {
                        WorkingDirectory = child as IFolder;
                    }
                }
            }
            else
            {
                WorkingDirectory = CreateFolder(Master, FolderName);
            }


            // define dictionary
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, DocumentName);
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");
            ContentStream contentStream = new ContentStream
            {
                FileName = DocumentName,
                MimeType = DocumentType,
                Length   = File.Length,
                Stream   = new MemoryStream(File)
            };


            if (FileExists(WorkingDirectory, DocumentName))
            {
                IItemEnumerable <ICmisObject> Files = WorkingDirectory.GetChildren();
                DeleteFile(Files, DocumentName);
            }

            return(WorkingDirectory.CreateDocument(properties, contentStream, null));
        }
示例#23
0
        public void EnsureFileNameStaysEqualWhileUploading(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath);

            string filename = "testfile.txt";
            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            try {
                IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            IDocument emptyDoc = folder.CreateDocument(properties, null, null);
            int       length   = 1024 * 1024;

            byte[]        content       = new byte[length];
            ContentStream contentStream = new ContentStream();

            contentStream.FileName = filename;
            contentStream.MimeType = MimeType.GetMIMEType(filename);
            contentStream.Length   = content.Length;
            Action assert = delegate {
                Assert.That((session.GetObject(emptyDoc.Id, OperationContextFactory.CreateNonCachingPathIncludingContext(session)) as IDocument).Name, Is.EqualTo(filename));
            };

            using (var memstream = new AssertingStream(new MemoryStream(content), assert)) {
                contentStream.Stream = memstream;
                emptyDoc.SetContentStream(contentStream, true, true);
            }
        }
示例#24
0
        public void CreateDocumentWithCreationAndModificationDate(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId,
            string binding)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding);

            if (!session.IsServerAbleToUpdateModificationDate())
            {
                Assert.Ignore("Server is not able to sync modification dates");
            }

            string    filename = "name";
            IDocument doc;

            try {
                doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument;
                if (doc != null)
                {
                    doc.Delete(true);
                }
            } catch (CmisObjectNotFoundException) {
            }

            DateTime creationDate     = DateTime.UtcNow - TimeSpan.FromDays(1);
            DateTime modificationDate = DateTime.UtcNow - TimeSpan.FromHours(1);
            IFolder  folder           = (IFolder)session.GetObjectByPath(remoteFolderPath);

            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue());
            properties.Add(PropertyIds.Name, filename);
            properties.Add(PropertyIds.CreationDate, creationDate);
            properties.Add(PropertyIds.LastModificationDate, modificationDate);

            doc = folder.CreateDocument(properties, null, null);

            Assert.That(((DateTime)doc.LastModificationDate - modificationDate).Seconds, Is.EqualTo(0), "Wrong modification date");
            Assert.That(((DateTime)doc.CreationDate - creationDate).Seconds, Is.EqualTo(0), "Wrong creation date");
            doc.DeleteAllVersions();
        }
        public Document Create(IRepository repository, String folderPath)
        {
            var parameters = GetParameters(repository.Id);

            var session = _factory.CreateSession(parameters);

            IFolder folder = (Folder)session.GetObjectByPath("/" + folderPath);

            var properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = String.Format("hello world {0}", Guid.NewGuid());
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            var content = Encoding.UTF8.GetBytes(String.Format("Hello World at {0}", DateTime.Now));

            try
            {
                var contentStream = new ContentStream
                {
                    FileName = String.Format("hello-world_{0}.txt", Guid.NewGuid()),
                    MimeType = "text/plain",
                    Length   = content.Length,
                    Stream   = new MemoryStream(content)
                };

                var operationContext = new OperationContext {
                    IncludeAcls = true
                };

                var doc =
                    (Document)
                    folder.CreateDocument(properties, contentStream, VersioningState.Major, new List <IPolicy>(), null,
                                          null, operationContext);

                session.Clear();

                return(doc);
            }
            catch (CmisBaseException baseException)
            {
                var mess = baseException.ErrorContent;

                throw;
            }
        }
示例#26
0
        public void CreateDocumentWithContentStream(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId);

            IFolder   folder  = (IFolder)session.GetObjectByPath(remoteFolderPath);
            string    content = "content";
            IDocument doc     = folder.CreateDocument("name", content);

            Assert.That(doc.ContentStreamLength, Is.EqualTo(content.Length));
            doc.DeleteAllVersions();
        }
示例#27
0
        public void _CurrentlyFailing_RemoteDocumentRename(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                                           string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Remote file creation
            string filename = "document.txt";
            // Create remote file
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes("Hello World!");
            ContentStream creationContentStream = new ContentStream();

            creationContentStream.FileName = filename;
            creationContentStream.MimeType = "text/plain";
            creationContentStream.Length   = creationContent.Length;
            creationContentStream.Stream   = new MemoryStream(creationContent);

            IDocument document = remoteBaseFolder.CreateDocument(properties, creationContentStream, null);

            // Wait for a few seconds so that sync gets a chance to sync things.
            Thread.Sleep(20 * 1000);

            // Check locally
            Assert.True(File.Exists(Path.Combine(sync.Folder(), (String)properties[PropertyIds.Name])));

            string newFilename = "renamed.txt";

            //document.Move(remoteBaseFolder, folder);
            document.Rename(newFilename);

            // Wait for a few seconds so that sync gets a chance to sync things.
            Thread.Sleep(20 * 1000);

            // Check locally
            Assert.False(File.Exists(Path.Combine(sync.Folder(), filename))); // Currently fails, local document is not renamed, even though document is correctly renamed on server.
            Assert.True(File.Exists(Path.Combine(sync.Folder(), newFilename)));
        }
示例#28
0
        public void RemoteDocumentMetadataModification(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath,
                                                       string url, string user, string password, string repositoryId)
        {
            // Prepare remote folder and CmisSync process.
            IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath);

            sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId);

            // Create remote file
            string filename = "document.txt";
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties[PropertyIds.Name]         = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            byte[]        creationContent       = UTF8Encoding.UTF8.GetBytes("Hello World!");
            ContentStream creationContentStream = new ContentStream();

            creationContentStream.FileName = filename;
            creationContentStream.MimeType = "text/plain";
            creationContentStream.Length   = creationContent.Length;
            creationContentStream.Stream   = new MemoryStream(creationContent);

            IDocument doc = remoteBaseFolder.CreateDocument(properties, creationContentStream, null);

            // Wait for 10 seconds so that sync gets a chance to sync things.
            Thread.Sleep(10 * 1000);

            // Check locally
            Assert.True(File.Exists(Path.Combine(sync.Folder(), (String)properties[PropertyIds.Name])));

            // Modify remote document metadata.
            doc = (IDocument)CreateSession(url, user, password, repositoryId)
                  .GetObjectByPath(remoteFolderPath + "/" + filename, true);

            // TODO create custom aspect on server
            //properties[PropertyIds.] = filename;

            // Wait so that sync gets a chance to sync things.
            Thread.Sleep(30 * 1000);

            // Check local file's metadata in database
            // TODO
        }
示例#29
0
        public void RemovingRemoteFolderAndAddingADocumentToItShouldThrowException(
            string canonical_name,
            string localPath,
            string remoteFolderPath,
            string url,
            string user,
            string password,
            string repositoryId)
        {
            ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId);

            IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath);

            IFolder subFolder = folder.CreateFolder("subFolder");

            IFolder subFolderInstanceCopy = (IFolder)session.GetObject(subFolder.Id);

            subFolder.DeleteTree(true, null, true);

            Assert.Throws <CmisObjectNotFoundException>(() => subFolderInstanceCopy.CreateDocument("testFile.bin", "testContent"));
        }
示例#30
0
        public IDocument CreateTextDocument(IFolder parent, string name, string content)
        {
            IDictionary <string, object> props = new Dictionary <string, object>();

            props[PropertyIds.Name]         = name;
            props[PropertyIds.ObjectTypeId] = "cmis:document";

            IContentStream contentStream = ContentStreamUtils.CreateTextContentStream(name, content);

            IDocument newDoc = parent.CreateDocument(props, contentStream, VersioningState.None);


            Assert.IsNotNull(newDoc);
            Assert.AreEqual(BaseTypeId.CmisDocument, newDoc.BaseTypeId);
            Assert.AreEqual("cmis:document", newDoc.DocumentType.Id);
            Assert.AreEqual(name, newDoc.Name);
            Assert.AreEqual(parent.Id, newDoc.Parents[0].Id);
            Assert.IsNotNull(newDoc.CreationDate);
            Assert.IsNotNull(newDoc.CreatedBy);
            Assert.IsNotNull(newDoc.LastModificationDate);
            Assert.IsNotNull(newDoc.LastModifiedBy);

            return(newDoc);
        }
示例#31
0
        public void Upload()
        {
            this.session = this.GetSession();
            IFolder folder = (IFolder)this.session.GetObjectByPath("/sites/" + AppConfigKeys.Site + "/documentLibrary/" + HttpContext.Current.Request.Form["path"] + "/");

            for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
            {
                string formattedName = HttpContext.Current.Request.Files[i].FileName;
                IDictionary <string, object> properties = new Dictionary <string, object>();
                properties.Add(PropertyIds.Name, formattedName);
                properties.Add(PropertyIds.ObjectTypeId, "cmis:document");
                string        mime          = System.Web.MimeMapping.GetMimeMapping(formattedName);
                ContentStream contentStream = new ContentStream
                {
                    FileName = formattedName,
                    MimeType = mime,
                    Length   = 100,
                    Stream   = HttpContext.Current.Request.Files[i].InputStream
                };
                IDocument doc = folder.CreateDocument(properties, contentStream, null);
                // _fileRepository.SaveMeta(doc.VersionSeriesId);
                //  _fileRepository.Commit();
            }
        }
示例#32
0
        public void StoreDocument(
            CMISFolder folder,                  // where to put the document
            string document,                    // file name of the document
            string docName,                     // name of the new document
            Dictionary <string, object> props,  // document properties
            bool?major)                         // use versioning and which one
        {
            IContentStream contentStream = getContentStream(document, docName);

            try
            {
                IFolder         iFolder = folder.IFolder(session);
                VersioningState?vs      = null;
                if (major != null)
                {
                    vs = major == true? VersioningState.Major : VersioningState.Minor;
                }
                props[PropertyIds.Name] = docName;
                iFolder.CreateDocument(props, contentStream, vs);
                props.Remove(PropertyIds.Name);
            }
            catch (CmisBaseException e) { throw new Exception(e.Message + "\n" + e.ErrorContent); }
            finally { contentStream.Stream.Dispose(); }
        }
            /// <summary>
            /// Upload a single file to the CMIS server.
            /// </summary>
            private void UploadFile(string filePath, IFolder remoteFolder)
            {
                activityListener.ActivityStarted();
                IDocument remoteDocument = null;
                Boolean success = false;
                try
                {
                    Logger.Info("Uploading: " + filePath);

                    // Prepare properties
                    string fileName = Path.GetFileName(filePath);
                    Dictionary<string, object> properties = new Dictionary<string, object>();
                    properties.Add(PropertyIds.Name, fileName);
                    properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

                    // Prepare content stream
                    using (Stream file = File.OpenRead(filePath))
                    {
                        ContentStream contentStream = new ContentStream();
                        contentStream.FileName = fileName;
                        contentStream.MimeType = MimeType.GetMIMEType(fileName);
                        contentStream.Length = file.Length;
                        contentStream.Stream = file;

                        // Upload
                        try
                        {
                            remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null);
                            success = true;
                        }
                        catch (Exception ex)
                        {
                            Logger.Fatal("Upload failed: " + filePath + " " + ex);
                            if (contentStream != null) {
                                contentStream.Stream.Close();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e is FileNotFoundException ||
                        e is IOException)
                    {
                        Logger.Warn("File deleted while trying to upload it, reverting.");
                        // File has been deleted while we were trying to upload/checksum/add.
                        // This can typically happen in Windows Explore when creating a new text file and giving it a name.
                        // In this case, revert the upload.
                        if (remoteDocument != null)
                        {
                            remoteDocument.DeleteAllVersions();
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                    
                // Metadata.
                if (success)
                {
                    Logger.Info("Uploaded: " + filePath);

                    // Get metadata. Some metadata has probably been automatically added by the server.
                    Dictionary<string, string[]> metadata = FetchMetadata(remoteDocument);

                    // Create database entry for this file.
                    database.AddFile(filePath, remoteDocument.LastModificationDate, metadata);
                }

                activityListener.ActivityStopped();
            }
示例#34
0
        public IDocument CreateDocument(IFolder folder, string name, string content)
        {
            Dictionary<string, object> properties = new Dictionary<string, object>();
            properties.Add(PropertyIds.Name, name);
            properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

            ContentStream contentStream = new ContentStream();
            contentStream.FileName = name;
            contentStream.MimeType = MimeType.GetMIMEType(name);
            contentStream.Length = content.Length;
            contentStream.Stream = new MemoryStream(Encoding.UTF8.GetBytes(content));

            return folder.CreateDocument(properties, contentStream, null);
        }
示例#35
0
        /**
         * Upload a single file to the CMIS server.
         */
        private void UploadFile(string filePath, IFolder remoteFolder)
        {
            activityListener.ActivityStarted();
            IDocument remoteDocument = null;
            try
            {
                // Prepare properties
                string fileName = Path.GetFileName(filePath);
                Dictionary<string, object> properties = new Dictionary<string, object>();
                properties.Add(PropertyIds.Name, fileName);
                properties.Add(PropertyIds.ObjectTypeId, "cmis:document");

                // Prepare content stream
                ContentStream contentStream = new ContentStream();
                contentStream.FileName = fileName;
                contentStream.MimeType = MimeType.GetMIMEType(fileName); // Should CmisSync try to guess?
                contentStream.Stream = File.OpenRead(filePath);

                // Upload
                remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null);

                // Create database entry for this file.
                database.AddFile(filePath, remoteDocument.LastModificationDate, null);
            }
            catch (FileNotFoundException e)
            {
                SparkleLogger.LogInfo("Sync", "File deleted while trying to upload it, reverting.");
                // File has been deleted while we were trying to upload/checksum/add.
                // This can typically happen in Windows when creating a new text file and giving it a name.
                // Revert the upload.
                if (remoteDocument != null)
                {
                    remoteDocument.DeleteAllVersions();
                }
            }
            activityListener.ActivityStopped();
        }
示例#36
0
            /// <summary>
            /// Upload a single file to the CMIS server.
            /// </summary>
            private bool UploadFile(string filePath, IFolder remoteFolder) // TODO make SyncItem
            {
                SleepWhileSuspended();

                var syncItem = database.GetSyncItemFromLocalPath(filePath);
                if (null == syncItem)
                {
                    syncItem = SyncItemFactory.CreateFromLocalPath(filePath, repoinfo);
                }
                Logger.Info("Uploading: " + syncItem.LocalPath);

                try
                {
                    IDocument remoteDocument = null;
                    byte[] filehash = { };

                    // Prepare properties
                    string remoteFileName = syncItem.RemoteFileName;
                    Dictionary<string, object> properties = new Dictionary<string, object>();
                    properties.Add(PropertyIds.Name, remoteFileName);
                    properties.Add(PropertyIds.ObjectTypeId, "cmis:document");
                    properties.Add(PropertyIds.CreationDate, File.GetCreationTime(syncItem.LocalPath));
                    properties.Add(PropertyIds.LastModificationDate, File.GetLastWriteTime(syncItem.LocalPath));

                    // Prepare content stream
                    using (Stream file = File.Open(syncItem.LocalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (SHA1 hashAlg = new SHA1Managed())
                    using (CryptoStream hashstream = new CryptoStream(file, hashAlg, CryptoStreamMode.Read))
                    {
                        ContentStream contentStream = new ContentStream();
                        contentStream.FileName = remoteFileName;
                        contentStream.MimeType = MimeType.GetMIMEType(remoteFileName);
                        contentStream.Length = file.Length;
                        contentStream.Stream = hashstream;

                        Logger.Debug("Uploading: " + syncItem.LocalPath + " as "
                            + remoteFolder.Path + "/" + remoteFileName);
                        remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null);
                        Logger.Debug("Uploaded: " + syncItem.LocalPath);
                        filehash = hashAlg.Hash;
                    }

                    // Get metadata. Some metadata has probably been automatically added by the server.
                    Dictionary<string, string[]> metadata = FetchMetadata(remoteDocument);

                    // Create database entry for this file.
                    database.AddFile(syncItem, remoteDocument.Id, remoteDocument.LastModificationDate, metadata, filehash);
                    Logger.Info("Added file to database: " + syncItem.LocalPath);
                    return true;
                }
                catch (Exception e)
                {
                    ProcessRecoverableException("Could not upload file: " + syncItem.LocalPath, e);
                    return false;
                }
            }