当前位置: 首页>>代码示例>>C#>>正文


C# IDocument.GetContentStream方法代码示例

本文整理汇总了C#中IDocument.GetContentStream方法的典型用法代码示例。如果您正苦于以下问题:C# IDocument.GetContentStream方法的具体用法?C# IDocument.GetContentStream怎么用?C# IDocument.GetContentStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IDocument的用法示例。


在下文中一共展示了IDocument.GetContentStream方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DownloadFile

        /**
         * Download a single file from the CMIS server.
         */
        private void DownloadFile(IDocument remoteDocument, string localFolder)
        {
            activityListener.ActivityStarted();
            DotCMIS.Data.IContentStream contentStream = remoteDocument.GetContentStream();

            // If this file does not have a content stream, ignore it.
            // Even 0 bytes files have a contentStream.
            // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
            if (contentStream == null)
            {
                SparkleLogger.LogInfo("Sync", "Skipping download of file with null content stream: " + remoteDocument.ContentStreamFileName);
                return;
            }

            // Download.
            string filePath = localFolder + Path.DirectorySeparatorChar + contentStream.FileName;

            // If there was previously a directory with this name, delete it.
            // TODO warn if local changes inside the folder.
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath);
            }

            bool success = false;
            do
            {
                try
                {
                    DownloadFile(contentStream, filePath);
                    success = true;
                }
                catch (WebException e)
                {
                    SparkleLogger.LogInfo("Sync", e.Message);
                    SparkleLogger.LogInfo("Sync", "Problem during download, waiting for 10 seconds...");
                    System.Threading.Thread.Sleep(10 * 1000);
                }
            }
            while (!success);

            // Get metadata.
            Dictionary<string, string> metadata = new Dictionary<string, string>();
            metadata.Add("Id", remoteDocument.Id);
            metadata.Add("VersionSeriesId", remoteDocument.VersionSeriesId);
            metadata.Add("VersionLabel", remoteDocument.VersionLabel);
            metadata.Add("CreationDate", remoteDocument.CreationDate.ToString());
            metadata.Add("CreatedBy", remoteDocument.CreatedBy);
            metadata.Add("lastModifiedBy", remoteDocument.LastModifiedBy);
            metadata.Add("CheckinComment", remoteDocument.CheckinComment);
            metadata.Add("IsImmutable", (bool)(remoteDocument.IsImmutable) ? "true" : "false");
            metadata.Add("ContentStreamMimeType", remoteDocument.ContentStreamMimeType);

            // Create database entry for this file.
            database.AddFile(filePath, remoteDocument.LastModificationDate, metadata);
            activityListener.ActivityStopped();
        }
开发者ID:smcardle,项目名称:CmisSync,代码行数:60,代码来源:CmisDirectory.cs

示例2: UpdateFile

            /// <summary>
            /// Upload new version of file.
            /// </summary>
            private bool UpdateFile(string filePath, IDocument remoteFile)
            {
                SleepWhileSuspended();
                try
                {
                    var syncItem = database.GetSyncItemFromLocalPath(filePath);
                    if (null == syncItem)
                    {
                        syncItem = SyncItemFactory.CreateFromLocalPath(filePath, repoinfo);
                    }

                    Logger.Info("Updating: " + syncItem.LocalPath);
                    using (Stream localfile = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        // Ignore files with null or empty content stream.
                        if ((localfile == null) && (localfile.Length == 0))
                        {
                            Logger.Info("Skipping update of file with null or empty content stream: " + filePath);
                            return true;
                        }

                        // Check is write permission is allow

                        // Check if the file is Check out or not
                        //if (!(bool)remoteFile.IsVersionSeriesCheckedOut)
                        if ((remoteFile.IsVersionSeriesCheckedOut == null) || !(bool)remoteFile.IsVersionSeriesCheckedOut)
                        {

                            // Prepare content stream
                            ContentStream remoteStream = new ContentStream();
                            remoteStream.FileName = remoteFile.ContentStreamFileName;
                            remoteStream.Length = localfile.Length;
                            remoteStream.MimeType = remoteFile.GetContentStream().MimeType;
                            remoteStream.Stream = localfile;
                            remoteStream.Stream.Flush();
                            Logger.Debug("before SetContentStream");

                            // CMIS do not have a Method to upload block by block. So upload file must be full.
                            // We must waiting for support of CMIS 1.1 https://issues.apache.org/jira/browse/CMIS-628
                            // http://docs.oasis-open.org/cmis/CMIS/v1.1/cs01/CMIS-v1.1-cs01.html#x1-29700019
                            // DotCMIS.Client.IObjectId objID = remoteFile.SetContentStream(remoteStream, true, true);
                            remoteFile.SetContentStream(remoteStream, true, true);

                            Logger.Debug("after SetContentStream");

                            // Update timestamp in database.
                            database.SetFileServerSideModificationDate(syncItem, ((DateTime)remoteFile.LastModificationDate).ToUniversalTime());

                            // Update checksum
                            database.RecalculateChecksum(syncItem);

                            // TODO Update metadata?
                            Logger.Info("Updated: " + syncItem.LocalPath);
                            return true;
                        }
                        else
                        {
                            string message = String.Format("File {0} is CheckOut on the server by another user: {1}", syncItem.LocalPath, remoteFile.CheckinComment);

                            // throw new IOException("File is Check Out on the server");
                            Logger.Info(message);
                            Utils.NotifyUser(message);
                            return false;
                        }
                    }
                }
                catch (Exception e)
                {
                    ProcessRecoverableException("Could not update file: " + filePath, e);
                    return false;
                }
            }
开发者ID:jelacote,项目名称:CmisSync,代码行数:75,代码来源:SynchronizedFolder.cs

示例3: DownloadFile

        /// <summary>
        /// Downloads the file and returns the SHA-1 hash of the content of the saved file
        /// </summary>
        /// <param name="remoteDocument">Remote document.</param>
        /// <param name="localFileStream">Local taget file stream.</param>
        /// <param name="transmission">Transmission status.</param>
        /// <param name="hashAlg">Hash algoritm, which should be used to calculate hash of the uploaded stream content</param>
        /// <exception cref="IOException">On any disc or network io exception</exception>
        /// <exception cref="DisposeException">If the remote object has been disposed before the dowload is finished</exception>
        /// <exception cref="AbortException">If download is aborted</exception>
        /// <exception cref="CmisException">On exceptions thrown by the CMIS Server/Client</exception>
        public void DownloadFile(
            IDocument remoteDocument,
            Stream localFileStream,
            Transmission transmission,
            HashAlgorithm hashAlg,
            UpdateChecksum update = null)
        {
            byte[] buffer = new byte[8 * 1024];
            int len;

            if (localFileStream.Length > 0) {
                localFileStream.Seek(0, SeekOrigin.Begin);
                while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) {
                    hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                }
            }

            long offset = localFileStream.Position;
            long? fileLength = remoteDocument.ContentStreamLength;
            if (fileLength <= offset) {
                transmission.Length = fileLength.GetValueOrDefault();
                transmission.Position = offset;
                hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                return;
            }

            DotCMIS.Data.IContentStream contentStream = null;
            if (offset > 0) {
                long remainingBytes = (long)fileLength - offset;
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;
                contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
            } else {
                contentStream = remoteDocument.GetContentStream();
            }

            using (var transmissionStream = transmission.CreateStream(localFileStream))
            using (CryptoStream hashstream = new CryptoStream(transmissionStream, hashAlg, CryptoStreamMode.Write))
            using (Stream remoteStream = contentStream != null ? contentStream.Stream : new MemoryStream(0)) {
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;
                int written = 0;
                while ((len = remoteStream.Read(buffer, 0, buffer.Length)) > 0) {
                    lock (this.disposeLock) {
                        if (this.disposed) {
                            transmission.Status = TransmissionStatus.ABORTED;
                            throw new ObjectDisposedException(transmission.Path);
                        }

                        try {
                            hashstream.Write(buffer, 0, len);
                            hashstream.Flush();
                            written += len;
                        } catch (Exception) {
                            this.UpdateHash(hashAlg, localFileStream.Length, update);
                            throw;
                        }

                        if (written >= 1024 * 1024) {
                            this.UpdateHash(hashAlg, localFileStream.Length, update);
                            written = 0;
                        }
                    }
                }

                if (written > 0) {
                    this.UpdateHash(hashAlg, localFileStream.Length, update);
                }
            }
        }
开发者ID:OpenDataSpace,项目名称:CmisSync,代码行数:81,代码来源:SimpleFileDownloader.cs

示例4: DownloadFile

            /// <summary>
            /// Download a single file from the CMIS server.
            /// </summary>
            private bool DownloadFile(IDocument remoteDocument, string localFolder)
            {
                SleepWhileSuspended();

                string fileName = remoteDocument.ContentStreamFileName;
                Logger.Info("Downloading: " + fileName);

                // Skip if invalid file name. See https://github.com/nicolas-raoul/CmisSync/issues/196
                if (Utils.IsInvalidFileName(fileName))
                {
                    Logger.Info("Skipping download of file with illegal filename: " + fileName);
                    return true;
                }

                try
                {
                    DotCMIS.Data.IContentStream contentStream = null;
                    string filepath = Path.Combine(localFolder, fileName);
                    string tmpfilepath = filepath + ".sync";
                    if(database.GetOperationRetryCounter(filepath,Database.OperationType.DOWNLOAD) > repoinfo.MaxDownloadRetries)
                    {
                        Logger.Info(String.Format("Skipping download of file {0} because of too many failed ({1}) downloads",database.GetOperationRetryCounter(filepath,Database.OperationType.DOWNLOAD)));
                        return true;
                    }

                    // If there was previously a directory with this name, delete it.
                    // TODO warn if local changes inside the folder.
                    if (Directory.Exists(filepath))
                    {
                        Directory.Delete(filepath);
                    }

                    if (File.Exists(tmpfilepath))
                    {
                        DateTime? remoteDate = remoteDocument.LastModificationDate;
                        if (null == remoteDate)
                        {
                            File.Delete(tmpfilepath);
                        }
                        else
                        {
                            remoteDate = ((DateTime)remoteDate).ToUniversalTime();
                            DateTime? serverDate = database.GetDownloadServerSideModificationDate(filepath);
                            if (remoteDate != serverDate)
                            {
                                File.Delete(tmpfilepath);
                            }
                        }
                    }

                    // Download file.
                    Boolean success = false;
                    byte[] filehash = { };
                    try
                    {
                        contentStream = remoteDocument.GetContentStream();

                        // If this file does not have a content stream, ignore it.
                        // Even 0 bytes files have a contentStream.
                        // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
                        if (contentStream == null)
                        {
                            Logger.Warn("Skipping download of file with null content stream: " + fileName);
                            return true;
                        }
                        // Skip downloading the content, just go on with an empty file
                        if (remoteDocument.ContentStreamLength == 0)
                        {
                            Logger.Info("Skipping download of file with content length zero: " + fileName);
                            using (FileStream s = File.Create(tmpfilepath))
                            {
                                s.Close();
                            }
                        }
                        else
                        {
                            filehash = DownloadStream(contentStream, tmpfilepath);
                            contentStream.Stream.Close();
                        }
                        success = true;
                    }
                    catch (CmisBaseException e)
                    {
                        ProcessRecoverableException("Download failed: " + fileName, e);
                        if (contentStream != null) contentStream.Stream.Close();
                        success = false;
                        File.Delete(tmpfilepath);
                    }

                    if (success)
                    {
                        Logger.Info(String.Format("Downloaded remote object({0}): {1}", remoteDocument.Id, fileName));

                        // TODO Control file integrity by using hash compare?

                        // Get metadata.
                        Dictionary<string, string[]> metadata = null;
//.........这里部分代码省略.........
开发者ID:pcreignou,项目名称:CmisSync,代码行数:101,代码来源:SynchronizedFolder.cs

示例5: DownloadFile

            /// <summary>
            /// Download a single file from the CMIS server.
            /// 
            /// Algorithm:
            /// 
            /// Skip if invalid filename
            /// If directory exists with same name, delete it
            /// If temporary file already exists but database has a different modification date than server, delete it
            /// Download data and metadata, return if that fails
            /// If a file with this name already exists locally
            ///   If conflict
            ///     Rename the existing file and put the server fils instead
            ///     Notify the user
            ///   If file update
            ///     Replace the file
            /// Else (new file)
            ///   Save
            /// Set creation date and last modification date if available
            /// Make read-only if remote can not be modified
            /// Create CmisSync database entry for this file
            /// 
            /// </summary>
            private bool DownloadFile(IDocument remoteDocument, string localFolder)
            {
                SleepWhileSuspended();

                var syncItem = database.GetSyncItemFromRemotePath(remoteDocument.Paths[0]);
                if (null == syncItem)
                {
                    syncItem = SyncItemFactory.CreateFromRemotePath(remoteDocument.Paths[0], repoinfo);
                }

                Logger.Info("Downloading: " + syncItem.RemoteFileName);

                // Skip if invalid file name. See https://github.com/aegif/CmisSync/issues/196
                if (Utils.IsInvalidFileName(syncItem.LocalFileName)) 
                {
                    Logger.Info("Skipping download of file with illegal filename: " + syncItem.LocalFileName);
                    return true;
                }

                try
                {
                    DotCMIS.Data.IContentStream contentStream = null;
                    string filepath = syncItem.LocalPath;
                    string tmpfilepath = filepath + ".sync";
                    if (database.GetOperationRetryCounter(filepath, Database.Database.OperationType.DOWNLOAD) > repoinfo.MaxDownloadRetries)
                    {
                        Logger.Info(String.Format("Skipping download of file {0} because of too many failed ({1}) downloads", database.GetOperationRetryCounter(filepath, Database.Database.OperationType.DOWNLOAD)));
                        return true;
                    }

                    // If there was previously a directory with this name, delete it.
                    // TODO warn if local changes inside the folder.
                    if (Directory.Exists(filepath))
                    {
                        Directory.Delete(filepath);
                    }

                    if (File.Exists(tmpfilepath))
                    {
                        DateTime? remoteDate = remoteDocument.LastModificationDate;
                        if (null == remoteDate)
                        {
                            File.Delete(tmpfilepath);
                        }
                        else
                        {
                            remoteDate = ((DateTime)remoteDate).ToUniversalTime();
                            DateTime? serverDate = database.GetDownloadServerSideModificationDate(syncItem);
                            if (remoteDate != serverDate)
                            {
                                File.Delete(tmpfilepath);
                            }
                        }
                    }

                    // Download file.
                    Boolean success = false;
                    byte[] filehash = { };
                    try
                    {
                        contentStream = remoteDocument.GetContentStream();

                        // If this file does not have a content stream, ignore it.
                        // Even 0 bytes files have a contentStream.
                        // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
                        if (contentStream == null)
                        {
                            Logger.Warn("Skipping download of file with null content stream: " + syncItem.RemoteFileName);
                            return true;
                        }
                        // Skip downloading the content, just go on with an empty file
                        if (remoteDocument.ContentStreamLength == 0)
                        {
                            Logger.Info("Skipping download of file with content length zero: " + syncItem.RemoteFileName);
                            using (FileStream s = File.Create(tmpfilepath))
                            {
                                s.Close();
                            }
//.........这里部分代码省略.........
开发者ID:jelacote,项目名称:CmisSync,代码行数:101,代码来源:SynchronizedFolder.cs

示例6: DownloadFile

        /**
         * Download a single file from the CMIS server.
         */
        private void DownloadFile(IDocument remoteDocument, string localFolder)
        {
            activityListener.ActivityStarted();
            DotCMIS.Data.IContentStream contentStream = remoteDocument.GetContentStream();

            // If this file does not have a content stream, ignore it.
            // Even 0 bytes files have a contentStream.
            // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
            if (contentStream == null)
            {
                SparkleLogger.LogInfo("Sync", "Skipping download of file with null content stream: " + remoteDocument.ContentStreamFileName);
                return;
            }

            // Download.
            string filePath = localFolder + Path.DirectorySeparatorChar + contentStream.FileName;

            // If there was previously a directory with this name, delete it.
            // TODO warn if local changes inside the folder.
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath);
            }

            SparkleLogger.LogInfo("Sync", "Downloading " + filePath);
            Stream file = File.OpenWrite(filePath);
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = contentStream.Stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                file.Write(buffer, 0, len);
            }
            file.Close();
            contentStream.Stream.Close();
            SparkleLogger.LogInfo("Sync", "Downloaded");

            // Get metadata.
            string lastModifiedBy = remoteDocument.LastModifiedBy;
            // Write metadata.
            // TODO

            // Create database entry for this file.
            database.AddFile(filePath, remoteDocument.LastModificationDate);
            activityListener.ActivityStopped();
        }
开发者ID:phamtuanchip,项目名称:CmisSync,代码行数:48,代码来源:Cmis.cs

示例7: DownloadNextChunk

        private int DownloadNextChunk(IDocument remoteDocument, long offset, long remainingBytes, Transmission transmission, Stream outputstream, HashAlgorithm hashAlg) {
            lock(this.disposeLock) {
                if (this.disposed) {
                    transmission.Status = TransmissionStatus.ABORTED;
                    throw new ObjectDisposedException(transmission.Path);
                }

                IContentStream contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;

                using (var remoteStream = contentStream.Stream)
                using (var forwardstream = new ForwardReadingStream(remoteStream))
                using (var offsetstream = new OffsetStream(forwardstream, offset))
                using (var progress = transmission.CreateStream(offsetstream)) {
                    byte[] buffer = new byte[8 * 1024];
                    int result = 0;
                    int len;
                    while ((len = progress.Read(buffer, 0, buffer.Length)) > 0) {
                        outputstream.Write(buffer, 0, len);
                        hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                        result += len;
                        outputstream.Flush();
                    }

                    return result;
                }
            }
        }
开发者ID:OpenDataSpace,项目名称:CmisSync,代码行数:29,代码来源:ChunkedDownloader.cs

示例8: DownloadFile

            /// <summary>
            /// Download a single file from the CMIS server.
            /// </summary>
            private bool DownloadFile(IDocument remoteDocument, string localFolder)
            {
                sleepWhileSuspended();

                string fileName = remoteDocument.ContentStreamFileName;
                Logger.Info("Downloading: " + fileName);

                // Skip if invalid file name. See https://github.com/nicolas-raoul/CmisSync/issues/196
                if (Utils.IsInvalidFileName(fileName))
                {
                    Logger.Info("Skipping download of file with illegal filename: " + fileName);
                    return true;
                }

                try
                {
                    DotCMIS.Data.IContentStream contentStream = null;
                    string filepath = Path.Combine(localFolder, fileName);
                    string tmpfilepath = filepath + ".sync";

                    // If there was previously a directory with this name, delete it.
                    // TODO warn if local changes inside the folder.
                    if (Directory.Exists(filepath))
                    {
                        Directory.Delete(filepath);
                    }

                    // If file exists, delete it.
                    File.Delete(filepath);
                    File.Delete(tmpfilepath);

                    // Download file.
                    Boolean success = false;
                    byte[] filehash = { };
                    try
                    {
                        contentStream = remoteDocument.GetContentStream();

                        // If this file does not have a content stream, ignore it.
                        // Even 0 bytes files have a contentStream.
                        // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
                        if (contentStream == null)
                        {
                            Logger.Warn("Skipping download of file with null content stream: " + fileName);
                            return true;
                        }
                        // Skip downloading the content, just go on with an empty file
                        if (remoteDocument.ContentStreamLength == 0)
                        {
                            Logger.Info("Skipping download of file with content length zero: " + fileName);
                            using (FileStream s = File.Create(tmpfilepath))
                            {
                                s.Close();
                            }
                        }
                        else
                        {
                            filehash = DownloadStream(contentStream, tmpfilepath);
                            contentStream.Stream.Close();
                        }
                        success = true;
                    }
                    catch (CmisBaseException e)
                    {
                        ProcessRecoverableException("Download failed: " + fileName, e);
                        if (contentStream != null) contentStream.Stream.Close();
                        success = false;
                        File.Delete(tmpfilepath);
                    }

                    if (success)
                    {
                        Logger.Info("Downloaded: " + fileName);
                        // TODO Control file integrity by using hash compare?

                        // Get metadata.
                        Dictionary<string, string[]> metadata = null;
                        try
                        {
                            metadata = FetchMetadata(remoteDocument);
                        }
                        catch (CmisBaseException e)
                        {
                            ProcessRecoverableException("Could not fetch metadata: " + fileName, e);
                            // Remove temporary local document to avoid it being considered a new document.
                            File.Delete(tmpfilepath);
                            return false;
                        }

                        // Remove the ".sync" suffix.
                        File.Move(tmpfilepath, filepath);

                        if (null != remoteDocument.CreationDate)
                        {
                            File.SetCreationTime(filepath, (DateTime)remoteDocument.CreationDate);
                        }
                        if (null != remoteDocument.LastModificationDate)
//.........这里部分代码省略.........
开发者ID:keithwharrison,项目名称:Oris4Sync,代码行数:101,代码来源:SynchronizedFolder.cs

示例9: DownloadFile

        private void DownloadFile(IDocument remoteDocument, string localFolder)
        {
            DotCMIS.Data.IContentStream contentStream = remoteDocument.GetContentStream();

            // If this file does not have a content stream, ignore it.
            // Even 0 bytes files have a contentStream.
            // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
            if (contentStream == null)
            {
                SparkleLogger.LogInfo("Sync", "Skipping download of file with null content stream: " + remoteDocument.ContentStreamFileName);
                return;
            }

            // Download.
            string filePath = localFolder + Path.DirectorySeparatorChar + contentStream.FileName;

            // If there was previously a directory with this name, delete it.
            // TODO warn if local changes inside the folder.
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath);
            }

            SparkleLogger.LogInfo("Sync", /*id +*/ "Downloading " + filePath);
            Stream file = File.OpenWrite(filePath);
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = contentStream.Stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                file.Write(buffer, 0, len);
            }
            file.Close();
            contentStream.Stream.Close();
            SparkleLogger.LogInfo("Sync", "Downloaded");

            // Create database entry for this file.
            DateTime? serverSideModificationDate = remoteDocument.LastModificationDate;
            try
            {
                SQLiteCommand command = new SQLiteCommand(sqliteConnection);
                command.CommandText =
                    "INSERT OR REPLACE INTO files (path, serverSideModificationDate)"
                    + " VALUES (@filePath, @serverSideModificationDate)";
                command.Parameters.AddWithValue("filePath", filePath);
                command.Parameters.AddWithValue("serverSideModificationDate", serverSideModificationDate);
                command.ExecuteReader();
            }
            catch (SQLiteException e)
            {
                SparkleLogger.LogInfo("Sync", e.Message);
            }
        }
开发者ID:vfh,项目名称:CmisSync,代码行数:52,代码来源:Cmis.cs

示例10: DownloadFile

        /// <summary>
        /// Download a single file from the CMIS server.
        /// 
        /// Algorithm:
        /// 
        /// Skip if invalid filename
        /// If directory exists with same name, delete it
        /// If temporary file already exists but database has a different modification date than server, delete it
        /// Download data and metadata, return if that fails
        /// If a file with this name already exists locally
        ///   If conflict
        ///     Rename the existing file and put the server fils instead
        ///     Notify the user
        ///   If file update
        ///     Replace the file
        /// Else (new file)
        ///   Save
        /// Set creation date and last modification date if available
        /// Make read-only if remote can not be modified
        /// Create CmisSync database entry for this file
        /// 
        /// </summary>
        private bool DownloadFile(IDocument remoteDocument, string localFolder)
        {
            CheckPendingCancelation();

            SyncItem syncItem = getSyncItemFromRemotePath(remoteDocument.Paths[0]);
            Logger.Info("Downloading: " + syncItem.RemoteFileName);

            // Skip if invalid file name. See https://github.com/aegif/CmisSync/issues/196
            if (SyncUtils.IsInvalidFileName(syncItem.LocalFileName))
            {
                Logger.Info("Skipping download of file with illegal filename: " + syncItem.LocalFileName);
                return true;
            }

            string filepath = syncItem.LocalPath;
            string tmpfilepath = filepath + ".sync";
            if (database.GetOperationRetryCounter(filepath, Database.Database.OperationType.DOWNLOAD) > SyncFolderInfo.MaxDownloadRetries)
            {
                Logger.Info(String.Format("Skipping download of file {0} because of too many failed ({1}) downloads", database.GetOperationRetryCounter(filepath, Database.Database.OperationType.DOWNLOAD)));
                return true;
            }

            try
            {
                // If there was previously a directory with this name
                if (Directory.Exists(filepath))
                {
                    HandleException(new DirectoryCollisionFileException(filepath));
                    return false;
                }

                if (File.Exists(tmpfilepath))
                {
                    Logger.Warn("found an existing .sync file wile downloading a new file. Probabli it's a previously failed syncronization leftover: deleting it");
                    //TODO: make sure it is not a user file
                    File.Delete(tmpfilepath);
                }

                // Download file.
                DotCMIS.Data.IContentStream contentStream = null;
                byte[] filehash = { };
                try
                {
                    contentStream = remoteDocument.GetContentStream();

                    // If this file does not have a content stream, ignore it.
                    // Even 0 bytes files have a contentStream.
                    // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
                    if (contentStream == null)
                    {
                        Logger.Warn("Skipping download of file with null content stream: " + syncItem.RemoteFileName);
                        return true;
                    }
                    // Skip downloading the content, just go on with an empty file
                    if (remoteDocument.ContentStreamLength == 0)
                    {
                        Logger.Info("Skipping download of file with content length zero: " + syncItem.RemoteFileName);
                        using (FileStream s = File.Create(tmpfilepath))
                        {
                            s.Close();
                        }
                    }
                    else
                    {
                        filehash = DownloadStream(contentStream, tmpfilepath);
                    }
                }
                catch (CmisBaseException e)
                {
                    try
                    {
                        HandleException(new DownloadFileException(syncItem.RemoteFileName, e));
                    }
                    finally
                    {
                        File.Delete(tmpfilepath);
                        if (contentStream != null) contentStream.Stream.Close();
                    }
//.........这里部分代码省略.........
开发者ID:lelmarir,项目名称:CmisSync,代码行数:101,代码来源:SyncFolderSyncronizer.cs

示例11: UpdateFile

        /// <summary>
        /// Upload new version of file.
        /// </summary>
        private bool UpdateFile(string filePath, ref IDocument remoteFile)
        {
            CheckPendingCancelation();
            try
            {
                SyncItem syncItem = getSyncItemFromLocalPath(filePath);

                Logger.Info("Updating: " + syncItem.LocalPath);
                using (Stream localfile = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    // Ignore files with null or empty content stream.
                    if ((localfile == null) && (localfile.Length == 0))
                    {
                        Logger.Info("Skipping update of file with null or empty content stream: " + filePath);
                        return true;
                    }

                    // Check is write permission is allow

                    // Check if the file is Check out or not
                    //if (!(bool)remoteFile.IsVersionSeriesCheckedOut)
                    if ((remoteFile.IsVersionSeriesCheckedOut == null) || !(bool)remoteFile.IsVersionSeriesCheckedOut)
                    {

                        // Prepare content stream
                        ContentStream remoteStream = new ContentStream();
                        remoteStream.FileName = remoteFile.ContentStreamFileName;
                        remoteStream.Length = localfile.Length;
                        remoteStream.MimeType = remoteFile.GetContentStream().MimeType;
                        remoteStream.Stream = localfile;
                        remoteStream.Stream.Flush();
                        Logger.Debug("before SetContentStream");

                        // CMIS do not have a Method to upload block by block. So upload file must be full.
                        // We must waiting for support of CMIS 1.1 https://issues.apache.org/jira/browse/CMIS-628
                        // http://docs.oasis-open.org/cmis/CMIS/v1.1/cs01/CMIS-v1.1-cs01.html#x1-29700019
                        // DotCMIS.Client.IObjectId objID = remoteFile.SetContentStream(remoteStream, true, true);
                        remoteFile.SetContentStream(remoteStream, true, true);

                        Logger.Debug("after SetContentStream");

                        // Update timestamp in database.
                        //remoteFile still refer to the old version of the file, and the LastModificationDate is not the right one:
                        //load the new version data
                        remoteFile = getSession().GetLatestDocumentVersion(remoteFile.Id);
                        database.SetFileServerSideModificationDate(syncItem, ((DateTime)remoteFile.LastModificationDate).ToUniversalTime());

                        // Update checksum
                        database.RecalculateChecksum(syncItem);

                        // TODO Update metadata?
                        Logger.Info("Updated: " + syncItem.LocalPath);
                        return true;
                    }
                    else
                    {
                        HandleException(new CheckOutFileException(syncItem.LocalPath, remoteFile.CheckinComment));
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                HandleException(new UploadFileException(filePath, e));
                return false;
            }
        }
开发者ID:lelmarir,项目名称:CmisSync,代码行数:70,代码来源:SyncFolderSyncronizer.cs

示例12: DownloadFile

            /// <summary>
            /// Download a single file from the CMIS server.
            /// </summary>
            private void DownloadFile(IDocument remoteDocument, string localFolder)
            {
                activityListener.ActivityStarted();

                string fileName = remoteDocument.ContentStreamFileName;
                Logger.Info("Downloading: " + fileName);

                // TODO: Make this configurable.
                if (remoteDocument.ContentStreamLength == 0)
                {
                    Logger.Info("Skipping download of file with content length zero: " + fileName);
                    activityListener.ActivityStopped();
                    return;
                }

                // Skip if invalid file name. See https://github.com/nicolas-raoul/CmisSync/issues/196
                if (Utils.IsInvalidFileName(fileName))
                {
                    Logger.Info("Skipping download of file with illegal filename: " + fileName);
                    activityListener.ActivityStopped();
                    return;
                }

                try
                {
                    DotCMIS.Data.IContentStream contentStream = null;
                    string filepath = Path.Combine(localFolder, fileName);
                    string tmpfilepath = filepath + ".sync";

                    // If there was previously a directory with this name, delete it.
                    // TODO warn if local changes inside the folder.
                    if (Directory.Exists(filepath))
                    {
                        Directory.Delete(filepath);
                    }

                    // If file exists, delete it.
                    File.Delete(filepath);
                    File.Delete(tmpfilepath);

                    // Download file.
                    Boolean success = false;
                    try
                    {
                        contentStream = remoteDocument.GetContentStream();

                        // If this file does not have a content stream, ignore it.
                        // Even 0 bytes files have a contentStream.
                        // null contentStream sometimes happen on IBM P8 CMIS server, not sure why.
                        if (contentStream == null)
                        {
                            Logger.Warn("Skipping download of file with null content stream: " + fileName);
                            activityListener.ActivityStopped();
                            return;
                        }

                        DownloadStream(contentStream, tmpfilepath);

                        contentStream.Stream.Close();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Download failed: " + fileName + " " + ex);
                        if (contentStream != null) contentStream.Stream.Close();
                        success = false;
                        File.Delete(tmpfilepath);
                    }

                    if (success)
                    {
                        Logger.Info("Downloaded: " + fileName);
                        // TODO Control file integrity by using hash compare?

                        // Get metadata.
                        Dictionary<string, string[]> metadata = null;
                        try
                        {
                            metadata = FetchMetadata(remoteDocument);
                        }
                        catch (Exception e)
                        {
                            Logger.Info("Exception while fetching metadata: " + fileName + " " + Utils.ToLogString(e));
                            // Remove temporary local document to avoid it being considered a new document.
                            File.Delete(tmpfilepath);
                            activityListener.ActivityStopped();
                            return;
                        }

                        // Remove the ".sync" suffix.
                        File.Move(tmpfilepath, filepath);

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

                        Logger.Info("Added to database: " + fileName);
                    }
//.........这里部分代码省略.........
开发者ID:jmanuelnavarro,项目名称:CmisSync,代码行数:101,代码来源:SynchronizedFolder.cs


注:本文中的IDocument.GetContentStream方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。