public static void ToFile(IBitmapWrapper bitmap, string filename)
        {
            Stream stream = FileStreamFactory.New(filename, "rw");

            ToStream(bitmap, stream);
            stream.Dispose();
        }
        public void CreateReadOnlyShared_ShouldReturnUnwritableFileStream()
        {
            var factory = new FileStreamFactory();

            var result = factory.CreateReadOnlyShared(Paths.SampleFile);

            Assert.False(result.CanWrite, "The returned stream was writable.");
        }
        public void CreateWriteOnlyShared_ShouldReturnFileStream()
        {
            var factory = new FileStreamFactory();

            var result = factory.CreateWriteOnlyShared(Paths.SampleFile);

            Assert.IsType <FileStream>(result);
        }
        public static object FromFile(string filename)
        {
            var stream = FileStreamFactory.New(filename, "r");
            var img    = FromStream(stream);

            stream.Dispose();
            return(img);
        }
        public void Setup()
        {
            tempDirectoryName = "temp" + new Random().Next();

            Directory.CreateDirectory(tempDirectoryName);

            logger            = new Mock <ILog>();
            fileStreamFactory = new FileStreamFactory(tempDirectoryName, logger.Object);
        }
Beispiel #6
0
        void OpenFile()
        {
            if (!File.Exists(_filename))
            {
                throw new Exception("file doesn't exists!");
            }

            _filePtr        = FileStreamFactory.CreateFileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, FileStreamBufferLength);
            _processedBytes = 0;
        }
        public void FileAccess_SetFileAccessProperty_FileAccessPropertyIsSet()
        {
            var fileAccess = FileAccess.Read;

            var factory = new FileStreamFactory();

            factory.FileAccess = fileAccess;

            Assert.AreEqual(fileAccess, factory.FileAccess);
        }
        public void Create_FilePathIsNotSet_ExceptionIsThrown()
        {
            var fileMode   = FileMode.Open;
            var fileAccess = FileAccess.Read;
            var fileShare  = FileShare.Read;

            var factory = new FileStreamFactory(null, fileMode, fileAccess, fileShare);

            factory.Create();
        }
        public void FileMode_SetFileModeProperty_FileModePropertyIsSet()
        {
            var fileMode = FileMode.Open;

            var factory = new FileStreamFactory();

            factory.FileMode = fileMode;

            Assert.AreEqual(fileMode, factory.FileMode);
        }
        public void FilePath_SetFilePathProperty_FilePathPropertyIsSet()
        {
            var filePath = "FilePath";

            var factory = new FileStreamFactory();

            factory.FilePath = filePath;

            Assert.AreEqual(filePath, factory.FilePath);
        }
        public void FileShare_SetFileShareProperty_FileSharePropertyIsSet()
        {
            var fileShare = FileShare.Read;

            var factory = new FileStreamFactory();

            factory.FileShare = fileShare;

            Assert.AreEqual(fileShare, factory.FileShare);
        }
        public void Correctly_Constructs_Read_File_Stream()
        {
            writeSampleFile();

            IFileStreamFactory fileStreamFactory = new FileStreamFactory();

            using (Stream stream = fileStreamFactory.ConstructReadFileStream("test.txt"))
            {
                Assert.That(stream.Length, Is.EqualTo(10));
            }
        }
Beispiel #13
0
        public void WhenCreatingAndOpeningFileShouldNotThrow()
        {
            var fileStreamFactory = new FileStreamFactory();
            var createdStream     = fileStreamFactory.CreateFile("testfile.test");
            var streamWriter      = new StreamWriter(createdStream);

            streamWriter.Write("blah");
            streamWriter.Flush();
            createdStream.Close();

            Assert.NotNull(fileStreamFactory.OpenFile("testfile.test"));
        }
Beispiel #14
0
        private static byte[][] ReadLeafs(HashAlgorithm tg, string filePath, long start, long end)
        {
            using (ThreadUtility.EnterBackgroundProcessingMode())
                using (var threadFilePtr = FileStreamFactory.CreateFileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024))
                {
                    var threadFileBlock = new FileBlock(start, end);
                    var LeafSize        = 1024;
                    var DataBlockSize   = LeafSize * 1024;
                    var data            = new byte[LeafSize + 1];

                    var totalLeafs = threadFileBlock.Length / LeafSize + threadFileBlock.Length % LeafSize > 0 ? 1 : 0;

                    var result = new byte[totalLeafs][];

                    threadFilePtr.Position = threadFileBlock.Start;

                    while (threadFilePtr.Position < threadFileBlock.End)
                    {
                        var leafIndex = (int)((threadFilePtr.Position - start) / 1024);

                        var dataBlock = new byte[Math.Min(threadFileBlock.End - threadFilePtr.Position, DataBlockSize)];

                        threadFilePtr.Read(dataBlock, 0, dataBlock.Length); //read block

                        var blockLeafs = dataBlock.Length / LeafSize;

                        int i;
                        for (i = 0; i < blockLeafs; i++)
                        {
                            Buffer.BlockCopy(dataBlock, i * LeafSize, data, 1, LeafSize);

                            tg.Initialize();
                            result[leafIndex++] = tg.ComputeHash(data);
                        }

                        if (i * LeafSize < dataBlock.Length)
                        {
                            data    = new byte[dataBlock.Length - blockLeafs * LeafSize + 1];
                            data[0] = LeafHash;

                            Buffer.BlockCopy(dataBlock, blockLeafs * LeafSize, data, 1, (data.Length - 1));

                            tg.Initialize();
                            result[leafIndex] = tg.ComputeHash(data);

                            data    = new byte[LeafSize + 1];
                            data[0] = LeafHash;
                        }
                    }
                    return(result);
                }
        }
        public void Constructor_AllParametersPassed_AllPropertiesAreSet()
        {
            var filePath   = "FilePath";
            var fileMode   = FileMode.Open;
            var fileAccess = FileAccess.Read;
            var fileShare  = FileShare.Read;

            var factory = new FileStreamFactory(filePath, fileMode, fileAccess, fileShare);

            Assert.AreEqual(filePath, factory.FilePath);
            Assert.AreEqual(fileMode, factory.FileMode);
            Assert.AreEqual(fileAccess, factory.FileAccess);
            Assert.AreEqual(fileShare, factory.FileShare);
        }
Beispiel #16
0
        void ProcessLeafs(object threadId)
        {
            using (LowPriority ? ThreadUtility.EnterBackgroundProcessingMode() : null)
                using (var threadFilePtr = FileStreamFactory.CreateFileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, FileStreamBufferLength))
                {
                    var threadFileBlock = _fileParts[(int)threadId];
                    var tg   = new T();
                    var data = new byte[LeafSize + 1];

                    threadFilePtr.Position = threadFileBlock.Start;

                    var dataBlock = new byte[DataBlockSize];

                    while (threadFilePtr.Position < threadFileBlock.End)
                    {
                        var leafIndex = (int)(threadFilePtr.Position / 1024);

                        var dataBlockSize = (int)Math.Min(threadFileBlock.End - threadFilePtr.Position, DataBlockSize);

                        threadFilePtr.Read(dataBlock, 0, dataBlockSize); //read block

                        Interlocked.Add(ref _processedBytes, dataBlockSize);

                        var blockLeafs = dataBlockSize / 1024;

                        int i;
                        for (i = 0; i < blockLeafs; i++)
                        {
                            Buffer.BlockCopy(dataBlock, i * LeafSize, data, 1, LeafSize);

                            tg.Initialize();
                            TTH[0][leafIndex++] = tg.ComputeHash(data);
                        }

                        if (i * LeafSize < dataBlockSize)
                        {
                            data    = new byte[dataBlockSize - blockLeafs * LeafSize + 1];
                            data[0] = LeafHash;

                            Buffer.BlockCopy(dataBlock, blockLeafs * LeafSize, data, 1, (data.Length - 1));

                            tg.Initialize();
                            TTH[0][leafIndex] = tg.ComputeHash(data);

                            data    = new byte[LeafSize + 1];
                            data[0] = LeafHash;
                        }
                    }
                }
        }
            /// <summary>
            /// Called to send a specific length of bytes to a server identified by serverKey.  The transfer
            /// is a blocking call and returns on success or raises an exception.  If Abort() is called durring
            /// the transfer, or if a ProgressChanged event handler raises the OperationCanceledException, the
            /// transfer is silently terminated and the method will return false.
            /// </summary>
            /// <param name="location">A string of up to 1024 bytes in length</param>
            /// <param name="filename">The name of the file to write to</param>
            /// <returns>True if the file was successfully received by the server</returns>
            public bool Download(string location, string filename)
            {
                FileStreamFactory file = new FileStreamFactory(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

                using (TempFile temp = TempFile.Attach(filename))
                    using (StreamCache cache = new StreamCache(file, LimitThreads))
                    {
                        temp.Length = 0;
                        if (Download(location, cache))
                        {
                            temp.Detatch();
                            return(true);
                        }
                    }
                return(false);
            }
Beispiel #18
0
        private async Task <long> InternalCopyChunk(Stream stream, long filePos, int bytesRequired)
        {
            if (_fileStream == null)
            {
                FileStream fs;
                using (new PerfLimit("Slow open " + Content.SystemPath, 4000))
                {
                    fs = FileStreamFactory.CreateFileStream(SystemPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite,
                                                            FileStreamReadBufferSize, FileOptions.Asynchronous);
                }

                lock (_syncRoot)
                {
                    if (_isDisposed)
                    {
                        fs.Dispose();
                        return(0);
                    }
                    _fileStream = fs;
                }

                Interlocked.Increment(ref _fileStreamsCount);
            }

            _fileStream.Position = filePos;

            long readSoFar = 0L;
            var  buffer    = new byte[FileStreamReadBufferSize];

            do
            {
                var toRead  = Math.Min(bytesRequired - readSoFar, buffer.Length);
                var readNow = await _fileStream.ReadAsync(buffer, 0, (int)toRead).ConfigureAwait(false);

                if (readNow == 0)
                {
                    break; // End of stream
                }
                await stream.WriteAsync(buffer, 0, readNow).ConfigureAwait(false);

                readSoFar += readNow;
                Interlocked.Add(ref _uploadedBytes, readNow);
            } while (readSoFar < bytesRequired);
            return(readSoFar);
        }
        public void Create_OpenExistingFile_StreamIsReturned()
        {
            var filePath   = this.FilePath;
            var fileMode   = FileMode.Open;
            var fileAccess = FileAccess.Read;
            var fileShare  = FileShare.Read;

            var factory = new FileStreamFactory(filePath, fileMode, fileAccess, fileShare);

            using (var file = File.Create(filePath))
            {
            }

            using (var stream = factory.Create())
            {
                Assert.IsInstanceOfType(stream, typeof(FileStream));
            }
        }
        public void Correctly_Constructs_Write_File_Stream()
        {
            deleteTestFile();

            IFileStreamFactory fileStreamFactory = new FileStreamFactory();

            using (Stream stream = fileStreamFactory.ConstructWriteFileStream("test.txt"))
            {
                FileStream fileStream = (FileStream)stream;
                fileStream.Write(new byte[] { 7, 9, 11 }, 0, 3);
            }

            using (Stream stream = fileStreamFactory.ConstructReadFileStream("test.txt"))
            {
                byte[] fileContents = new byte[3];
                Assert.That(stream.Read(fileContents, 0, 3), Is.EqualTo(3));
                Assert.That(fileContents, Is.EqualTo(new byte[] { 7, 9, 11 }));
            }
        }
 public void TestFileStreamInvalidFileShare()
 {
     using (TempFile tempFile = new TempFile())
     {
         FileStreamFactory factory = new FileStreamFactory(tempFile.TempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
         using (factory.Create())
         {
             factory.Create().Dispose();
             Assert.Fail();
         }
     }
 }
 public void TestFileStreamInvalidAccessWithMode()
 {
     using (TempFile tempFile = new TempFile())
     {
         FileStreamFactory factory = new FileStreamFactory(tempFile.TempPath, FileMode.Create, FileAccess.Read);
         Assert.AreEqual(tempFile.TempPath, factory.FileName);
         factory.Create().Dispose();
         Assert.Fail();
     }
 }
 public void TestFileStreamInvalidBufferSize()
 {
     using (TempFile tempFile = new TempFile())
     {
         FileStreamFactory factory = new FileStreamFactory(tempFile.TempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0);
         Assert.AreEqual(tempFile.TempPath, factory.FileName);
         factory.Create().Dispose();
         Assert.Fail();
     }
 }
 public void TestFileStreamFactoryCreateABunch()
 {
     using (TempFile tempFile = new TempFile())
     {
         FileStreamFactory factory = new FileStreamFactory(tempFile.TempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
         using (DisposingList<Stream> open = new DisposingList<Stream>())
         {
             for( int i = 0; i < 50; i++ )
                 open.Add(factory.Create());
         }
     }
 }
 public void TestFileStreamFactoryReturnsFileStream()
 {
     using(TempFile tempFile = new TempFile())
     {
         FileStreamFactory factory = new FileStreamFactory(tempFile.TempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.Asynchronous);
         Assert.AreEqual(tempFile.TempPath, factory.FileName);
         using (FileStream s = (FileStream)factory.Create())
             Assert.IsTrue(s.CanRead && s.CanWrite && s.IsAsync);
     }
 }
Beispiel #26
0
 /// <summary> Opens the file named 'fname' for writing the bit stream, using the 'he'
 /// header encoder. The magic number is written to the bit
 /// stream. Normally, the header encoder must be empty (i.e. no data has
 /// been written to it yet). A BufferedOutputStream is used on top of the
 /// file to increase throughput, the length of the buffer is DEF_BUF_LEN.
 ///
 /// </summary>
 /// <param name="fname">The name of file where to write the bit stream
 ///
 /// </param>
 /// <param name="mb">The maximum number of bytes that can be written to the bit
 /// stream.
 ///
 /// </param>
 /// <param name="encSpec">The encoder's specifications
 ///
 /// </param>
 /// <exception cref="IOException">If an error occurs while trying to open the file
 /// for writing or while writing the magic number.
 ///
 /// </exception>
 public FileCodestreamWriter(System.String fname, int mb) : base(mb)
 {
     //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'"
     out_Renamed = FileStreamFactory.New(fname, "rw");
     initSOP_EPHArrays();
 }
 /// <summary>
 /// Called to send a specific length of bytes to a server identified by serverKey.  The transfer
 /// is a blocking call and returns on success or raises an exception.  If Abort() is called durring
 /// the transfer, or if a ProgressChanged event handler raises the OperationCanceledException, the
 /// transfer is silently terminated and the method will return false.
 /// </summary>
 /// <param name="location">A string of up to 1024 bytes in length</param>
 /// <param name="filename">The name of the file to write to</param>
 /// <returns>True if the file was successfully received by the server</returns>
 public bool Download(string location, string filename)
 {
     FileStreamFactory file = new FileStreamFactory(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     using (TempFile temp = TempFile.Attach(filename))
     using (StreamCache cache = new StreamCache(file, LimitThreads))
     {
         temp.Length = 0;
         if (Download(location, cache))
         {
             temp.Detatch();
             return true;
         }
     }
     return false;
 }