Exemplo n.º 1
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which retrieves the binary contents from a provivder, and writes them into a given file.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="fileInfo">Provides meta information about the file to be read.</param>
 /// <param name="filePath">The file to be created. If a corresponding file already
 /// exists, it will be overwritten.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
 /// is a null reference.</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="filePath"/>
 /// is a null reference.</exception>
 public static void SaveFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, string filePath)
 {
   using (Stream destination = new FileStream(filePath, FileMode.Create, FileAccess.Write))
   {
     ReadFile(provider, fileInfo, destination, true);
   }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the MD5 file hash of a given file on the file system.
        /// </summary>
        protected string GetFileHash(VirtualFileInfo file)
        {
            var token = FileSystem.DownloadTransfers.RequestDownloadToken(file.FullName, true);

            FileSystem.DownloadTransfers.CancelTransfer(token.TransferId, AbortReason.ClientAbort);
            return(token.Md5FileHash);
        }
Exemplo n.º 3
0
    public void Overwriting_File_Without_Request_Should_Be_Blocked()
    {
      VirtualFile file;

      FileInfo sourceFile = rootDirectory.GetFiles().First();
      using (Stream stream = sourceFile.OpenRead())
      {
        file = root.AddFile("foobar.bin", stream, false, sourceFile.Length, ContentUtil.UnknownContentType);
        Assert.AreEqual("foobar.bin", file.MetaData.Name);
      }

      VirtualFileInfo original = file.MetaData;

      //overwrite file - this will not happen
      sourceFile = rootDirectory.GetFiles().Last();
      using (Stream stream = sourceFile.OpenRead())
      {
        try
        {
          root.AddFile("foobar.bin", stream, false, sourceFile.Length, ContentUtil.UnknownContentType);
          Assert.Fail("Could overwrite file.");
        }
        catch (ResourceOverwriteException e)
        {
          StringAssert.Contains("foobar.bin", e.Message);
        }
      }

      //make sure nothing changed
      var update = root.GetFiles("foobar.bin").Single();
      Assert.AreEqual(original.Length, update.MetaData.Length);
      Assert.AreEqual(original.LastWriteTime, update.MetaData.LastWriteTime);
    }
Exemplo n.º 4
0
    public void Overwriting_A_File_Should_Update_Meta_Data()
    {
      VirtualFile file;

      FileInfo sourceFile = rootDirectory.GetFiles().First();
      using (Stream stream = sourceFile.OpenRead())
      {
        file = root.AddFile("foobar.bin", stream, false, sourceFile.Length, ContentUtil.UnknownContentType);
        Assert.AreEqual("foobar.bin", file.MetaData.Name);
      }

      VirtualFileInfo original = file.MetaData;

      //make a break in order to ensure timestamps are not the same
      Thread.Sleep(1000);

      //overwrite file
      sourceFile = rootDirectory.GetFiles().Last();
      using (Stream stream = sourceFile.OpenRead())
      {
        file = root.AddFile("foobar.bin", stream, true, sourceFile.Length, ContentUtil.UnknownContentType);
        Assert.AreEqual("foobar.bin", file.MetaData.Name);
      }

      VirtualFileInfo update = file.MetaData;

      Assert.AreNotSame(original, update);
      Assert.AreEqual(original.Name, update.Name);
      Assert.AreEqual(original.FullName, update.FullName);
      Assert.AreNotEqual(original.Length, update.Length);
      Assert.AreNotEqual(original.LastWriteTime, update.LastWriteTime);
    }
Exemplo n.º 5
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which writes the data of a given file to the submitted output stream as a non-blocking
 /// operation, and invokes the submitted delegate once the process has been completed.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="fileInfo">Provides meta information about the file to be read.</param>
 /// <param name="output">A stream to which the file's contents are written. The stream will
 /// be automatically closed as soon as the operations finishes.</param>
 /// <param name="completionCallback">Invoked as soon as the operation has been completed,
 /// or aborted. This is an optional parameter, which can be null.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
 /// is a null reference.</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="output"/>
 /// is a null reference.</exception>
 public static void BeginReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream output,
                                  Action <FileOperationResult> completionCallback)
 {
     ThreadPool.QueueUserWorkItem(delegate
     {
         FileOperationResult result = new FileOperationResult(fileInfo);
         try
         {
             ReadFile(provider, fileInfo, output, true);
             if (completionCallback != null)
             {
                 completionCallback(result);
             }
         }
         catch (Exception e)
         {
             if (completionCallback != null)
             {
                 result.Exception = e;
                 completionCallback(result);
             }
             else
             {
                 //log an error in order to make sure this doesn't go unnoticed
                 string msg = "Async file read operation failed silently for file '{0}':\n{1}";
                 msg        = String.Format(msg, fileInfo.FullName, e);
                 Debug.WriteLine(msg);
             }
         }
     });
 }
Exemplo n.º 6
0
        /// <summary>
        /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
        /// which gets the binary contents as a stream as a blocking operation.
        /// Use the methods in <see cref="ContentUtil"/> class for simplified stream
        /// handling.
        /// </summary>
        /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
        /// file's contents.</param>
        /// <param name="fileInfo">Provides meta information about the file to be read.</param>
        /// <param name="destination">A stream to which the file's contents are written.</param>
        /// <param name="autoCloseStream">Whether to automatically close the submitted
        /// <paramref name="destination"/> stream.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
        /// is a null reference.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="destination"/>
        /// is a null reference.</exception>
        public static void ReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream destination, bool autoCloseStream)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (fileInfo == null)
            {
                throw new ArgumentNullException("fileInfo");
            }
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }

            try
            {
                using (Stream stream = provider.ReadFileContents(fileInfo.FullName))
                {
                    stream.WriteTo(destination);
                }
            }
            finally
            {
                if (autoCloseStream)
                {
                    destination.Close();
                }
            }
        }
Exemplo n.º 7
0
		private VirtualFileInfo ConvertFileSystemInfoToVirtualFileInfo(FileSystemInfo FileSystemInfo)
		{
			var VirtualFileInfo = new VirtualFileInfo()
			{
				Path = GetRelativePathFromAbsolute(FileSystemInfo.FullName),
				Exists = FileSystemInfo.Exists,
				LastWriteTimeUtc = FileSystemInfo.LastWriteTimeUtc,
			};

			var FileInfo = FileSystemInfo as FileInfo;
			var DirectoryInfo = FileSystemInfo as DirectoryInfo;

			if (FileInfo != null)
			{
				VirtualFileInfo.Length = FileInfo.Length;
				VirtualFileInfo.Type = VirtualFileType.File;
			}
			else if (DirectoryInfo != null)
			{
				VirtualFileInfo.Length = 0;
				VirtualFileInfo.Type = VirtualFileType.Directory;
			}

			return VirtualFileInfo;
		}
Exemplo n.º 8
0
        private void fileAdded(VirtualFileInfo file)
        {
            String        parentPath = file.DirectoryName;
            DirectoryNode node       = getNodeForPath(file.DirectoryName) as DirectoryNode;

            node.addFileNode(new FileNode(file));
        }
Exemplo n.º 9
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which retrieves the binary contents from a provivder, and writes them into a given file.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="fileInfo">Provides meta information about the file to be read.</param>
 /// <param name="filePath">The file to be created. If a corresponding file already
 /// exists, it will be overwritten.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
 /// is a null reference.</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="filePath"/>
 /// is a null reference.</exception>
 public static void SaveFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, string filePath)
 {
     using (Stream destination = new FileStream(filePath, FileMode.Create, FileAccess.Write))
     {
         ReadFile(provider, fileInfo, destination, true);
     }
 }
Exemplo n.º 10
0
    public static VirtualFileInfo ToFileInfo(this ZipNode node)
    {
      Ensure.ArgumentNotNull(node, "node");

      if(node.IsDirectoryNode)
      {
        string msg = "ZIP entry [{0}] does not represent a file.";
        msg = String.Format(msg, node.FileEntry.FileName);
        throw new InvalidOperationException(msg);
      }

      var fi = new VirtualFileInfo
                               {
                                 Name = Path.GetFileName(node.FullName),
                                 ContentType = ContentUtil.ResolveContentType(Path.GetExtension(node.FullName)),
                               };


      SetCommonProperties(fi, node);
      if (node.FileEntry != null)
      {
        fi.Length = node.FileEntry.UncompressedSize;
      }

      return fi;
    }
Exemplo n.º 11
0
        /// <summary>
        /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
        /// which retrieves the binary contents from a provivder, and writes them into a given file.
        /// This is a non-blocking operation which invokes the submitted <param name="completionCallback" />
        /// once the process has been completed.
        /// </summary>
        /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
        /// file's contents.</param>
        /// <param name="fileInfo">Provides meta information about the file to be read.</param>
        /// <param name="filePath">The file to be created. If a corresponding file already
        /// exists, it will be overwritten.</param>
        /// <param name="completionCallback">Invoked as soon as the operation has been completed,
        /// or aborted. This is an optional parameter, which can be null.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
        /// is a null reference.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="filePath"/>
        /// is a null reference.</exception>
        public static void BeginSaveFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, string filePath,
                                         Action <FileOperationResult> completionCallback)
        {
            Stream destination = new FileStream(filePath, FileMode.Create, FileAccess.Write);

            BeginReadFile(provider, fileInfo, destination, completionCallback);
        }
Exemplo n.º 12
0
        public FileItem ResolveFileResourcePath2(string submittedFilePath, FileSystemTask context)
        {
            if (String.IsNullOrEmpty(submittedFilePath))
            {
                throw new InvalidResourcePathException("An empty or null string is not a valid file path");
            }

            //make sure we operate on absolute paths
            var absolutePath = PathUtil.GetAbsolutePath(submittedFilePath, RootDirectory);

            if (IsRootPath(absolutePath))
            {
                throw new InvalidResourcePathException("Invalid path submitted: " + submittedFilePath);
            }

            var             localFile   = new FileInfo(absolutePath);
            VirtualFileInfo virtualFile = localFile.CreateFileResourceInfo();

            var item = new FileItem(localFile, virtualFile);

            //convert to relative paths if required (also prevents qualified paths in validation exceptions)
            if (UseRelativePaths)
            {
                item.MakePathsRelativeTo(RootDirectory);
            }

            ValidateFileRequestAccess(item, submittedFilePath, context);
            return(item);
        }
Exemplo n.º 13
0
        public void CreateFromString()
        {
            // confirm that full name parts
            // were parsed and set correctly
            string          fullName = @"C:\foo\bar.txt";
            VirtualFileInfo fi       = new VirtualFileInfo(fullName);

            Assert.AreEqual(fullName, fi.FullName);
            Assert.AreEqual("bar.txt", fi.Name);
            Assert.AreEqual(@"C:\foo", fi.DirectoryName);

            // invalid full names should throw an exception
            ArgumentException exception = null;

            try
            {
                fullName = @"bar.txt";
                fi       = new VirtualFileInfo(fullName);
            }
            catch (ArgumentException ex)
            {
                exception = ex;
            }

            Assert.IsNotNull(exception);
        }
Exemplo n.º 14
0
        public static VirtualFileInfo ToFileInfo(this ZipNode node)
        {
            Ensure.ArgumentNotNull(node, "node");

            if (node.IsDirectoryNode)
            {
                string msg = "ZIP entry [{0}] does not represent a file.";
                msg = String.Format(msg, node.FileEntry.FileName);
                throw new InvalidOperationException(msg);
            }

            var fi = new VirtualFileInfo
            {
                Name        = Path.GetFileName(node.FullName),
                ContentType = ContentUtil.ResolveContentType(Path.GetExtension(node.FullName)),
            };


            SetCommonProperties(fi, node);
            if (node.FileEntry != null)
            {
                fi.Length = node.FileEntry.UncompressedSize;
            }

            return(fi);
        }
    public void Initiating_Token_Should_Not_Delete_Existing_File_Yet()
    {
      Token = Uploads.RequestUploadToken(TargetFilePath, true, SourceFile.Length, "");

      Assert.IsTrue(FileSystem.IsFileAvailable(TargetFilePath));
      target = FileSystem.GetFileInfo(TargetFilePath);
      Assert.AreEqual(SourceFile.Length, target.Length);
    }
Exemplo n.º 16
0
        public void Initiating_Token_Should_Not_Delete_Existing_File_Yet()
        {
            Token = Uploads.RequestUploadToken(TargetFilePath, true, SourceFile.Length, "");

            Assert.IsTrue(FileSystem.IsFileAvailable(TargetFilePath));
            target = FileSystem.GetFileInfo(TargetFilePath);
            Assert.AreEqual(SourceFile.Length, target.Length);
        }
    public void Cancelling_Transfer_Before_Writing_Any_Data_Should_Retain_File_That_Would_Have_Overwritten()
    {
      Token = Uploads.RequestUploadToken(TargetFilePath, true, SourceFile.Length, "");
      Uploads.CancelTransfer(Token.TransferId, AbortReason.ClientAbort);

      Assert.IsTrue(FileSystem.IsFileAvailable(TargetFilePath));
      target = FileSystem.GetFileInfo(TargetFilePath);
      Assert.AreEqual(SourceFile.Length, target.Length);
    }
Exemplo n.º 18
0
 protected override void InitInternal()
 {
     illegalFile = new VirtualFileInfo {
         FullName = "a?:<>@*%&/"
     };
     illegalFolder = new VirtualFolderInfo {
         FullName = "a?:<>@*%&/"
     };
 }
Exemplo n.º 19
0
        public void Cancelling_Transfer_Before_Writing_Any_Data_Should_Retain_File_That_Would_Have_Overwritten()
        {
            Token = Uploads.RequestUploadToken(TargetFilePath, true, SourceFile.Length, "");
            Uploads.CancelTransfer(Token.TransferId, AbortReason.ClientAbort);

            Assert.IsTrue(FileSystem.IsFileAvailable(TargetFilePath));
            target = FileSystem.GetFileInfo(TargetFilePath);
            Assert.AreEqual(SourceFile.Length, target.Length);
        }
        public void Submitting_Invalid_File_Uri_Should_Fail()
        {
            VirtualFileInfo file = new VirtualFileInfo();

            file.FullName = "a?:@*%&/";

            provider.GetFileInfo(file.FullName);
            provider.ReadFileContents(file);
        }
Exemplo n.º 21
0
        public void Add(short handle, DosStream stream, VirtualFileInfo fileInfo, bool overwrite = false)
        {
            stream.FileInfo = fileInfo;

            if (fileInfo != null)
            {
                unsafe
                {
                    if (stream.SFTIndex == -1)
                    {
                        if (this.sftFileCount >= this.maxFiles)
                        {
                            throw new InvalidOperationException("Maximum number of open files exceeded.");
                        }

                        stream.SFTIndex = this.sftFileCount;
                        var entry = &this.entries[this.sftFileCount];

                        this.sftFileCount++;

                        entry->RefCount                  = 1;
                        entry->FileOpenMode              = 0;
                        entry->FileAttribute             = fileInfo.DosAttributes;
                        entry->DeviceInfo                = 0;
                        entry->StartingCluster           = 0;
                        entry->FileTime                  = fileInfo.DosModifyTime;
                        entry->FileDate                  = fileInfo.DosModifyDate;
                        entry->FileSize                  = fileInfo.DosLength;
                        entry->CurrentOffset             = 0;
                        entry->RelativeClusterLastAccess = 0;
                        entry->DirectoryEntrySector      = 0;
                        entry->DirectoryEntry            = 0;

                        var fcbName = GetFCBName(fileInfo.Name);
                        for (int i = 0; i < 11; i++)
                        {
                            entry->FileName[i] = (byte)fcbName[i];
                        }
                    }
                    else
                    {
                        var entry = &this.entries[stream.SFTIndex];
                        entry->RefCount++;
                    }
                }
            }

            if (!overwrite)
            {
                this.fileHandles.Add(handle, stream);
            }
            else
            {
                this.fileHandles[handle] = stream;
            }
        }
Exemplo n.º 22
0
        public void CreateFromFileInfo()
        {
            FileInfo        fi  = new FileInfo(@"Props\foo.txt");
            VirtualFileInfo vfi = new VirtualFileInfo(fi);

            Assert.AreEqual(fi.FullName, vfi.FullName);
            Assert.AreEqual(fi.Name, vfi.Name);
            Assert.AreEqual(fi.DirectoryName, vfi.DirectoryName);
            Assert.AreEqual(fi.Length, vfi.Length);
            Assert.AreEqual(fi.CreationTime, vfi.CreationTime);
            Assert.AreEqual(fi.LastWriteTime, vfi.LastWriteTime);
        }
    public void Init()
    {
      provider = new LocalFileSystemProvider();
      FileInfo fi = new FileInfo(FileUtil.CreateTempFilePath("txt"));
      var writer = fi.CreateText();
      writer.WriteLine("hello world.");
      writer.Close();

      sourceFile = fi.CreateFileResourceInfo();
      Assert.IsTrue(fi.Exists);

      targetFile = new FileInfo(FileUtil.CreateTempFilePath("txt"));
    }
    protected override void InitInternal()
    {
      var dir = rootDirectory.GetDirectories().First();;
      targetDir = new DirectoryInfo(Path.Combine(rootDirectory.GetDirectories().Last().FullName, "target"));
      targetDir.Create();

      sourcePath = new FileInfo(Path.Combine(dir.FullName, "foo.bin"));
      File.WriteAllBytes(sourcePath.FullName, new byte[99999]);
      sourcePath.Refresh();
      
      targetPath = new FileInfo(Path.Combine(targetDir.FullName, "bar.bin"));
      original = provider.GetFileInfo(sourcePath.FullName);
    }
        protected VirtualFileInfo GetFileInfoInternal(string virtualFilePath, bool mustExist, out string absolutePath)
        {
            try
            {
                if (String.IsNullOrEmpty(virtualFilePath))
                {
                    VfsLog.Debug("File request without file path received.");
                    throw new ResourceAccessException("An empty or null string is not a valid file path");
                }

                //make sure we operate on absolute paths
                absolutePath = PathUtil.GetAbsolutePath(virtualFilePath, RootDirectory);

                if (IsRootPath(absolutePath))
                {
                    VfsLog.Debug("Blocked file request with path '{0}' (resolves to root directory).", virtualFilePath);
                    throw new ResourceAccessException("Invalid path submitted: " + virtualFilePath);
                }

                var             fi       = new FileInfo(absolutePath);
                VirtualFileInfo fileInfo = fi.CreateFileResourceInfo();

                //convert to relative paths if required (also prevents qualified paths in validation exceptions)
                if (UseRelativePaths)
                {
                    fileInfo.MakePathsRelativeTo(RootDirectory);
                }

                //make sure the user is allowed to access the resource
                ValidateResourceAccess(fileInfo);

                //verify file exists on FS
                if (mustExist)
                {
                    fileInfo.VerifyFileExists(RootDirectory);
                }

                return(fileInfo);
            }
            catch (VfsException)
            {
                //just bubble internal exceptions
                throw;
            }
            catch (Exception e)
            {
                VfsLog.Debug(e, "Could not create file based on path '{0}' with root '{1}'", virtualFilePath,
                             RootDirectory);
                throw new ResourceAccessException("Invalid path submitted: " + virtualFilePath);
            }
        }
        public void Init()
        {
            provider = new LocalFileSystemProvider();
            FileInfo fi     = new FileInfo(FileUtil.CreateTempFilePath("txt"));
            var      writer = fi.CreateText();

            writer.WriteLine("hello world.");
            writer.Close();

            sourceFile = fi.CreateFileResourceInfo();
            Assert.IsTrue(fi.Exists);

            targetFile = new FileInfo(FileUtil.CreateTempFilePath("txt"));
        }
Exemplo n.º 27
0
        public void AzureBlobPakuStrategyUploadTest()
        {
            AzureBlobPakuStrategy strategy = new AzureBlobPakuStrategy();
            AzurePakuConfig       config   = JsonConvert.DeserializeObject <AzurePakuConfig>(File.ReadAllText(@"Props\azure.json"));

            File.WriteAllText("AzureBlobTest.txt", "test file");
            VirtualFileInfo        fi    = new VirtualFileInfo(new FileInfo("AzureBlobTest.txt"));
            List <VirtualFileInfo> files = new List <VirtualFileInfo>()
            {
                fi
            };

            strategy.Upload(config.ConnectionString, config.Container, files);
        }
        protected override void InitInternal()
        {
            var dir = rootDirectory.GetDirectories().First();;

            targetDir = new DirectoryInfo(Path.Combine(rootDirectory.GetDirectories().Last().FullName, "target"));
            targetDir.Create();

            sourcePath = new FileInfo(Path.Combine(dir.FullName, "foo.bin"));
            File.WriteAllBytes(sourcePath.FullName, new byte[99999]);
            sourcePath.Refresh();

            targetPath = new FileInfo(Path.Combine(targetDir.FullName, "bar.bin"));
            original   = provider.GetFileInfo(sourcePath.FullName);
        }
Exemplo n.º 29
0
 private void addFile(VirtualFileInfo fileInfo)
 {
     if (!fileInfo.Name.EndsWith("~") && !fileInfo.DirectoryName.Contains(".svn") && !isIgnoredFile(fileInfo.FullName) && !isIgnoreDirectory(fileInfo.DirectoryName))
     {
         //Make sure the file does not already exist in the list.
         foreach (VirtualFileInfo existingInfo in files)
         {
             if (existingInfo.RealLocation == fileInfo.RealLocation)
             {
                 return;
             }
         }
         files.Add(fileInfo);
     }
 }
        public void Submitting_Root_Path_Should_Fail()
        {
            var dir = TestUtil.CreateTestDirectory();

            using (new Guard(() => dir.Delete(true)))
            {
                provider = new LocalFileSystemProvider(dir, false);
                provider.ReadFileContents(sourceFile);
            }

            VirtualFileInfo file = new VirtualFileInfo();

            file.FullName = provider.GetFileSystemRoot().FullName;
            provider.ReadFileContents(file);
        }
Exemplo n.º 31
0
        protected internal void pushFixedFileInfo(String file, IntPtr ogreFileList, IntPtr archive)
        {
            VirtualFileInfo archiveInfo   = vfs.getFileInfo(file);
            String          fixedFilename = baseName.Length > 0 ? archiveInfo.FullName.Replace(baseName, "") : archiveInfo.FullName;

            if (fixedFilename.StartsWith("/"))
            {
                fixedFilename = fixedFilename.Substring(1);
            }
            String fixedPath = baseName.Length > 0 ? archiveInfo.DirectoryName.Replace(baseName, "") : archiveInfo.DirectoryName;

            if (fixedPath.StartsWith("/"))
            {
                fixedPath = fixedPath.Substring(1);
            }
            OgreFileInfoList_push_back(ogreFileList, archive, new IntPtr(archiveInfo.CompressedSize), new IntPtr(archiveInfo.UncompressedSize), archiveInfo.Name, fixedFilename, fixedPath);
        }
Exemplo n.º 32
0
        public void initialize(StandaloneController standaloneController)
        {
            TimelineController = standaloneController.TimelineController;
            AtlasPluginManager = standaloneController.AtlasPluginManager;
            MvcCore            = standaloneController.MvcCore;
            GuiManager         = standaloneController.GUIManager;

            AnatomyTaskManager anatomyTasks = standaloneController.AnatomyTaskManager;

            foreach (DDPluginTask task in tasks)
            {
                task._setPlugin(this);
                anatomyTasks.addTask(task, task.TaggedAnatomy);
            }

            //Load sequences
            if (!String.IsNullOrEmpty(SequencesDirectory))
            {
                String            fullSequencesDirectory = Path.Combine(PluginRootFolder, SequencesDirectory);
                VirtualFileSystem archive = VirtualFileSystem.Instance;
                if (archive.exists(fullSequencesDirectory))
                {
                    loadedSequences = new List <VirtualFSMovementSequenceInfo>();
                    MovementSequenceController movementSequenceController = standaloneController.MovementSequenceController;
                    foreach (String directory in archive.listDirectories(fullSequencesDirectory, false, false))
                    {
                        String groupName = archive.getFileInfo(directory).Name;
                        foreach (String file in archive.listFiles(directory, false))
                        {
                            VirtualFileInfo fileInfo = archive.getFileInfo(file);
                            String          fileName = fileInfo.Name;
                            if (fileName.EndsWith(".seq"))
                            {
                                VirtualFSMovementSequenceInfo info = new VirtualFSMovementSequenceInfo();
                                info.GroupName = groupName;
                                info.Name      = fileName.Substring(0, fileName.Length - 4);
                                info.FileName  = fileInfo.FullName;
                                movementSequenceController.addMovementSequence(info.GroupName, info);
                                loadedSequences.Add(info);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Checks whether the <see cref="VirtualResourceInfo.FullName"/>
        /// matches an existing file on the local file system. If that's
        /// not the case, a <see cref="VirtualResourceNotFoundException"/> is
        /// thrown.
        /// </summary>
        /// <param name="file">The file to check.</param>
        /// <param name="rootDirectory">The used root directory, if any, which is used
        /// to resolve relative paths.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="file"/>
        /// is a null reference.</exception>
        /// <exception cref="VirtualResourceNotFoundException">If the submitted
        /// file's <see cref="VirtualResourceInfo.FullName"/> does not link to
        /// an existing file.</exception>
        internal static void VerifyFileExists(this VirtualFileInfo file, DirectoryInfo rootDirectory)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            string path = PathUtil.GetAbsolutePath(file.FullName, rootDirectory);

            if (String.IsNullOrEmpty(path) || !File.Exists(path))
            {
                string msg = String.Format("File not found on local file system at '{0}'", file.FullName);
                throw new VirtualResourceNotFoundException(msg)
                      {
                          Resource = file
                      };
            }
        }
Exemplo n.º 34
0
        public void AzureBlobPakuStrategyTest()
        {
            // create test files
            List <VirtualFileInfo> files = new List <VirtualFileInfo>();

            for (int i = 0; i < 3; i++)
            {
                string fname = $"AzureBlobTest_{i}.txt";
                File.WriteAllText(fname, $"test file {i}");
                VirtualFileInfo fi = new VirtualFileInfo(new FileInfo(fname));
                files.Add(fi);
            }

            AzureBlobPakuStrategy strategy = new AzureBlobPakuStrategy();
            PakuResult            result   = strategy.Eat(new DirectoryInfo(Directory.GetCurrentDirectory()), files, @"Props\azure.json");

            Assert.IsTrue(result.Success);
            Assert.AreEqual(3, result.RemovedFiles.Count);
        }
Exemplo n.º 35
0
        public override MovementSequence loadSequence(XmlSaver xmlSaver)
        {
            MovementSequence loadingSequence = null;

            try
            {
                VirtualFileSystem archive = VirtualFileSystem.Instance;
                using (XmlTextReader xmlReader = new XmlTextReader(archive.openStream(FileName, FileMode.Open, FileAccess.Read)))
                {
                    loadingSequence = xmlSaver.restoreObject(xmlReader) as MovementSequence;
                    VirtualFileInfo fileInfo = archive.getFileInfo(FileName);
                    loadingSequence.Name = fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
                }
            }
            catch (Exception e)
            {
                Log.Error("Could not read muscle sequence {0}.\nReason: {1}.", FileName, e.Message);
            }
            return(loadingSequence);
        }
Exemplo n.º 36
0
        public void Creating_Item_From_Existing_File_Should_Include_All_Information()
        {
            FileInfo fi = new FileInfo(GetType().Assembly.Location);

            Assert.IsTrue(fi.Exists);

            VirtualFileInfo item = fi.CreateFileResourceInfo();

            Assert.AreEqual(fi.Name, item.Name);
            Assert.AreEqual(fi.FullName, item.FullName);

            //timestamps should match file info
            Assert.AreEqual((DateTimeOffset)fi.CreationTime, item.CreationTime);
            Assert.AreEqual((DateTimeOffset)fi.LastAccessTime, item.LastAccessTime);
            Assert.AreEqual((DateTimeOffset)fi.LastWriteTime, item.LastWriteTime);

            //length should match file
            Assert.AreNotEqual(0, item.Length);
            Assert.AreEqual(fi.Length, item.Length);
        }
        /// <summary>
        /// Resolves the parent folder for a virtual resource.
        /// </summary>
        /// <param name="child">The child file or folder.</param>
        /// <returns>The parent folder info.</returns>
        private VirtualFolderInfo GetParentInternal(VirtualResourceInfo child)
        {
            if (child == null)
            {
                throw new ArgumentNullException("child");
            }

            string path = PathUtil.GetAbsolutePath(child.FullName, RootDirectory);

            if (IsRootPath(path))
            {
                //only log the request for the root's parent - do not include that
                //info in an exception in case we're hiding path information
                string msg = "Error while requesting parent of resource {0} - the folder itself already is the root.";
                VfsLog.Error(msg, child.FullName);

                //create exception with a relative path, if required
                string exceptionPath = UseRelativePaths ? PathUtil.RelativeRootPrefix : child.FullName;
                msg = String.Format(msg, exceptionPath);
                throw new ResourceAccessException(msg);
            }

            //make sure the processed directory exists
            VirtualFolderInfo folder = child as VirtualFolderInfo;

            if (folder != null)
            {
                folder.VerifyDirectoryExists(RootDirectory);
            }
            else
            {
                VirtualFileInfo file = (VirtualFileInfo)child;
                file.VerifyFileExists(RootDirectory);
            }

            //get the path of the parent (returned value may be null!)
            string parentPath = Path.GetDirectoryName(path);

            //get folder info
            return(GetFolderInfo(parentPath));
        }
Exemplo n.º 38
0
        private void UpdateHibernateConfig()
        {
            var file = new VirtualFileInfo(string.Format(@"\Webroot\{0}\hibernate.xml", _context.Portal.PortalAlias));

            if (_context.Package != null && _context.Package.Entities.Count > 0 && file.Exists)
            {
                XmlSerializer serializer = new XmlSerializer(typeof (HibernateConfiguration));
                HibernateConfiguration config;

                using (Stream stream = new VirtualFileStream(file, VirtualFileMode.Open))
                {
                    config = (HibernateConfiguration) serializer.Deserialize(stream);
                }

                bool exists = CollectionUtils.Contains(
                    config.MappingAssemblies,
                    delegate(string item)
                        {
                            return (StringUtils.CaseInsensitiveEquals(item, _assemblyName));
                        });

                if (!exists)
                {
                    config.MappingAssemblies.Add(_assemblyName);

                    using (Stream stream = new VirtualFileStream(file, VirtualFileMode.Create))
                    {
                        serializer.Serialize(stream, config);
                    }
                }

                FetchLinkedFile(_context.Portal.SupportFiles, @"SupportFiles\hibernate.xml");
            }
        }
Exemplo n.º 39
0
 /// <summary>
 /// Gets the MD5 file hash of a given file on the file system.
 /// </summary>
 protected string GetFileHash(VirtualFileInfo file)
 {
   var token = FileSystem.DownloadTransfers.RequestDownloadToken(file.FullName, true);
   FileSystem.DownloadTransfers.CancelTransfer(token.TransferId, AbortReason.ClientAbort);
   return token.Md5FileHash;
 }
    protected override void InitInternal()
    {

      illegalFile = new VirtualFileInfo { FullName = "a?:<>@*%&/" };
      illegalFolder = new VirtualFolderInfo { FullName = "a?:<>@*%&/" };
    }
    public void Submitting_Root_Path_Should_Fail()
    {
      var dir = TestUtil.CreateTestDirectory();
      using (new Guard(() => dir.Delete(true)))
      {
        provider = new LocalFileSystemProvider(dir, false);
        provider.ReadFileContents(sourceFile);
      }

      VirtualFileInfo file = new VirtualFileInfo();
      file.FullName = provider.GetFileSystemRoot().FullName;
      provider.ReadFileContents(file);
    }
Exemplo n.º 42
0
 /// <summary>
 /// Copies a given file to a new destination.
 /// </summary>
 /// <param name="file">Represents the resource in the file system.</param>
 /// <param name="destinationPath">The new path of the resource. Can be another name
 /// for the resource itself.</param>
 /// <returns>A <see cref="VirtualFileInfo"/> object that represents the new
 /// file in the file system.</returns>
 /// <exception cref="ResourceAccessException">In case of invalid or prohibited
 /// resource access, or if the operation is not possible (e.g. a resource being
 /// moved/copied to itself).</exception>
 /// <exception cref="VirtualResourceNotFoundException">If the resource that
 /// should be moved does not exist in the file system.</exception>
 /// <exception cref="ResourceOverwriteException">If a resource that matches the
 /// submitted <paramref name="destinationPath"/> already exists.</exception>
 public VirtualFileInfo CopyFile(VirtualFileInfo file, string destinationPath)
 {
   return FaultUtil.SecureFunc(FileSystemTask.FileCopyRequest, () => Decorated.CopyFile(file, destinationPath));
 }
Exemplo n.º 43
0
 public ZipFileItem(ZipNode node, VirtualFileInfo virtualFile)
 {
   Node = node;
   ResourceInfo = virtualFile;
 }
Exemplo n.º 44
0
    /// <summary>
    /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
    /// which gets the binary contents as a stream as a blocking operation.
    /// Use the methods in <see cref="ContentUtil"/> class for simplified stream
    /// handling.
    /// </summary>
    /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
    /// file's contents.</param>
    /// <param name="fileInfo">Provides meta information about the file to be read.</param>
    /// <param name="destination">A stream to which the file's contents are written.</param>
    /// <param name="autoCloseStream">Whether to automatically close the submitted
    /// <paramref name="destination"/> stream.</param>
    /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
    /// is a null reference.</exception>
    /// <exception cref="ArgumentNullException">If <paramref name="destination"/>
    /// is a null reference.</exception>
    public static void ReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream destination, bool autoCloseStream)
    {
      if (provider == null) throw new ArgumentNullException("provider");
      if (fileInfo == null) throw new ArgumentNullException("fileInfo");
      if (destination == null) throw new ArgumentNullException("destination");

      try
      {
        using (Stream stream = provider.ReadFileContents(fileInfo.FullName))
        {
          stream.WriteTo(destination);
        }
      }
      finally
      {
        if(autoCloseStream)
        {
          destination.Close();
        }
      }
    }
Exemplo n.º 45
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which writes the data of a given file to the submitted output stream as a non-blocking
 /// operation, and invokes the submitted delegate once the process has been completed.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="fileInfo">Provides meta information about the file to be read.</param>
 /// <param name="output">A stream to which the file's contents are written. The stream will
 /// be automatically closed as soon as the operations finishes.</param>
 /// <param name="completionCallback">Invoked as soon as the operation has been completed,
 /// or aborted. This is an optional parameter, which can be null.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
 /// is a null reference.</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="output"/>
 /// is a null reference.</exception>
 public static void BeginReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream output,
                                  Action<FileOperationResult> completionCallback)
 {
   ThreadPool.QueueUserWorkItem(delegate
                                  {
                                    FileOperationResult result = new FileOperationResult(fileInfo);
                                    try
                                    {
                                      ReadFile(provider, fileInfo, output, true);
                                      if (completionCallback != null) completionCallback(result);
                                    }
                                    catch (Exception e)
                                    {
                                      if (completionCallback != null)
                                      {
                                        result.Exception = e;
                                        completionCallback(result);
                                      }
                                      else
                                      {
                                        //log an error in order to make sure this doesn't go unnoticed
                                        string msg = "Async file read operation failed silently for file '{0}':\n{1}";
                                        msg = String.Format(msg, fileInfo.FullName, e);
                                        Debug.WriteLine(msg);
                                      }
                                    }
                                  });
 }
Exemplo n.º 46
0
 /// <summary>
 /// Gets the parent folder of a given file system resource.
 /// </summary>
 /// <param name="child">An arbitrary file resource of the file system.</param>
 /// <returns>The parent of the file.</returns>
 /// <exception cref="ArgumentNullException">If <paramref name="child"/>
 /// is a null reference.</exception>
 /// <exception cref="VirtualResourceNotFoundException">If the file that is represented
 /// by <paramref name="child"/> does not exist in the file system.</exception>
 /// <exception cref="ResourceAccessException">In case of an invalid or prohibited
 /// resource access.</exception>
 public VirtualFolderInfo GetFileParent(VirtualFileInfo child)
 {
   return FaultUtil.SecureFunc(FileSystemTask.FileParentRequest, () => Decorated.GetFileParent(child));
 }
Exemplo n.º 47
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which retrieves the binary contents from a provivder, and writes them into a given file.
 /// This is a non-blocking operation which invokes the submitted <param name="completionCallback" />
 /// once the process has been completed.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="fileInfo">Provides meta information about the file to be read.</param>
 /// <param name="filePath">The file to be created. If a corresponding file already
 /// exists, it will be overwritten.</param>
 /// <param name="completionCallback">Invoked as soon as the operation has been completed,
 /// or aborted. This is an optional parameter, which can be null.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/>
 /// is a null reference.</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="filePath"/>
 /// is a null reference.</exception>
 public static void BeginSaveFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, string filePath,
                                  Action<FileOperationResult> completionCallback)
 {
   Stream destination = new FileStream(filePath, FileMode.Create, FileAccess.Write);
   BeginReadFile(provider, fileInfo, destination, completionCallback);
 }
    public void Saving_File_Asynchronously_With_Path_Of_Existing_File_Should_Return_Results()
    {
      //create temp file
      Assert.IsFalse(targetFile.Exists);
      File.WriteAllBytes(targetFile.FullName, new byte[1024 * 1024 * 20]);

      //run async operation with invalid file path
      FileOperationResult result = null;
      var invalidSource = new VirtualFileInfo {FullName = FileUtil.GetUniqueFileName("VFS_INVALID")};
      provider.BeginSaveFile(invalidSource, targetFile.FullName, c => result = c);
      while (result == null) Thread.CurrentThread.Join(500);

      Assert.IsFalse(result.IsSuccess);
      Assert.IsInstanceOf<VfsException>(result.Exception);
      

      //run async operation with valid data
      result = null;

      provider.BeginSaveFile(sourceFile, targetFile.FullName, c => result = c);

      while (result == null)
      {
        Console.Out.WriteLine("waiting...");
        Thread.CurrentThread.Join(1000);
      }

      Assert.IsTrue(result.IsSuccess, result.IsSuccess ? "" : result.Exception.ToString());
      Assert.AreEqual(FileUtil.ComputeFingerPrint(sourceFile.FullName), targetFile.ComputeFingerPrint());
    }
Exemplo n.º 49
0
 public FileItem(FileInfo localFile, VirtualFileInfo virtualFile)
 {
   LocalFile = localFile;
   ResourceInfo = virtualFile; 
 }
 protected override void InitInternal()
 {
   base.InitInternal();
   target = FileSystem.WriteFile(SourceFile.FullName, TargetFilePath, false);
   Assert.IsTrue(FileSystem.IsFileAvailable(TargetFilePath));
 }
    public void Submitting_Invalid_File_Uri_Should_Fail()
    {
      VirtualFileInfo file = new VirtualFileInfo();
      file.FullName = "a?:@*%&/";

      provider.GetFileInfo(file.FullName);
      provider.ReadFileContents(file);
    }
Exemplo n.º 52
0
 /// <summary>
 /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances,
 /// which writes the data of a given file to the submitted output stream as a non-blocking
 /// operation, and invokes the submitted delegate once the process has been completed.
 /// </summary>
 /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the
 /// file's contents.</param>
 /// <param name="localFilePath">The path of the file to be uploaded.</param>
 /// <param name="destinationPath">The path of the file to be created on the file system.</param>
 /// <param name="overwrite">Whether an existing file should be overwritten
 /// or not. If this parameter is false and the file already exists, a
 /// <see cref="ResourceOverwriteException"/> is thrown.</param>
 /// <param name="completionCallback">Invoked as soon as the operation has been completed,
 /// or aborted. This is an optional parameter, which can be null.</param>
 public static void BeginWriteFile(this IFileSystemProvider provider, string localFilePath, string destinationPath, bool overwrite,
                                  Action<FileOperationResult> completionCallback)
 {
   ThreadPool.QueueUserWorkItem(delegate
   {
     try
     {
       var fileInfo = WriteFile(provider, localFilePath, destinationPath, overwrite);
       if (completionCallback != null)
       {
         FileOperationResult result = new FileOperationResult(fileInfo);
         completionCallback(result);
       }
     }
     catch (Exception e)
     {
       if (completionCallback != null)
       {
         VirtualFileInfo fileInfo = new VirtualFileInfo();
         fileInfo.FullName = destinationPath;
         FileOperationResult result = new FileOperationResult(fileInfo) {Exception = e};
         completionCallback(result);
       }
       else
       {
         //log an error in order to make sure this doesn't go unnoticed
         string msg = "Async file write operation failed silently for file '{0}':\n{1}";
         msg = String.Format(msg, destinationPath, e);
         Debug.WriteLine(msg);
       }
     }
   });
 }