Пример #1
0
        private void CopyFile()
        {
            FileSystemAwareFileUtilities fileUtils = new FileSystemAwareFileUtilities(new DeviceManager(), new StreamHelper(), new FileSystemAwareFileInfoProvider(new DeviceManager()));

            if (!fileUtils.FileExists(GetSourcePath()))
            {
                DisplayMessage(string.Format("Cannot find source file {0}", GetSourcePath()), DisplayLevel.Error);
            }

            if (fileUtils.FileExists(GetDestinationPath()))
            {
                fileUtils.FileDelete(GetDestinationPath());
            }

            // put this section in the test preable
            string folder = GetRootFolder();
            FileSystemAwareDirectoryInfoProvider dirInfoProvider = new FileSystemAwareDirectoryInfoProvider(new DeviceManager());
            IDirectoryInfo info = dirInfoProvider.GetDirectoryInfo(folder);

            info.Create();

            fileUtils.FileCopy(GetSourcePath(), GetDestinationPath());

            if (fileUtils.FileExists(GetDestinationPath()))
            {
                DisplayMessage(string.Format("File copied to {0} OK", GetDestinationPath()));
            }
            else
            {
                DisplayMessage(string.Format("Cannot find destination file {0}", GetDestinationPath()), DisplayLevel.Error);
            }
        }
Пример #2
0
 public void SetUp()
 {
     _directoryInfo = _fileSystem.DirectoryInfo.FromDirectoryName(FolderPath);
     _directoryInfo.Create();
     _sourceFileInfo     = _fileSystem.FileInfo.FromFileName(GetPlatformSourcePath());
     _targetFileInfo     = _fileSystem.FileInfo.FromFileName(GetPlatformTargetPath());
     using Stream stream = _sourceFileInfo.Create();
 }
Пример #3
0
        public bool TryToCreateDirectory(IDirectoryInfo directory)
        {
            if (directory.Exists)
                return false;

            directory.Create();
            return true;
        }
Пример #4
0
 public PostThumbnailService(IFileSystem fileSystem)
 {
     _thumbnailDirectory = fileSystem.GetDirectory("post-thumbs");
     if (!_thumbnailDirectory.Exists)
     {
         _thumbnailDirectory.Create();
     }
 }
Пример #5
0
        public AvatarService(IPathResolver pathResolver, IFileSystem fileSystemProvider)
        {
            _pathResolver = pathResolver;
            _fileSystemProvider = fileSystemProvider;

            _avatarDirectoryInfo = _fileSystemProvider.GetDirectory("avatars");
            if (!_avatarDirectoryInfo.Exists)
                _avatarDirectoryInfo.Create();
        }
Пример #6
0
        private void CreateFolderIfNeeded(string folder)
        {
            IDirectoryInfo dir = _directoryInfoProvider.GetDirectoryInfo(folder);

            if (!dir.Exists)
            {
                dir.Create();
            }
        }
Пример #7
0
        public void Create()
        {
            string         fileName = "test1";
            string         fullPath = Path.Combine(this.testFolder.FullName, fileName);
            IDirectoryInfo dirInfo  = Factory.CreateDirectoryInfo(fullPath);

            dirInfo.Create();
            Assert.That(dirInfo.Exists, Is.EqualTo(true));
        }
Пример #8
0
        public bool TryToCreateDirectory(IDirectoryInfo directory)
        {
            if (directory.Exists)
            {
                return(false);
            }

            directory.Create();
            return(true);
        }
Пример #9
0
        public AvatarService(IPathResolver pathResolver, IFileSystem fileSystemProvider)
        {
            _pathResolver       = pathResolver;
            _fileSystemProvider = fileSystemProvider;

            _avatarDirectoryInfo = _fileSystemProvider.GetDirectory("avatars");
            if (!_avatarDirectoryInfo.Exists)
            {
                _avatarDirectoryInfo.Create();
            }
        }
Пример #10
0
        public static IDirectoryInfo CreateItemFolderWithSingleFile(IFileSystem fileSystem, string steamUploadPath)
        {
            IDirectoryInfo itemFolder = fileSystem.DirectoryInfo.FromDirectoryName(steamUploadPath);

            itemFolder.Create();
            itemFolder.CreateSubdirectory("sub_dir");
            using StreamWriter streamWriter = fileSystem.File.CreateText(steamUploadPath + "/sub_dir/file.txt");
            streamWriter.Write("My awesome content!");
            streamWriter.Close();

            return(itemFolder);
        }
Пример #11
0
        public void DeleteTrue()
        {
            string         fileName = "test1";
            string         fullPath = Path.Combine(this.testFolder.FullName, fileName);
            IDirectoryInfo dirInfo  = Factory.CreateDirectoryInfo(fullPath);

            dirInfo.Create();
            Assert.That(dirInfo.Exists, Is.True);
            dirInfo.Delete(true);
            dirInfo.Refresh();
            Assert.That(dirInfo.Exists, Is.False);
        }
Пример #12
0
        public MigrationModel(IProject project)
            : base(project)
        {
            Guard.ArgumentNotNull(project, "project");

            _reportInfo = new ModelItemInfo(this, typeof (MigrationReport));
            _modelRoot = Project.Drive.GetDirectoryInfo(ModelRootPath);

            if (!_modelRoot.Exists)
            {
                _modelRoot.Create();
            }
        }
        private void CreateFolderIfNeeded()
        {
            string         folder = Path.GetDirectoryName(_syncItem.DestinationPath);
            IDirectoryInfo dir    = _directoryInfoProvider.GetDirectoryInfo(folder);

            if (!dir.Exists)
            {
                dir.Create();
            }
            if (_fileUtilities.FileExists(_syncItem.DestinationPath))
            {
                _fileUtilities.FileDelete(_syncItem.DestinationPath);
            }
        }
Пример #14
0
        private void When_creating_directory_it_must_succeed()
        {
            // Arrange
            const string path = @"d:\some\folder\nested";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                                     .IncludingDirectory(@"d:\")
                                     .Build();

            IDirectoryInfo dirInfo = fileSystem.ConstructDirectoryInfo(path);

            // Act
            dirInfo.Create();

            // Assert
            fileSystem.Directory.Exists(path).Should().BeTrue();
        }
Пример #15
0
        public void ProcessMessage(
            [NotNull] ExtractFileMessage message,
            [NotNull] IMessageHeader header)
        {
            string fullSrc = _fileSystem.Path.Combine(_fileSystemRoot, message.DicomFilePath);

            ExtractedFileStatusMessage statusMessage;

            if (!_fileSystem.File.Exists(fullSrc))
            {
                statusMessage = new ExtractedFileStatusMessage(message)
                {
                    DicomFilePath = message.DicomFilePath,
                    Status        = ExtractedFileStatus.FileMissing,
                    StatusMessage = $"Could not find '{fullSrc}'"
                };
                _ = _copyStatusProducerModel.SendMessage(statusMessage, header, _options.NoVerifyRoutingKey);
                return;
            }

            string fullDest = _fileSystem.Path.Combine(_extractionRoot, message.ExtractionDirectory, message.OutputPath);

            if (_fileSystem.File.Exists(fullDest))
            {
                _logger.Warn($"Output file '{fullDest}' already exists. Will overwrite.");
            }

            IDirectoryInfo parent = _fileSystem.Directory.GetParent(fullDest);

            if (!parent.Exists)
            {
                _logger.Debug($"Creating directory '{parent}'");
                parent.Create();
            }

            _logger.Debug($"Copying source file to '{message.OutputPath}'");
            _fileSystem.File.Copy(fullSrc, fullDest, overwrite: true);

            statusMessage = new ExtractedFileStatusMessage(message)
            {
                DicomFilePath  = message.DicomFilePath,
                Status         = ExtractedFileStatus.Copied,
                OutputFilePath = message.OutputPath,
            };
            _ = _copyStatusProducerModel.SendMessage(statusMessage, header, _options.NoVerifyRoutingKey);
        }
Пример #16
0
        private void TestCreateFolder(string folder)
        {
            DisplayMessage(string.Format("Creating {0}", folder));

            FileSystemAwareDirectoryInfoProvider dirInfoProvider = new FileSystemAwareDirectoryInfoProvider(new DeviceManager());

            IDirectoryInfo info = dirInfoProvider.GetDirectoryInfo(folder);

            info.Create();

            if (info.Exists)
            {
                DisplayMessage(string.Format("{0} Created OK", info.FullName));
            }
            else
            {
                DisplayMessage(string.Format("{0} Failed to create", info.FullName), DisplayLevel.Error);
            }
        }
Пример #17
0
        private string GetLogDirectory()
        {
            if (_logDirectoryPath == null)
            {
                lock (_logDirectoryPathLock)
                {
                    if (_logDirectoryPath == null)
                    {
                        string         basePath          = _fileSystem.Path.Combine(_dataDirectory.ResolvedPath, InMemoryDirectory);
                        IDirectoryInfo baseDirectoryInfo = _fileSystem.DirectoryInfo.FromDirectoryName(basePath);
                        if (!baseDirectoryInfo.Exists)
                        {
                            baseDirectoryInfo.Create();
                        }

                        IDirectoryInfo[] existingLogDirectories = baseDirectoryInfo.GetDirectories("log*");
                        int existingSuffix = existingLogDirectories.Select(x =>
                        {
                            if (int.TryParse(x.Name.Substring(3), out int suffix))
                            {
                                return(suffix);
                            }

                            return(0);
                        })
                                             .DefaultIfEmpty()
                                             .Max();
                        int    newSuffix        = existingSuffix + 1;
                        string logDirectoryName = $"log{newSuffix:0000}";

                        if (_logger.IsDebug())
                        {
                            LogDebug.CreatingMemoryStoreLogDirectory(_logger, logDirectoryName,
                                                                     baseDirectoryInfo.FullName, null);
                        }
                        IDirectoryInfo logDirectory = baseDirectoryInfo.CreateSubdirectory(logDirectoryName);
                        _logDirectoryPath = logDirectory.FullName;
                    }
                }
            }

            return(_logDirectoryPath);
        }
Пример #18
0
        private void When_creating_directory_it_must_not_update_properties()
        {
            // Arrange
            const string path = @"d:\some\folder\nested";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                                     .IncludingDirectory(@"d:\")
                                     .Build();

            IDirectoryInfo dirInfo = fileSystem.ConstructDirectoryInfo(path);

            bool beforeExists = dirInfo.Exists;

            // Act
            dirInfo.Create();

            // Assert
            beforeExists.Should().BeFalse();
            dirInfo.Exists.Should().BeFalse();
        }
Пример #19
0
        /// <summary>
        /// Adds the Object to Disk and Database
        /// </summary>
        /// <param name='localFile'>
        /// Local file.
        /// </param>
        /// <param name='remoteId'>
        /// Remote Object (already fetched).
        /// </param>
        /// <param name="localContent">Hint if the local content has been changed.</param>
        /// <param name="remoteContent">Information if the remote content has been changed.</param>
        /// <exception cref='ArgumentException'>
        /// Is thrown when remoteId is not prefetched.
        /// </exception>
        public override void Solve(
            IFileSystemInfo localFile,
            IObjectId remoteId,
            ContentChangeType localContent  = ContentChangeType.NONE,
            ContentChangeType remoteContent = ContentChangeType.NONE)
        {
            if (localFile is IDirectoryInfo)
            {
                if (!(remoteId is IFolder))
                {
                    throw new ArgumentException("remoteId has to be a prefetched Folder");
                }

                var            remoteFolder = remoteId as IFolder;
                IDirectoryInfo localFolder  = localFile as IDirectoryInfo;
                localFolder.Create();

                Guid uuid = Guid.Empty;
                if (localFolder.IsExtendedAttributeAvailable())
                {
                    uuid = Guid.NewGuid();
                    try {
                        localFolder.Uuid = uuid;
                    } catch (RestoreModificationDateException) {
                    }
                }

                if (remoteFolder.LastModificationDate != null)
                {
                    localFolder.LastWriteTimeUtc = (DateTime)remoteFolder.LastModificationDate;
                }

                var mappedObject = new MappedObject(remoteFolder);
                mappedObject.Guid = uuid;
                mappedObject.LastRemoteWriteTimeUtc = remoteFolder.LastModificationDate;
                mappedObject.LastLocalWriteTimeUtc  = localFolder.LastWriteTimeUtc;
                this.Storage.SaveMappedObject(mappedObject);
                OperationsLogger.Info(string.Format("New local folder {0} created and mapped to remote folder {1}", localFolder.FullName, remoteId.Id));
            }
            else if (localFile is IFileInfo)
            {
                Guid guid = Guid.NewGuid();
                var  file = localFile as IFileInfo;
                if (!(remoteId is IDocument))
                {
                    throw new ArgumentException("remoteId has to be a prefetched Document");
                }

                if (file.Exists)
                {
                    Guid?uuid = file.Uuid;
                    if (uuid != null)
                    {
                        if (this.Storage.GetObjectByGuid((Guid)uuid) != null)
                        {
                            throw new ArgumentException("This file has already been synced => force crawl sync");
                        }
                    }

                    Logger.Debug(string.Format("This file {0} conflicts with remote file => conflict file will be produced after download", file.FullName));
                }

                var cacheFile = this.fsFactory.CreateDownloadCacheFileInfo(guid);

                IDocument remoteDoc         = remoteId as IDocument;
                var       transmissionEvent = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_NEW_FILE, localFile.FullName, cacheFile.FullName);
                this.manager.AddTransmission(transmissionEvent);
                byte[] hash = null;
                using (var hashAlg = new SHA1Managed())
                    using (var fileStream = cacheFile.Open(FileMode.Create, FileAccess.Write, FileShare.Read))
                        using (var downloader = FileTransmission.ContentTaskUtils.CreateDownloader())
                        {
                            try {
                                downloader.DownloadFile(remoteDoc, fileStream, transmissionEvent, hashAlg);
                            } catch (Exception ex) {
                                transmissionEvent.ReportProgress(new TransmissionProgressEventArgs {
                                    FailedException = ex
                                });
                                throw;
                            }

                            hash = hashAlg.Hash;
                        }

                cacheFile.Uuid = guid;
                try {
                    cacheFile.MoveTo(file.FullName);
                } catch (IOException e) {
                    file.Refresh();
                    if (file.Exists)
                    {
                        IFileInfo conflictFile = this.fsFactory.CreateConflictFileInfo(file);
                        IFileInfo targetFile   = cacheFile.Replace(file, conflictFile, true);
                        targetFile.SetExtendedAttribute(MappedObject.ExtendedAttributeKey, guid.ToString(), true);
                        conflictFile.SetExtendedAttribute(MappedObject.ExtendedAttributeKey, null, true);
                    }
                    else
                    {
                        transmissionEvent.ReportProgress(new TransmissionProgressEventArgs {
                            FailedException = e
                        });
                        throw;
                    }
                }

                file.Refresh();
                if (remoteDoc.LastModificationDate != null)
                {
                    try {
                        file.LastWriteTimeUtc = (DateTime)remoteDoc.LastModificationDate;
                    } catch (IOException e) {
                        Logger.Debug("Cannot set last modification date", e);
                    }
                }

                MappedObject mappedObject = new MappedObject(
                    file.Name,
                    remoteDoc.Id,
                    MappedObjectType.File,
                    remoteDoc.Parents[0].Id,
                    remoteDoc.ChangeToken,
                    remoteDoc.ContentStreamLength ?? 0)
                {
                    Guid = guid,
                    LastLocalWriteTimeUtc  = file.LastWriteTimeUtc,
                    LastRemoteWriteTimeUtc = remoteDoc.LastModificationDate,
                    LastChecksum           = hash,
                    ChecksumAlgorithmName  = "SHA-1"
                };
                this.Storage.SaveMappedObject(mappedObject);
                OperationsLogger.Info(string.Format("New local file {0} created and mapped to remote file {1}", file.FullName, remoteId.Id));
                transmissionEvent.ReportProgress(new TransmissionProgressEventArgs {
                    Completed = true
                });
            }
        }
Пример #20
0
 public PostThumbnailService(IFileSystem fileSystem)
 {
     _thumbnailDirectory = fileSystem.GetDirectory("post-thumbs");
     if (!_thumbnailDirectory.Exists)
         _thumbnailDirectory.Create();
 }
Пример #21
0
        /// <summary>
        /// Adds the Object to Disk and Database
        /// </summary>
        /// <param name='localFile'>
        /// Local file.
        /// </param>
        /// <param name='remoteId'>
        /// Remote Object (already fetched).
        /// </param>
        /// <param name="localContent">Hint if the local content has been changed.</param>
        /// <param name="remoteContent">Information if the remote content has been changed.</param>
        /// <exception cref='ArgumentException'>
        /// Is thrown when remoteId is not prefetched.
        /// </exception>
        public override void Solve(
            IFileSystemInfo localFile,
            IObjectId remoteId,
            ContentChangeType localContent  = ContentChangeType.NONE,
            ContentChangeType remoteContent = ContentChangeType.NONE)
        {
            if (localFile is IDirectoryInfo)
            {
                if (!(remoteId is IFolder))
                {
                    throw new ArgumentException("remoteId has to be a prefetched Folder");
                }

                var            remoteFolder = remoteId as IFolder;
                IDirectoryInfo localFolder  = localFile as IDirectoryInfo;
                localFolder.Create();

                Guid uuid = Guid.Empty;
                if (localFolder.IsExtendedAttributeAvailable())
                {
                    uuid = Guid.NewGuid();
                    try {
                        localFolder.Uuid = uuid;
                    } catch (RestoreModificationDateException) {
                    }
                }

                if (remoteFolder.LastModificationDate != null)
                {
                    try {
                        localFolder.LastWriteTimeUtc = (DateTime)remoteFolder.LastModificationDate;
                    } catch (IOException e) {
                        Logger.Info("Directory modification date could not be synced", e);
                    }
                }

                var mappedObject = new MappedObject(remoteFolder);
                mappedObject.Guid = uuid;
                mappedObject.LastRemoteWriteTimeUtc = remoteFolder.LastModificationDate;
                mappedObject.LastLocalWriteTimeUtc  = localFolder.LastWriteTimeUtc;
                mappedObject.Ignored = remoteFolder.AreAllChildrenIgnored();
                this.Storage.SaveMappedObject(mappedObject);
                OperationsLogger.Info(string.Format("New local folder {0} created and mapped to remote folder {1}", localFolder.FullName, remoteId.Id));
            }
            else if (localFile is IFileInfo)
            {
                if (!(remoteId is IDocument))
                {
                    throw new ArgumentException("remoteId has to be a prefetched Document");
                }

                Guid     guid          = Guid.NewGuid();
                byte[]   localFileHash = null;
                DateTime?lastLocalFileModificationDate = null;
                var      file = localFile as IFileInfo;
                if (file.Exists)
                {
                    Guid?uuid = file.Uuid;
                    if (uuid != null)
                    {
                        if (this.Storage.GetObjectByGuid((Guid)uuid) != null)
                        {
                            throw new ArgumentException("This file has already been synced => force crawl sync");
                        }
                    }

                    lastLocalFileModificationDate = file.LastWriteTimeUtc;
                    if (this.MergeExistingFileWithRemoteFile(file, remoteId as IDocument, guid, out localFileHash))
                    {
                        return;
                    }

                    Logger.Debug(string.Format("This file {0} conflicts with remote file => conflict file will could be produced after download", file.FullName));
                }

                var cacheFile = this.fsFactory.CreateDownloadCacheFileInfo(guid);

                IDocument remoteDoc    = remoteId as IDocument;
                var       transmission = this.manager.CreateTransmission(TransmissionType.DOWNLOAD_NEW_FILE, localFile.FullName, cacheFile.FullName);
                byte[]    hash         = DownloadCacheFile(cacheFile, remoteDoc, transmission, this.fsFactory);

                try {
                    cacheFile.Uuid = guid;
                } catch (RestoreModificationDateException e) {
                    Logger.Debug("Could not retore the last modification date of " + cacheFile.FullName, e);
                }

                try {
                    cacheFile.MoveTo(file.FullName);
                } catch (IOException e) {
                    file.Refresh();
                    if (file.Exists)
                    {
                        if (localFileHash == null ||
                            lastLocalFileModificationDate == null ||
                            !lastLocalFileModificationDate.Equals(file.LastWriteTimeUtc))
                        {
                            lastLocalFileModificationDate = file.LastWriteTimeUtc;
                            using (var f = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) {
                                localFileHash = SHA1Managed.Create().ComputeHash(f);
                            }
                        }

                        if (localFileHash.SequenceEqual(hash))
                        {
                            file.Uuid = guid;
                            try {
                                cacheFile.Delete();
                            } catch (IOException) {
                            }
                        }
                        else
                        {
                            IFileInfo conflictFile = this.fsFactory.CreateConflictFileInfo(file);
                            try {
                                IFileInfo targetFile = cacheFile.Replace(file, conflictFile, true);
                                try {
                                    targetFile.Uuid = guid;
                                } catch (RestoreModificationDateException restoreException) {
                                    Logger.Debug("Could not retore the last modification date of " + targetFile.FullName, restoreException);
                                }
                            } catch (Exception ex) {
                                transmission.FailedException = ex;
                                throw;
                            }

                            try {
                                conflictFile.Uuid = null;
                            } catch (RestoreModificationDateException restoreException) {
                                Logger.Debug("Could not retore the last modification date of " + conflictFile.FullName, restoreException);
                            }
                        }
                    }
                    else
                    {
                        transmission.FailedException = e;
                        throw;
                    }
                }

                file.Refresh();
                if (remoteDoc.LastModificationDate != null)
                {
                    try {
                        file.LastWriteTimeUtc = (DateTime)remoteDoc.LastModificationDate;
                    } catch (IOException e) {
                        Logger.Debug("Cannot set last modification date", e);
                    }
                }

                MappedObject mappedObject = new MappedObject(
                    file.Name,
                    remoteDoc.Id,
                    MappedObjectType.File,
                    remoteDoc.Parents[0].Id,
                    remoteDoc.ChangeToken,
                    remoteDoc.ContentStreamLength ?? 0)
                {
                    Guid = guid,
                    LastLocalWriteTimeUtc  = file.LastWriteTimeUtc,
                    LastRemoteWriteTimeUtc = remoteDoc.LastModificationDate,
                    LastChecksum           = hash,
                    ChecksumAlgorithmName  = "SHA-1"
                };
                this.Storage.SaveMappedObject(mappedObject);
                OperationsLogger.Info(string.Format("New local file {0} created and mapped to remote file {1}", file.FullName, remoteId.Id));
                transmission.Status = TransmissionStatus.FINISHED;
            }
        }
Пример #22
0
 private void CreateItemFolderWithSingleFile(FileSystem fileSystem)
 {
     _itemFolder = fileSystem.DirectoryInfo.FromDirectoryName(SteamUploadPath);
     _itemFolder.Create();
     fileSystem.File.CreateText(SteamUploadPath + "/file.txt").Close();
 }