Example #1
0
        private void RollFile(string prefix)
        {
            int highestRollNumber = GetHighestRollNumber(prefix);

            if (highestRollNumber > 0)
            {
                for (var i = highestRollNumber; i > 0; i--)
                {
                    string sourcePath = GetLogFilePath(prefix, i);
                    string destPath   = GetLogFilePath(prefix, i + 1);

                    try
                    {
                        Log.To.Telemetry.Add(() => $"Renaming '{sourcePath}' to '{destPath}'");
                        _fileSystem.MoveFile(sourcePath, destPath);
                    }
                    catch (Exception ex)
                    {
                        Log.To.Telemetry.Add(() => $"Failed to rename '{sourcePath}' to '{destPath}': {ex}");
                    }
                }
            }

            string currentPath   = GetLogFilePath(prefix);
            string firstRollPath = GetLogFilePath(prefix, 1);

            Log.To.Telemetry.Add(() => $"Renaming active log file '{currentPath}' to '{firstRollPath}'");
            _fileSystem.MoveFile(currentPath, firstRollPath);
        }
        public void MoveFile_ToOtherDirectory_FileIsInOtherDirectory()
        {
            fs.CreateDirectory("/upload/world");
            fs.WriteFile("/upload/hello.txt", new MemoryStream(Encoding.UTF8.GetBytes("hello world")));

            fs.MoveFile("/upload/hello.txt", "/upload/world/hello.txt");

            var f = fs.GetFile("/upload/world/hello.txt");

            Assert.That(f, Is.Not.Null);
            Assert.That(f.VirtualPath, Is.EqualTo("/upload/world/hello.txt"));
        }
        public static bool CreateHistory(SharedFile file, IFileSystem fileSystem, string virtualFilePath, string virtualHistoryPath)
        {
            bool historyCreated = false;

            //File.Move(Path.Combine(sourceFilePath, Path.GetFileName(this.serverFileName)), Path.Combine(historyFolderPath, Path.GetFileName(this.serverFileName)));
            fileSystem.MoveFile(
                VirtualPathUtility.Combine(virtualFilePath, file.ServerFileName),
                VirtualPathUtility.Combine(virtualHistoryPath, file.ServerFileName),
                true);

            historyCreated = SharedFile.AddHistory(
                file.ItemGuid,
                file.ModuleGuid,
                file.UserGuid,
                file.ItemId,
                file.ModuleId,
                file.FriendlyName,
                file.OriginalFileName,
                file.ServerFileName,
                file.SizeInKB,
                file.UploadDate,
                file.UploadUserId);

            return historyCreated;
        }
Example #4
0
        public Task Save(IFileSystem fileSystem, UPath savePath, SaveContext saveContext)
        {
            var fileStream = fileSystem.OpenFile(savePath, FileMode.Create, FileAccess.Write);

            _img.Save(fileStream, Images.Select(x => x.ImageInfo).ToArray());

            if (!_isCompressed)
            {
                return(Task.CompletedTask);
            }

            // Compress file
            fileStream = fileSystem.OpenFile(savePath);
            var compFile = fileSystem.OpenFile(savePath + ".comp", FileMode.Create, FileAccess.Write);

            Compress(fileStream, compFile);

            fileStream.Close();
            compFile.Close();

            // Set compressed file as saved file
            fileSystem.DeleteFile(savePath);
            fileSystem.MoveFile(savePath + ".comp", savePath);

            return(Task.CompletedTask);
        }
Example #5
0
        public static bool CreateHistory(SharedFile file, IFileSystem fileSystem, string virtualFilePath, string virtualHistoryPath)
        {
            bool historyCreated = false;

            //File.Move(Path.Combine(sourceFilePath, Path.GetFileName(this.serverFileName)), Path.Combine(historyFolderPath, Path.GetFileName(this.serverFileName)));
            fileSystem.MoveFile(
                VirtualPathUtility.Combine(virtualFilePath, file.ServerFileName),
                VirtualPathUtility.Combine(virtualHistoryPath, file.ServerFileName),
                true);

            historyCreated = SharedFile.AddHistory(
                file.ItemGuid,
                file.ModuleGuid,
                file.UserGuid,
                file.ItemId,
                file.ModuleId,
                file.FriendlyName,
                file.OriginalFileName,
                file.ServerFileName,
                file.SizeInKB,
                file.UploadDate,
                file.UploadUserId,
                file.ViewRoles
                );


            return(historyCreated);
        }
Example #6
0
        private void WriteXml()
        {
            int    i = 0;
            var    destinationFileName = _settingsPath;
            string filename            = destinationFileName + "_" + Guid.NewGuid();
            bool   writeWasSucessful;

            do
            {
                WriteXmlImpl(filename);
            }while (!(writeWasSucessful = ValidateXmlFile(filename)) && ++i < 10);

            if (!writeWasSucessful)
            {
                Log.To.Main.Add("Critical error writing XML settings file", LogLevel.Verbose);
                return;
            }

            if (_fileSystem.FileExists(destinationFileName))
            {
                _fileSystem.ReplaceFile(filename, destinationFileName, filename + "_fsCopy");
                if (_fileSystem.FileExists(filename + "_fsCopy"))
                {
                    _fileSystem.DeleteFile(filename + "_fsCopy");
                }
            }
            else
            {
                _fileSystem.MoveFile(filename, destinationFileName);
            }
        }
Example #7
0
        void btnUpdateAvartar_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            // this is fired when the avatar upload dialog is closed
            // we don't really know for sure if the image was updated
            // but if it was we should rename it since the previous version may be cached by web browsers
            // so we'll check if the files was modified recently, and if so rename it
            if ((siteUser != null) && siteUser.AvatarUrl.Length > 0)
            {
                FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];
                if (p != null)
                {
                    IFileSystem fileSystem     = p.GetFileSystem();
                    string      avatarBasePath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/useravatars/";
                    WebFile     avatarFile     = fileSystem.RetrieveFile(avatarBasePath + siteUser.AvatarUrl);
                    if (avatarFile != null)
                    {
                        if (avatarFile.Modified > DateTime.Today)
                        {
                            // it was updated today so we'll assume it was just now since the avatar dialog just closed
                            string newfileName = "user"
                                                 + siteUser.UserId.ToInvariantString()
                                                 + "-" + siteUser.Name.ToCleanFileName()
                                                 + "-" + DateTime.UtcNow.Millisecond.ToInvariantString()
                                                 + System.IO.Path.GetExtension(siteUser.AvatarUrl);

                            fileSystem.MoveFile(avatarBasePath + siteUser.AvatarUrl, avatarBasePath + newfileName, true);
                            siteUser.AvatarUrl = newfileName;
                            siteUser.Save();
                        }
                    }
                }
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }
Example #8
0
        public RenameResult Execute(RenameState state)
        {
            try
            {
                // state.target is expected to be relative
                // per UI lib specification
                var destination = _fileSystem.PathCombine(
                    new NPath(System.IO.Path.GetDirectoryName(state.Source.Raw)),
                    state.Target).Raw;

                if (_fileSystem.DirectoryExists(state.Source))
                {
                    _fileSystem.MoveDirectory(state.Source, new NPath(destination));
                }
                else if (_fileSystem.FileExists(state.Source))
                {
                    _fileSystem.MoveFile(state.Source, new NPath(destination));
                }

                Result = new RenameResult(true, new
                {
                    id    = destination,
                    value = state.Target.Raw
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                Result = new RenameResult(false, null);
            }

            return(Result);
        }
Example #9
0
        void btnUpdateAvartar_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if ((siteUser != null) && siteUser.AvatarUrl.Length > 0)
            {
                FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];
                if (p != null)
                {
                    IFileSystem fileSystem     = p.GetFileSystem();
                    string      avatarBasePath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/useravatars/";
                    WebFile     avatarFile     = fileSystem.RetrieveFile(avatarBasePath + siteUser.AvatarUrl);
                    if (avatarFile != null)
                    {
                        if (avatarFile.Modified > DateTime.Today)
                        {
                            string newfileName = "user"
                                                 + siteUser.UserId.ToInvariantString()
                                                 + "-" + siteUser.Name.ToCleanFileName()
                                                 + "-" + DateTime.UtcNow.Millisecond.ToInvariantString()
                                                 + System.IO.Path.GetExtension(siteUser.AvatarUrl);

                            fileSystem.MoveFile(avatarBasePath + siteUser.AvatarUrl, avatarBasePath + newfileName, true);
                            siteUser.AvatarUrl = newfileName;
                            siteUser.Save();
                        }
                    }
                }
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }
Example #10
0
        private void MoveFile(HttpContext context)
        {
            var result = OpResult.Denied;

            if (
                (fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(virtualSourcePath))) &&
                (fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(virtualTargetPath)))
                )
            {
                try
                {
                    if (OnFileMoving(virtualSourcePath, virtualTargetPath, ref result))
                    {
                        result = fileSystem.MoveFile(virtualSourcePath, virtualTargetPath, false);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    result = OpResult.Error;
                }
            }

            RenderJsonResult(context, result);
        }
Example #11
0
        void files_FileMoved(object sender, FileEventArgs e)
        {
            if (!Enabled)
            {
                return;
            }

            if (!IsResizableImagePath(e.VirtualPath))
            {
                return;
            }

            foreach (ImageSizeElement size in images.Sizes.AllElements)
            {
                string source = ImagesUtility.GetResizedPath(e.SourcePath, size.Name);
                if (files.FileExists(source))
                {
                    string destination = ImagesUtility.GetResizedPath(e.VirtualPath, size.Name);
                    if (!files.FileExists(destination))
                    {
                        files.MoveFile(source, destination);
                    }
                }
            }
        }
Example #12
0
        private void WriteHashFile(HttpContext context, string nupkgPath, string hashFilePath, long packageSize, string packageHash)
        {
            if (hashFilePath == null)
            {
                return; // feature not enabled.
            }
            try
            {
                var tempHashFilePath = GetHashFile(nupkgPath, true);
                _fileSystem.DeleteFile(tempHashFilePath);
                _fileSystem.DeleteFile(hashFilePath);

                var content = new StringBuilder();
                content.AppendLine(packageSize.ToString(CultureInfo.InvariantCulture));
                content.AppendLine(packageHash);

                using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(content.ToString())))
                {
                    _fileSystem.AddFile(tempHashFilePath, stream);
                }
                // move temp file to official location when previous operation completed successfully to minimize impact of potential errors (ex: machine crash in the middle of saving the file).
                _fileSystem.MoveFile(tempHashFilePath, hashFilePath);
            }
            catch (Exception e)
            {
                // Hashing persistence is a perf optimization feature; we chose to degrade perf over degrading functionality in case of failure.
                Log(context, string.Format("Unable to create hash file '{0}'.", hashFilePath), e);
            }
        }
Example #13
0
        public void Delete(IFileSystem fileSystem, string filePath)
        {
            if (!fileSystem.FileExists(filePath))
            {
                return;
            }

            try
            {
                if (Path.GetExtension(filePath) == TempExtenstion)
                {
                    fileSystem.DeleteFile(filePath);
                }
                else
                {
                    var tempFilePath = filePath + TempExtenstion;

                    fileSystem.MoveFile(filePath, tempFilePath, true);
                    _logger.LogTrace($"Moved file {filePath} to temp place {tempFilePath}.");

                    fileSystem.DeleteFile(filePath);
                    _logger.LogTrace($"Deleted file {filePath} successfully.");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.GetBaseException().ToString());
            }
        }
Example #14
0
        private void Process(
            FileOperation file,
            bool isMove,
            SynchronizationContext uiContext,
            CancellationTokenSource cancellation)
        {
            var retry = true;

            while (retry)
            {
                retry = false;
                try
                {
                    if (isMove)
                    {
                        _fileSystem.MoveFile(file.SourcePath, file.DestinationPath);
                    }
                    else
                    {
                        _fileSystem.CopyFile(file.SourcePath, file.DestinationPath);
                    }
                }
                catch (FileNotFoundException)
                {
                    // silently ignore this error, just don't copy/move the file
                }
                catch (DirectoryNotFoundException)
                {
                    // silently ignore this error, just don't copy/move the file
                }
                catch (IOException)
                {
                    var result = DialogResult.No;
                    uiContext.Send(_ =>
                    {
                        result = _dialogView.ConfirmReplace(file.DestinationPath);
                    }, null);

                    if (result == DialogResult.Yes)
                    {
                        retry = true;
                        _fileSystem.DeleteFile(file.DestinationPath);
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        cancellation.Cancel();
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    uiContext.Send(_ => _dialogView.UnauthorizedAccess(file.SourcePath), null);
                }
                catch (SecurityException)
                {
                    uiContext.Send(_ => _dialogView.UnauthorizedAccess(file.SourcePath), null);
                }
            }
        }
Example #15
0
        private void PerformFileSorting(MovieFileOrganizationOptions options, FileOrganizationResult result)
        {
            // We should probably handle this earlier so that we never even make it this far
            if (string.Equals(result.OriginalPath, result.TargetPath, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            _libraryMonitor.ReportFileSystemChangeBeginning(result.TargetPath);

            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(result.TargetPath));

            var targetAlreadyExists = _fileSystem.FileExists(result.TargetPath);

            try
            {
                if (targetAlreadyExists || options.CopyOriginalFile)
                {
                    _fileSystem.CopyFile(result.OriginalPath, result.TargetPath, true);
                }
                else
                {
                    _fileSystem.MoveFile(result.OriginalPath, result.TargetPath);
                }

                result.Status        = FileSortingStatus.Success;
                result.StatusMessage = string.Empty;
            }
            catch (Exception ex)
            {
                var errorMsg = string.Format("Failed to move file from {0} to {1}: {2}", result.OriginalPath, result.TargetPath, ex.Message);

                result.Status        = FileSortingStatus.Failure;
                result.StatusMessage = errorMsg;
                _logger.ErrorException(errorMsg, ex);

                return;
            }
            finally
            {
                _libraryMonitor.ReportFileSystemChangeComplete(result.TargetPath, true);
            }

            if (targetAlreadyExists && !options.CopyOriginalFile)
            {
                try
                {
                    _fileSystem.DeleteFile(result.OriginalPath);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error deleting file {0}", ex, result.OriginalPath);
                }
            }
        }
Example #16
0
        public void Execute(TemplatePlanContext context)
        {
            var fileSet = new FileSet
            {
                DeepSearch = false,
                Include    = "*.*",
                Exclude    = "*.exe;*.dll;.git;{0};{1};".ToFormat(FubuIgnoreFile, AutoRunFubuRake.FubuRakeFile)
            };
            var fubuIgnore = FileSystem.Combine(context.TempDir, FubuIgnoreFile);

            if (_fileSystem.FileExists(fubuIgnore))
            {
                _fileSystem
                .ReadStringFromFile(fubuIgnore)
                .SplitOnNewLine()
                .Each(ignore =>
                {
                    fileSet.Exclude += "{0};".ToFormat(ignore);
                });
            }

            var excludedFiles = fileSet.ExcludedFilesFor(context.TempDir);

            _fileSystem
            .FindFiles(context.TempDir, fileSet)
            .Where(file => !excludedFiles.Contains(file))
            .Each(from =>
            {
                var destination = Path.Combine(context.TargetPath, _fileSystem.GetFileName(from));
                if (_fileSystem.FileExists(destination))
                {
                    _fileSystem.DeleteFile(destination);
                }
                _fileSystem.MoveFile(from, destination);
            });

            _fileSystem
            .ChildDirectoriesFor(context.TempDir)
            .Each(directory =>
            {
                var destinationName = _fileSystem.GetFileName(directory);
                if (destinationName == ".git")
                {
                    return;
                }

                var destination = Path.Combine(context.TargetPath, destinationName);
                if (_fileSystem.DirectoryExists(destination))
                {
                    _fileSystem.DeleteDirectory(destination);
                }
                _fileSystem.MoveDirectory(directory, destination);
            });
        }
Example #17
0
        private bool TryArchiveLogFile(FileLoggerOptions options, string logFilePath)
        {
            try
            {
                _FileSystem.MoveFile(logFilePath, Path.Combine(options.LogFileArchiveDirectory, Path.GetFileName(logFilePath)));
                return(true);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
#pragma warning restore CA1031 // Do not catch general exception types
            {
                return(false);
            }
        }
        void dgFile_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView grid        = (GridView)sender;
                TextBox  txtEditName = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtEditName");

                if (txtEditName.Text.Trim().Length < 1)
                {
                    return;
                }

                string dir = GetCurrentDirectory();
                string path;
                string previousPath;
                if (dir.Length > 0)
                {
                    path         = dir + displayPathSeparator + txtEditName.Text;
                    previousPath = dir + displayPathSeparator + ViewState["lastSelection"].ToString();
                }
                else
                {
                    path         = txtEditName.Text;
                    previousPath = ViewState["lastSelection"].ToString();
                }

                int type = int.Parse(grid.DataKeys[e.RowIndex].Value.ToString());
                if (type == 0)
                {
                    // folder
                    fileSystem.MoveFolder(previousPath, path);
                }
                else
                {
                    // file
                    fileSystem.MoveFile(previousPath, path, false);
                }
                grid.EditIndex = -1;
                BindData();
                //Response.Redirect(Request.Url.ToString(),false);
            }
            catch (UnauthorizedAccessException ex)
            {
                lblError.Text = ex.Message;
            }
            catch (ArgumentException ex)
            {
                lblError.Text = ex.Message;
            }
        }
Example #19
0
        private void MoveFromProcessingFolder(string initialFilePath, string folder)
        {
            var processingFilePath = initialToProcessingPathMapping[initialFilePath];

            // capturedFiles.Remove(processingFilePath);

            fileSystem.MoveFile(processingFilePath, Path.Combine(folder, Path.GetFileName(processingFilePath)), true);

            string tempFilePath = null;

            initialToProcessingPathMapping.TryRemove(initialFilePath, out tempFilePath);

            fileSystem.DeleteFile(Path.ChangeExtension(processingFilePath, doneFileExtension));
        }
Example #20
0
        private void DeleteLibraryFile(string path, bool renameRelatedFiles, string targetPath)
        {
            _fileSystem.DeleteFile(path);

            if (!renameRelatedFiles)
            {
                return;
            }

            // Now find other files
            var originalFilenameWithoutExtension = Path.GetFileNameWithoutExtension(path);
            var directory = _fileSystem.GetDirectoryName(path);

            if (!string.IsNullOrWhiteSpace(originalFilenameWithoutExtension) && !string.IsNullOrWhiteSpace(directory))
            {
                // Get all related files, e.g. metadata, images, etc
                var files = _fileSystem.GetFilePaths(directory)
                            .Where(i => (Path.GetFileNameWithoutExtension(i) ?? string.Empty).StartsWith(originalFilenameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                            .ToList();

                var targetFilenameWithoutExtension = Path.GetFileNameWithoutExtension(targetPath);

                foreach (var file in files)
                {
                    directory = _fileSystem.GetDirectoryName(file);
                    var filename = Path.GetFileName(file);

                    filename = filename.Replace(originalFilenameWithoutExtension, targetFilenameWithoutExtension,
                                                StringComparison.OrdinalIgnoreCase);

                    var destination = Path.Combine(directory, filename);

                    _fileSystem.MoveFile(file, destination);
                }
            }
        }
Example #21
0
        protected void Move(string oldPath, string newPath)
        {
            try
            {
                if (_fileSystem.FileExists(newPath))
                {
                    _fileSystem.DeleteFile(newPath);
                }
            }
            catch (FileNotFoundException)
            {
            }

            _fileSystem.MoveFile(oldPath, newPath);
        }
Example #22
0
        public void Log(string message)
        {
            var fileName = _fileNameGenerator.GetFileName();

            _fileSystem.CreateFileIfNotExists(fileName);

            if (fileName == "weekend.txt")
            {
                if (_fileSystem.GetCreationTime(fileName) < _dateTime.Today.AddDays(-2))
                {
                    _fileSystem.MoveFile(fileName, _fileNameGenerator.GetLastSaturdayFileName());
                }
            }

            _fileSystem.StringWriteLineToFile(fileName, message);
        }
        public BeginCreatePostResult BeginCreatePost(string markdownContent, string title)
        {
            var postId = this.randomIdGenerator.GenerateId(8);

            var tempPath = GetPostDirectory(postId);

            fileSystem.CreateDirectory(tempPath);

            List <string> localImageUrls = null;

            (localImageUrls, markdownContent) = ExtractAndReplaceClientCachedImages(postId, markdownContent);

            List <string> serverCachedImagesNames = null;

            (serverCachedImagesNames, markdownContent) = ExtractAndReplaceServerCachedImages(postId, markdownContent);

            var imageDirectory = Path.Combine(Path.Combine(tempPath, "img"));

            if (serverCachedImagesNames.Count > 0)
            {
                fileSystem.CreateDirectory(imageDirectory);
            }

            foreach (var serverImageName in serverCachedImagesNames)
            {
                var fromFilename = Path.Combine(this.blogSettings.LocalImageTempFolder, serverImageName);
                var toFileName   = Path.Combine(Path.Combine(tempPath, "img"), serverImageName);
                fileSystem.MoveFile(fromFilename, toFileName);
            }

            fileSystem.WriteAllText(Path.Combine(tempPath, "content.md"), markdownContent);
            //TODO: PublicationDate should be deferred until commit so we should move metadata to commit in the future.
            var metadata = new PostMetadata
            {
                Title           = title,
                PostId          = postId,
                PublicationDate = this.clock.Now
            };

            fileSystem.WriteAllText(Path.Combine(tempPath, "metadata.json"), JsonConvert.SerializeObject(metadata));

            return(new BeginCreatePostResult
            {
                PostId = postId,
                LocalImageUrls = localImageUrls
            });
        }
Example #24
0
        public void ParseFile(string file)
        {
            var fileContent = _fileSystem.ReadStringFromFile(file);

            var replacedFileContent = _keywordReplacer.Replace(fileContent);
            if (fileContent != replacedFileContent)
            {
                _fileSystem.WriteStringToFile(file, replacedFileContent);
            }

            var newFileName = _keywordReplacer.Replace(file);
            if (file != newFileName)
            {
                Console.WriteLine("{0} -> {1}", file, Path.GetFileName(newFileName));
                _fileSystem.MoveFile(file, newFileName);
            }
        }
Example #25
0
        private void MoveFile(HttpContext context)
        {
            var result = OpResult.Denied;

            try
            {
                if (OnFileMoving(srcPath, destPath, ref result))
                {
                    result = fileSystem.MoveFile(srcPath, destPath, false);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result = OpResult.Error;
            }

            RenderJsonResult(context, result);
        }
Example #26
0
        public void Copy(IFileSystem srcFileSystem, IFileSystem destFileSystem, string srcFilePath, string destFilePath)
        {
            if (srcFileSystem == null)
            {
                throw new ArgumentNullException(nameof(srcFileSystem));
            }
            if (destFileSystem == null)
            {
                throw new ArgumentNullException(nameof(destFileSystem));
            }
            if (srcFilePath == null)
            {
                throw new ArgumentNullException(nameof(srcFilePath));
            }
            if (destFilePath == null)
            {
                throw new ArgumentNullException(nameof(destFilePath));
            }

            if (srcFilePath.EndsWith(TempExtenstion))
            {
                return;
            }

            try
            {
                var tempFilePath = srcFilePath + TempExtenstion;

                destFileSystem.CreateDirectory(Path.GetDirectoryName(srcFilePath));

                srcFileSystem.CopyFile(srcFilePath, destFileSystem, tempFilePath, true);
                _logger.LogTrace($"Copied file from source {srcFilePath} to temp {tempFilePath}.");

                destFileSystem.MoveFile(tempFilePath, destFilePath, true);
                _logger.LogTrace($"Moved file from source {srcFilePath} to dest {destFilePath} successfully.");

                _fileComparer.EnsureIsEqualFile(srcFileSystem, destFileSystem, srcFilePath, destFilePath);
            }
            catch (Exception e)
            {
                _logger.LogError(e.GetBaseException().ToString());
            }
        }
Example #27
0
        void dgFile_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView grid        = (GridView)sender;
                TextBox  txtEditName = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtEditName");

                if (txtEditName.Text.Trim().Length < 1)
                {
                    return;
                }

                string dir = GetCurrentDirectory();
                //string path = dir + txtEditName.Text.ToCleanFolderName(WebConfigSettings.ForceLowerCaseForFolderCreation);
                string previousPath = dir + ViewState["lastSelection"].ToString();

                int type = int.Parse(grid.DataKeys[e.RowIndex].Value.ToString());
                if (type == 0)
                {
                    // folder
                    string path = dir + txtEditName.Text.ToCleanFolderName(WebConfigSettings.ForceLowerCaseForFolderCreation);
                    fileSystem.MoveFolder(previousPath, path);
                }
                else
                {
                    // file
                    string path = dir + txtEditName.Text.ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                    fileSystem.MoveFile(previousPath, path, false);
                }
                grid.EditIndex = -1;
                BindData();
            }
            catch (UnauthorizedAccessException ex)
            {
                lblError.Text = ex.Message;
            }
            catch (ArgumentException ex)
            {
                lblError.Text = ex.Message;
            }
        }
Example #28
0
        private void WriteContentAddressableFile(IFileSystem fs, UPath path, byte[] contents)
        {
            UPath dirPath = path.GetDirectory();

            CreateDirectoryRecursively(fs, dirPath);

            // Assuming the filename is content-addressable, so that if there is
            // already the file of the same name the content is the same as well.
            if (fs.FileExists(path))
            {
                return;
            }

            // For atomicity, writes bytes into an intermediate temp file,
            // and then renames it to the final destination.
            UPath tmpPath = dirPath / $".{Guid.NewGuid():N}.tmp";

            try
            {
                fs.WriteAllBytes(tmpPath, contents);
                try
                {
                    fs.MoveFile(tmpPath, path);
                }
                catch (IOException)
                {
                    if (!fs.FileExists(path) ||
                        fs.GetFileLength(path) != contents.LongLength)
                    {
                        throw;
                    }
                }
            }
            finally
            {
                if (fs.FileExists(tmpPath))
                {
                    fs.DeleteFile(tmpPath);
                }
            }
        }
Example #29
0
        protected void AssertCommonReadOnly(IFileSystem fs)
        {
            Assert.True(fs.DirectoryExists("/"));

            Assert.Throws <IOException>(() => fs.CreateDirectory("/test"));
            Assert.Throws <IOException>(() => fs.DeleteDirectory("/test", true));
            Assert.Throws <IOException>(() => fs.MoveDirectory("/drive", "/drive2"));

            Assert.Throws <IOException>(() => fs.CreateFile("/toto.txt"));
            Assert.Throws <IOException>(() => fs.CopyFile("/toto.txt", "/dest.txt", true));
            Assert.Throws <IOException>(() => fs.MoveFile("/drive", "/drive2"));
            Assert.Throws <IOException>(() => fs.DeleteFile("/toto.txt"));
            Assert.Throws <IOException>(() => fs.OpenFile("/toto.txt", FileMode.Create, FileAccess.ReadWrite));
            Assert.Throws <IOException>(() => fs.OpenFile("/toto.txt", FileMode.Open, FileAccess.Write));
            Assert.Throws <IOException>(() => fs.ReplaceFile("/a/a/a.txt", "/A.txt", "/titi.txt", true));

            Assert.Throws <IOException>(() => fs.SetAttributes("/toto.txt", FileAttributes.ReadOnly));
            Assert.Throws <IOException>(() => fs.SetCreationTime("/toto.txt", DateTime.Now));
            Assert.Throws <IOException>(() => fs.SetLastAccessTime("/toto.txt", DateTime.Now));
            Assert.Throws <IOException>(() => fs.SetLastWriteTime("/toto.txt", DateTime.Now));

            AssertCommonRead(fs, true);
        }
Example #30
0
        public void Move(IEntity entity, string newPath)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (newPath == null)
            {
                throw new ArgumentNullException(nameof(newPath));
            }

            if (entity is FileEntity)
            {
                _fileSystem.MoveFile(entity.Path, newPath);
            }
            else if (entity is DirectoryEntity)
            {
                _fileSystem.MoveDirectory(entity.Path, newPath);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(entity));
            }
        }
Example #31
0
        public void TestFile()
        {
            // Test CreateFile/OpenFile
            var stream          = fs.CreateFile("/toto.txt");
            var writer          = new StreamWriter(stream);
            var originalContent = "This is the content";

            writer.Write(originalContent);
            writer.Flush();
            stream.Dispose();

            // Test FileExists
            Assert.False(fs.FileExists(null));
            Assert.False(fs.FileExists("/titi.txt"));
            Assert.True(fs.FileExists("/toto.txt"));

            // ReadAllText
            var content = fs.ReadAllText("/toto.txt");

            Assert.Equal(originalContent, content);

            // sleep for creation time comparison
            Thread.Sleep(16);

            // Test CopyFile
            fs.CopyFile("/toto.txt", "/titi.txt", true);
            Assert.True(fs.FileExists("/toto.txt"));
            Assert.True(fs.FileExists("/titi.txt"));
            content = fs.ReadAllText("/titi.txt");
            Assert.Equal(originalContent, content);

            // Test Attributes/Times
            Assert.True(fs.GetFileLength("/toto.txt") > 0);
            Assert.Equal(fs.GetFileLength("/toto.txt"), fs.GetFileLength("/titi.txt"));
            Assert.Equal(fs.GetAttributes("/toto.txt"), fs.GetAttributes("/titi.txt"));
            Assert.NotEqual(fs.GetCreationTime("/toto.txt"), fs.GetCreationTime("/titi.txt"));
            // Because we read titi.txt just before, access time must be different
            Assert.NotEqual(fs.GetLastAccessTime("/toto.txt"), fs.GetLastAccessTime("/titi.txt"));
            Assert.Equal(fs.GetLastWriteTime("/toto.txt"), fs.GetLastWriteTime("/titi.txt"));

            var now  = DateTime.Now + TimeSpan.FromSeconds(10);
            var now1 = DateTime.Now + TimeSpan.FromSeconds(11);
            var now2 = DateTime.Now + TimeSpan.FromSeconds(12);

            fs.SetCreationTime("/toto.txt", now);
            fs.SetLastAccessTime("/toto.txt", now1);
            fs.SetLastWriteTime("/toto.txt", now2);
            Assert.Equal(now, fs.GetCreationTime("/toto.txt"));
            Assert.Equal(now1, fs.GetLastAccessTime("/toto.txt"));
            Assert.Equal(now2, fs.GetLastWriteTime("/toto.txt"));

            Assert.NotEqual(fs.GetCreationTime("/toto.txt"), fs.GetCreationTime("/titi.txt"));
            Assert.NotEqual(fs.GetLastAccessTime("/toto.txt"), fs.GetLastAccessTime("/titi.txt"));
            Assert.NotEqual(fs.GetLastWriteTime("/toto.txt"), fs.GetLastWriteTime("/titi.txt"));

            // Test MoveFile
            fs.MoveFile("/toto.txt", "/tata.txt");
            Assert.False(fs.FileExists("/toto.txt"));
            Assert.True(fs.FileExists("/tata.txt"));
            Assert.True(fs.FileExists("/titi.txt"));
            content = fs.ReadAllText("/tata.txt");
            Assert.Equal(originalContent, content);

            // Test Enumerate file
            var files = fs.EnumerateFiles("/").Select(p => p.FullName).ToList();

            files.Sort();
            Assert.Equal(new List <string>()
            {
                "/tata.txt", "/titi.txt"
            }, files);

            var dirs = fs.EnumerateDirectories("/").Select(p => p.FullName).ToList();

            Assert.Empty(dirs);

            // Check ReplaceFile
            var originalContent2 = "this is a content2";

            fs.WriteAllText("/tata.txt", originalContent2);
            fs.ReplaceFile("/tata.txt", "/titi.txt", "/titi.bak.txt", true);
            Assert.False(fs.FileExists("/tata.txt"));
            Assert.True(fs.FileExists("/titi.txt"));
            Assert.True(fs.FileExists("/titi.bak.txt"));
            content = fs.ReadAllText("/titi.txt");
            Assert.Equal(originalContent2, content);
            content = fs.ReadAllText("/titi.bak.txt");
            Assert.Equal(originalContent, content);

            // Check File ReadOnly
            fs.SetAttributes("/titi.txt", FileAttributes.ReadOnly);
            Assert.Throws <UnauthorizedAccessException>(() => fs.DeleteFile("/titi.txt"));
            Assert.Throws <UnauthorizedAccessException>(() => fs.CopyFile("/titi.bak.txt", "/titi.txt", true));
            Assert.Throws <UnauthorizedAccessException>(() => fs.OpenFile("/titi.txt", FileMode.Open, FileAccess.ReadWrite));
            fs.SetAttributes("/titi.txt", FileAttributes.Normal);

            // Delete File
            fs.DeleteFile("/titi.txt");
            Assert.False(fs.FileExists("/titi.txt"));
            fs.DeleteFile("/titi.bak.txt");
            Assert.False(fs.FileExists("/titi.bak.txt"));
        }
        public static bool RestoreHistoryFile(
            int historyId, 
            IFileSystem fileSystem,
            string virtualSourcePath, 
            string virtualHistoryPath)
        {
            bool historyRestored = false;

            if (string.IsNullOrEmpty(virtualSourcePath)) { return historyRestored; }
            if (string.IsNullOrEmpty(virtualHistoryPath)) { return historyRestored; }
            if (fileSystem == null) { return historyRestored; }

            int itemId = 0;
            int moduleId = 0;
            string historyFriendlyName = string.Empty;
            string historyOriginalName = string.Empty;
            string historyServerName = string.Empty;
            DateTime historyUploadDate = DateTime.Now;
            int historyUploadUserID = 0;
            int historyFileSize = 0;

            using (IDataReader reader = SharedFile.GetHistoryFileAsIDataReader(historyId))
            {
                if (reader.Read())
                {
                    itemId = Convert.ToInt32(reader["ItemID"]);
                    moduleId = Convert.ToInt32(reader["ModuleID"]);
                    historyFriendlyName = reader["FriendlyName"].ToString();
                    historyOriginalName = reader["OriginalFileName"].ToString();
                    historyServerName = reader["ServerFileName"].ToString();
                    historyFileSize = Convert.ToInt32(reader["SizeInKB"]);
                    historyUploadUserID = Convert.ToInt32(reader["UploadUserID"]);
                    historyUploadDate = DateTime.Parse(reader["UploadDate"].ToString());

                }
            }

            SharedFile sharedFile = new SharedFile(moduleId, itemId);
            CreateHistory(sharedFile, fileSystem, virtualSourcePath, virtualHistoryPath);

            //File.Move(Path.Combine(historyPath, Path.GetFileName(historyServerName)), Path.Combine(sourcePath, Path.GetFileName(historyServerName)));
            fileSystem.MoveFile(
                VirtualPathUtility.Combine(virtualHistoryPath, historyServerName),
                VirtualPathUtility.Combine(virtualSourcePath, historyServerName),
                true);

            sharedFile.ServerFileName = historyServerName;
            sharedFile.OriginalFileName = historyOriginalName;
            sharedFile.FriendlyName = historyFriendlyName;
            sharedFile.SizeInKB = historyFileSize;
            sharedFile.UploadDate = historyUploadDate;
            sharedFile.UploadUserId = historyUploadUserID;
            historyRestored = sharedFile.Save();
            SharedFile.DeleteHistory(historyId);

            fileSystem.DeleteFile(VirtualPathUtility.Combine(virtualHistoryPath, historyServerName));

            return historyRestored;
        }