Exemple #1
0
 public void Write(Stream stream)
 {
     using (var fs = File.OpenWrite())
     {
         stream.WriteTo(fs);
     }
 }
Exemple #2
0
        public override void Store(Stream stream, FileSystemObject fso)
        {
            CreateFolder(fso.FolderName);

            using (var fs = new FileStream(fso.FullName, FileMode.Create, FileAccess.Write))
            {
                stream.WriteTo(fs);
            }
        }
 public byte[] Compress(Stream inputStream)
 {
     using (var outputStream = new MemoryStream())
         using (var gzipStream = new GZipStream(outputStream, CompressionMode.Compress))
         {
             inputStream.WriteTo(gzipStream);
             return(outputStream.ToArray());
         }
 }
Exemple #4
0
        public void WriteFile(string filePath, Stream stream)
        {
            var realFilePath = RootDir.RealPath.CombineWith(filePath);

            EnsureDirectory(Path.GetDirectoryName(realFilePath));
            using (var fs = File.Open(realFilePath, FileMode.Create, FileAccess.Write))
            {
                stream.WriteTo(fs);
            }
        }
Exemple #5
0
        public void AppendFile(string filePath, Stream stream)
        {
            var realFilePath = RootDir.RealPath.CombineWith(filePath);

            EnsureDirectory(Path.GetDirectoryName(realFilePath));
            using (var fs = new FileStream(realFilePath, FileMode.Append))
            {
                stream.WriteTo(fs);
            }
        }
Exemple #6
0
            public void WriteTo(Stream responseStream)
            {
                if (_responseStream == null)
                {
                    return;
                }

                _responseStream.WriteTo(responseStream);
                responseStream.Flush();
            }
Exemple #7
0
        /// <summary>
        /// 将流内容复制到 <see cref="MemoryStream"/> 对象中。
        /// </summary>
        /// <param name="stream">流对象。</param>
        /// <returns></returns>
        public static MemoryStream CopyToMemory(this Stream stream)
        {
            var memoryStream = new MemoryStream();

#if !N35
            stream.CopyTo(memoryStream);
#else
            stream.WriteTo(memoryStream);
#endif
            return(memoryStream);
        }
        public static string PutFile(string filename, Stream s)
        {
            var    dir  = GetFileDir();
            string path = Path.Combine(dir.FullName, filename);

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                s.WriteTo(fs);
            }
            return(path);
        }
Exemple #9
0
        public static void CacheUrlResource(string url, string fileName)
        {
            Stream stream = GetUrlResource(url);

            FileStream output = new FileStream(fileName, FileMode.Create, FileAccess.Write);

            stream.WriteTo(output);

            output.Flush();
            output.Close();
        }
        public void Completed_Transfer_Should_Unlock_File()
        {
            //get stream and write to file
            using (Stream stream = Downloads.ReadFile(SourceFileInfo.FullName))
            {
                stream.WriteTo(TargetFilePath);
            }

            Assert.IsTrue(SourceFile.Exists);
            SourceFile.Delete();
        }
        XElement ToXml(Stream stream)
        {
            using (var output = new MemoryStream())
            {
                stream.WriteTo(output);
                output.Position = 0;

                var bytes = new byte[output.Length];
                output.Read(bytes, 0, bytes.Length);
                var xml = Ionic.Zlib.GZipStream.UncompressString(bytes);
                return XDocument.Parse(xml).Root;
            }
        }
        public void Read_Data_Should_Match_Source_File()
        {
            //get stream and write to file
            using (Stream stream = Downloads.ReadFile(SourceFileInfo.FullName))
            {
                stream.WriteTo(TargetFilePath);
            }

            //calculate hashes of source and target and compare
            string sourceHash = GetFileHash(SourceFileInfo);
            string targetHash = new FileInfo(TargetFilePath).CalculateMd5Hash();

            Assert.AreEqual(sourceHash, targetHash);
        }
Exemple #13
0
        /// <summary>
        /// Gets a buffer that contains all data of a given stream.
        /// </summary>
        /// <param name="source">The stream to read from.</param>
        /// <returns>All data that was read from the buffer.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="source"/>
        /// is a null reference.</exception>
        public static byte[] ReadIntoBuffer(this Stream source)
        {
            Ensure.ArgumentNotNull(source, "source");

            MemoryStream destination = source as MemoryStream;

            if (destination == null)
            {
                destination = new MemoryStream();
                source.WriteTo(destination);
            }

            return(destination.ToArray());
        }
        public void Read_Data_From_Download_Token_Should_Match_Source_File()
        {
            //get stream and write to file
            var token = InitToken();

            using (Stream stream = Downloads.DownloadFile(token.TransferId))
            {
                stream.WriteTo(TargetFilePath);
            }

            //calculate hashes of source and target and compare
            string sourceHash = GetFileHash(SourceFileInfo);
            string targetHash = new FileInfo(TargetFilePath).CalculateMd5Hash();

            Assert.AreEqual(sourceHash, targetHash);
        }
Exemple #15
0
        /// <summary>
        /// Reads a given <paramref name="source"/> stream and writes its contents
        /// to a given file.
        /// </summary>
        /// <param name="source">The stream to source data from.</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="source"/>
        /// is a null reference.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="filePath"/>
        /// is a null reference.</exception>
        public static void WriteTo(this Stream source, string filePath)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            using (Stream destination = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                source.WriteTo(destination);
            }
        }
        public void Read_Data_Should_Match_Source_File()
        {
            string targetPath = FileUtil.CreateTempFilePath(ParentDirectory.FullName, "copy", "bin");

            //get stream and write to file
            using (Stream stream = DownloadHandler.ReadFile(SourceFileInfo.FullName))
            {
                stream.WriteTo(targetPath);
            }

            //calculate hashes of source and target and compare
            string sourceHash = SourceFile.CalculateMd5Hash();
            string targetHash = new FileInfo(targetPath).CalculateMd5Hash();

            Assert.AreEqual(sourceHash, targetHash);
        }
Exemple #17
0
    /// <summary>
    /// Clones a stream into an in-memory stream.
    /// </summary>
    /// <param name="stream" this="true">The object this extension method applies to.</param>
    public static MemoryStream Clone(this Stream stream)
    {
        Guard.NotNull(() => stream, stream);

        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        var mem = new MemoryStream();

        stream.WriteTo(mem);
        mem.Position = 0;

        return(mem);
    }
Exemple #18
0
        public void Read_Data_Should_Match_Source_File()
        {
            string targetPath = FileUtil.CreateTempFilePath(RootDir.FullName, "copy", "bin");

            //get stream and write to file
            using (Stream stream = DownloadService.ReadResourceStreamed(Token.TransferId))
            {
                stream.WriteTo(targetPath);
            }

            //calculate hashes of source and target and compare
            string sourceHash = SourceFile.CalculateMd5Hash();
            string targetHash = new FileInfo(targetPath).CalculateMd5Hash();

            Assert.AreEqual(sourceHash, targetHash);
        }
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            foreach (var entry in pageResult.Options)
            {
                if (entry.Key == HttpHeaders.ContentType)
                {
                    context.HttpContext.Response.ContentType = entry.Value;
                }
                else
                {
                    context.HttpContext.Response.Headers[entry.Key] = entry.Value;
                }
            }

            contents.WriteTo(context.HttpContext.Response.OutputStream);
        }
Exemple #20
0
        public Task <long> CrearAsync(Soporte modelo, Stream filestream)
        {
            var subdirinfo = dirInfoSoportes.CreateSubdirectory("{0}_{1}".Fmt(modelo.ProyectoId, modelo.RegionalId));

            var filePath = Path.Combine(subdirinfo.FullName, NombreSoporte(modelo));

            long bytes = 0;

            using (var fs = File.OpenWrite(filePath))
            {
                bytes = filestream.WriteTo(fs);
            }

            //soportes/14_4/430_

            return(bytes.InTask());
        }
		public override void Load(OpenedFile file, Stream stream)
		{
			if (file == PrimaryFile) {
				try {
					XmlDocument doc = new XmlDocument();
					doc.Load(stream);
					
					setDoc = new SettingsDocument(doc.DocumentElement, view);
					view.ShowEntries(setDoc.Entries);
				} catch (XmlException ex) {
					ShowLoadError(ex.Message);
				}
			} else if (file == appConfigFile) {
				appConfigStream = new MemoryStream();
				stream.WriteTo(appConfigStream);
			}
		}
Exemple #22
0
    /// <summary>
    /// Returns all bytes from the given stream.
    /// </summary>
    /// <nuget id="netfx-System.IO.StreamGetBytes" />
    /// <param name="stream" this="true">The stream to get bytes</param>
    public static byte[] GetBytes(this Stream stream)
    {
        Guard.NotNull(() => stream, stream);

        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        var mem = new MemoryStream();

        stream.WriteTo(mem);

        var buffer = new byte[mem.Length];

        Array.Copy(mem.GetBuffer(), buffer, mem.Length);

        return(buffer);
    }
Exemple #23
0
        public override void Load(OpenedFile file, Stream stream)
        {
            if (file == PrimaryFile)
            {
                try {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(stream);

                    setDoc = new SettingsDocument(doc.DocumentElement, view);
                    view.ShowEntries(setDoc.Entries);
                } catch (XmlException ex) {
                    ShowLoadError(ex.Message);
                }
            }
            else if (file == appConfigFile)
            {
                appConfigStream = new MemoryStream();
                stream.WriteTo(appConfigStream);
            }
        }
        /// <summary>
        /// Copies a stream to another stream
        /// </summary>
        /// <param name="inputStream">Seekable stream to duplicate</param>
        /// <param name="outputStream">Output stream</param>
        /// <exception cref="ArgumentException">Thrown when an argument is not valid for copying</exception>
        /// <exception cref="ArgumentNullException">Thrown when an argument is null</exception>
        /// <exception cref="IOException">Thrown when the in stream cannot be read or the outstream written</exception>
        public static void CopyTo(this Stream inputStream, Stream outputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }

            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream");
            }

            if (!inputStream.CanSeek)
            {
                throw new ArgumentException("instream must be seekable");
            }

            inputStream.Seek(0, SeekOrigin.Begin);
            inputStream.WriteTo(outputStream);
            inputStream.Seek(0, SeekOrigin.Begin);
        }
        public string Save(Stream stream, string filename, string username)
        {
            string userFolder = Path.Combine(_root, username);
            if (!Directory.Exists(userFolder))
            {
                Directory.CreateDirectory(userFolder);
            }

            string storageFile = Path.Combine(userFolder, filename);
            if (File.Exists(storageFile))
            {
                File.Delete(storageFile);
            }

            using (Stream file = File.Create(storageFile))
            {
                stream.WriteTo(file);
            }

            return storageFile;
        }
        public static void UploadFile(this WebRequest webRequest, Stream fileStream, string fileName, string mimeType)
        {
            var httpReq = (HttpWebRequest)webRequest;

            httpReq.UserAgent         = Env.ServerUserAgent;
            httpReq.Method            = "POST";
            httpReq.AllowAutoRedirect = false;
            httpReq.KeepAlive         = false;

            var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            httpReq.ContentType = "multipart/form-data; boundary=" + boundary;

            using (var ms = new MemoryStream())
            {
                var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                var headerTemplate = "\r\n--" + boundary +
                                     "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";

                var header = string.Format(headerTemplate, fileName, mimeType);

                var headerbytes = System.Text.Encoding.ASCII.GetBytes(header);

                ms.Write(headerbytes, 0, headerbytes.Length);
                fileStream.WriteTo(ms);

                ms.Write(boundarybytes, 0, boundarybytes.Length);

                httpReq.ContentLength = ms.Length;

                var requestStream = httpReq.GetRequestStream();

                ms.Position = 0;

                ms.WriteTo(requestStream);

                requestStream.Close();
            }
        }
        private void WriteFileImpl(string virtualFilePath, Stream input, bool overwrite, long resourceLength, string contentType)
        {
            //get a token - this creates a new transfer and validates the request
            UploadToken token = RequestUploadToken(virtualFilePath, overwrite, resourceLength, contentType);

            if (resourceLength == 0)
            {
                //create an empty data block and submit it
                var block = new BufferedDataBlock
                {
                    TransferTokenId = token.TransferId,
                    BlockLength     = 0,
                    BlockNumber     = 0,
                    Data            = new byte[0],
                    IsLastBlock     = true
                };

                WriteBlock(block);
            }
            else
            {
                //we don't expose the underlying stream directly, but rather use blocks again,
                //which disconnects the exposed stream from the underlying resource and allows for simple
                //aborting
                try
                {
                    input.WriteTo(token, resourceLength, token.MaxBlockSize ?? 32768, WriteBlockStreamed);
                }
                catch (Exception)
                {
                    CancelTransfer(token.TransferId, AbortReason.Undefined);
                    throw;
                }

                //we don't need to explicitly complete the transfer - the extension method
                //implicitly closed the transfer by marking the last block:
                //CompleteTransfer(token.TransferId);
            }
        }
Exemple #28
0
        /// <inheritdoc/>
        public PutObjectResult PutObject(Uri signedUrl, Stream content)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(signedUrl);

            webRequest.Timeout       = Timeout.Infinite; // A temporary solution.
            webRequest.Method        = HttpMethod.Put.ToString().ToUpperInvariant();
            webRequest.ContentLength = content.Length;
            using (var requestStream = webRequest.GetRequestStream())
            {
                content.WriteTo(requestStream);
            }

            var             response = webRequest.GetResponse() as HttpWebResponse;
            PutObjectResult result   = null;

            if (response != null && response.StatusCode == HttpStatusCode.OK)
            {
                result = new PutObjectResult {
                    ETag = response.Headers[HttpHeaders.ETag]
                };
            }
            return(result);
        }
Exemple #29
0
        public string Save(Stream stream, string filename, string username)
        {
            string userFolder = Path.Combine(_root, username);

            if (!Directory.Exists(userFolder))
            {
                Directory.CreateDirectory(userFolder);
            }

            string storageFile = Path.Combine(userFolder, filename);

            if (File.Exists(storageFile))
            {
                File.Delete(storageFile);
            }

            using (Stream file = File.Create(storageFile))
            {
                stream.WriteTo(file);
            }

            return(storageFile);
        }
Exemple #30
0
        /// <summary>
        /// Uploads a stream to the desired path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public bool Upload(string path, Stream stream)
        {
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            var request = CreateRequest(path, WebRequestMethods.Ftp.UploadFile);

            request.ContentLength = stream.Length;

            try
            {
                using (Stream output = request.GetRequestStream( ))
                    stream.WriteTo(output);

                return(true);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Could not upload {0}: {1}", path, ex);
                return(false);
            }
        }
        public byte[] Compress(Stream inputStream)
        {
            byte[]       result;
            MemoryStream outputStream = null;

            try
            {
                outputStream = new MemoryStream();
                using (var deflateStream = new DeflateStream(outputStream, CompressionMode.Compress))
                {
                    inputStream.WriteTo(deflateStream);
                    result = outputStream.ToArray();
                }
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Dispose();
                }
            }

            return(result);
        }
 protected  void WriteFileStreamToFileSystem2(FileItem fileItem, Stream input) {
     input.WriteTo(fileItem.LocalFile.FullName);
 }
Exemple #33
0
        /// <summary>
        /// Generates a task sequence for getting the properties of the queue service.
        /// </summary>
        /// <param name="setResult">A delegate to receive the service properties.</param>
        /// <returns>A task sequence that gets the properties of the queue service.</returns>
        private TaskSequence GetServicePropertiesImpl(Action <ServiceProperties> setResult)
        {
            HttpWebRequest request = QueueRequest.GetServiceProperties(this.BaseUri, this.Timeout.RoundUpToSeconds());

            CommonUtils.ApplyRequestOptimizations(request, -1);
            this.Credentials.SignRequest(request);

            // Get the web response.
            Task <WebResponse> responseTask = request.GetResponseAsyncWithTimeout(this, this.Timeout);

            yield return(responseTask);

            using (HttpWebResponse response = responseTask.Result as HttpWebResponse)
                using (Stream responseStream = response.GetResponseStream())
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        // Download the service properties.
                        Task <NullTaskReturn> downloadTask = new InvokeTaskSequenceTask(() => { return(responseStream.WriteTo(memoryStream)); });
                        yield return(downloadTask);

                        // Materialize any exceptions.
                        NullTaskReturn scratch = downloadTask.Result;

                        // Get the result from the memory stream.
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        setResult(QueueResponse.ReadServiceProperties(memoryStream));
                    }
        }
        /// <summary>
        /// Implementation method for the WritePage methods.
        /// </summary>
        /// <param name="pageData">The page data.</param>
        /// <param name="startOffset">The start offset.</param> 
        /// <param name="sourceStreamPosition">The beginning position of the source stream prior to execution, negative if stream is unseekable.</param>
        /// <param name="options">An object that specifies any additional options for the request.</param>
        /// <returns>A <see cref="TaskSequence"/> that writes the pages.</returns>
        private TaskSequence WritePageImpl(Stream pageData, long startOffset, long sourceStreamPosition, BlobRequestOptions options)
        {
            CommonUtils.AssertNotNull("options", options);

            long length = pageData.Length;

            // Logic to rewind stream on a retry
            // HACK : for non seekable streams we need a way to detect the retry iteration so as to only attempt to execute once.
            // The first attempt will have SourceStreamPosition = -1, which means the first iteration on a non seekable stream.
            // The second attempt will have SourceStreamPosition = -2, anything below -1 is considered an abort. Since the Impl method
            // does not have an executino context to be aware of what iteration is used the SourceStreamPosition is utilized as counter to
            // differentiate between the first attempt and a retry.
            if (sourceStreamPosition >= 0 && pageData.CanSeek)
            {
                if (sourceStreamPosition != pageData.Position)
                {
                    pageData.Seek(sourceStreamPosition, 0);
                }
            }
            else if (sourceStreamPosition < -1)
            {
                // TODO : Need to rewrite this to support buffering in XSCL2 so that retries can work on non seekable streams
                throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.CannotRetryNonSeekableStreamError));
            }

            if (startOffset % Protocol.Constants.PageSize != 0)
            {
                CommonUtils.ArgumentOutOfRange("startOffset", startOffset);
            }

            // TODO should reuse sourceStreamPoisition when the HACK above is removed, for readability using a new local variable
            long rangeStreamOffset = pageData.CanSeek ? pageData.Position : 0;

            PutPageProperties properties = new PutPageProperties()
            {
                Range = new PageRange(startOffset, startOffset + length - rangeStreamOffset - 1),
                PageWrite = PageWrite.Update,
            };

            if ((1 + properties.Range.EndOffset - properties.Range.StartOffset) % Protocol.Constants.PageSize != 0 ||
                (1 + properties.Range.EndOffset - properties.Range.StartOffset) == 0)
            {
                CommonUtils.ArgumentOutOfRange("pageData", pageData);
            }

            var webRequest = ProtocolHelper.GetWebRequest(
                this.ServiceClient,
                options,
                (timeout) => BlobRequest.PutPage(this.TransformedAddress, timeout, properties, null));

            ////BlobRequest.AddMetadata(webRequest, this.Metadata);

            // Retrieve the stream
            var requestStreamTask = webRequest.GetRequestStreamAsync();
            yield return requestStreamTask;

            // Copy the data
            using (var outputStream = requestStreamTask.Result)
            {
                var copyTask = new InvokeTaskSequenceTask(() => { return pageData.WriteTo(outputStream); });
                yield return copyTask;

                // Materialize any exceptions
                var scratch = copyTask.Result;
            }

            // signing request needs Size to be set
            this.ServiceClient.Credentials.SignRequest(webRequest);

            // Get the response
            var responseTask = webRequest.GetResponseAsyncWithTimeout(this.ServiceClient, options.Timeout);
            yield return responseTask;

            // Parse the response
            using (HttpWebResponse webResponse = responseTask.Result as HttpWebResponse)
            {
                this.ParseSizeAndLastModified(webResponse);
            }
        }
        /// <summary>
        /// Uploads the data into the web request.
        /// </summary>
        /// <param name="request">The request that is setup for a put.</param>
        /// <param name="source">The source of data.</param>
        /// <param name="result">The response from the server.</param>
        /// <returns>The sequence used for uploading data.</returns>
        internal TaskSequence UploadData(HttpWebRequest request, Stream source, Action<WebResponse> result)
        {
            // Retrieve the stream
            var requestStreamTask = request.GetRequestStreamAsync();
            yield return requestStreamTask;

            // Copy the data
            using (var outputStream = requestStreamTask.Result)
            {
                var copyTask = new InvokeTaskSequenceTask(() => { return source.WriteTo(outputStream); });
                yield return copyTask;

                // Materialize any exceptions
                var scratch = copyTask.Result;
            }

            // Get the response
            var responseTask = request.GetResponseAsyncWithTimeout(this.ServiceClient, this.ServiceClient.Timeout);
            yield return responseTask;

            // Return the response object
            var response = responseTask.Result;

            result(response);
        }
 private void StoreFile(string filename, Stream contentStream)
 {
     using (var file = File.Create(filename))
     {
         contentStream.WriteTo(file);
     }
 }
 public void AppendFile(string filePath, Stream stream)
 {
     var realFilePath = RootDir.RealPath.CombineWith(filePath);
     EnsureDirectory(Path.GetDirectoryName(realFilePath));
     using (var fs = new FileStream(realFilePath, FileMode.Append))
     {
         stream.WriteTo(fs);
     }
 }
        public static void UploadFile(this WebRequest webRequest, Stream fileStream, string fileName, string mimeType)
        {
            var httpReq = (HttpWebRequest)webRequest;
            httpReq.UserAgent = Env.ServerUserAgent;
            httpReq.Method = "POST";
            httpReq.AllowAutoRedirect = false;
            httpReq.KeepAlive = false;

            var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            httpReq.ContentType = "multipart/form-data; boundary=" + boundary;

            using (var ms = new MemoryStream())
            {
                var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                var headerTemplate = "\r\n--" + boundary +
                                     "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";

                var header = string.Format(headerTemplate, fileName, mimeType);

                var headerbytes = System.Text.Encoding.ASCII.GetBytes(header);

                ms.Write(headerbytes, 0, headerbytes.Length);
                fileStream.WriteTo(ms);

                ms.Write(boundarybytes, 0, boundarybytes.Length);

                httpReq.ContentLength = ms.Length;

                var requestStream = httpReq.GetRequestStream();

                ms.Position = 0;

                ms.WriteTo(requestStream);

                requestStream.Close();
            }
        }
Exemple #39
0
 protected void WriteFileStreamToFileSystem2(FileItem fileItem, Stream input)
 {
     input.WriteTo(fileItem.LocalFile.FullName);
 }
Exemple #40
0
        /// <summary>
        /// Implementation method for the WritePage methods.
        /// </summary>
        /// <param name="pageData">The page data.</param>
        /// <param name="startOffset">The start offset.</param>
        /// <param name="sourceStreamPosition">The beginning position of the source stream prior to execution, negative if stream is unseekable.</param>
        /// <param name="options">An object that specifies any additional options for the request.</param>
        /// <returns>A <see cref="TaskSequence"/> that writes the pages.</returns>
        private TaskSequence WritePageImpl(Stream pageData, long startOffset, long sourceStreamPosition, BlobRequestOptions options)
        {
            CommonUtils.AssertNotNull("options", options);

            long length = pageData.Length;

            // Logic to rewind stream on a retry
            // For non seekable streams we need a way to detect the retry iteration so as to only attempt to execute once.
            // The first attempt will have SourceStreamPosition = -1, which means the first iteration on a non seekable stream.
            // The second attempt will have SourceStreamPosition = -2, anything below -1 is considered an abort. Since the Impl method
            // does not have an execution context to be aware of what iteration is used the SourceStreamPosition is utilized as counter to
            // differentiate between the first attempt and a retry.
            if (sourceStreamPosition >= 0 && pageData.CanSeek)
            {
                if (sourceStreamPosition != pageData.Position)
                {
                    pageData.Seek(sourceStreamPosition, 0);
                }
            }
            else if (sourceStreamPosition < -1)
            {
                throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.CannotRetryNonSeekableStreamError));
            }

            if (startOffset % Protocol.Constants.PageSize != 0)
            {
                CommonUtils.ArgumentOutOfRange("startOffset", startOffset);
            }

            long rangeStreamOffset = pageData.CanSeek ? pageData.Position : 0;

            PutPageProperties properties = new PutPageProperties()
            {
                Range     = new PageRange(startOffset, startOffset + length - rangeStreamOffset - 1),
                PageWrite = PageWrite.Update,
            };

            if ((1 + properties.Range.EndOffset - properties.Range.StartOffset) % Protocol.Constants.PageSize != 0 ||
                (1 + properties.Range.EndOffset - properties.Range.StartOffset) == 0)
            {
                CommonUtils.ArgumentOutOfRange("pageData", pageData);
            }

            var webRequest = ProtocolHelper.GetWebRequest(
                this.ServiceClient,
                options,
                (timeout) => BlobRequest.PutPage(this.TransformedAddress, timeout, properties, null));

            ////BlobRequest.AddMetadata(webRequest, this.Metadata);

            // Retrieve the stream
            var requestStreamTask = webRequest.GetRequestStreamAsync();

            yield return(requestStreamTask);

            // Copy the data
            using (var outputStream = requestStreamTask.Result)
            {
                var copyTask = new InvokeTaskSequenceTask(() => { return(pageData.WriteTo(outputStream)); });
                yield return(copyTask);

                // Materialize any exceptions
                var scratch = copyTask.Result;
            }

            // signing request needs Size to be set
            this.ServiceClient.Credentials.SignRequest(webRequest);

            // Get the response
            var responseTask = webRequest.GetResponseAsyncWithTimeout(this.ServiceClient, options.Timeout);

            yield return(responseTask);

            // Parse the response
            using (HttpWebResponse webResponse = responseTask.Result as HttpWebResponse)
            {
                this.ParseSizeAndLastModified(webResponse);
            }
        }
    /// <summary>
    /// Creates or updates a given file resource in the file system.
    /// </summary>
    /// <param name="parentFolderPath">The qualified path of the parent folder that will
    /// contain the file.</param>
    /// <param name="fileName">The name of the file to be created.</param>
    /// <param name="input">A stream that provides the file's contents.</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>
    /// <exception cref="VirtualResourceNotFoundException">If the parent folder
    /// does not exist.</exception>
    /// <exception cref="ResourceAccessException">In case of invalid or prohibited
    /// resource access.</exception>
    /// <exception cref="ResourceOverwriteException">If a file already exists at the
    /// specified location, and the <paramref name="overwrite"/> flag was not set.</exception>
    /// <exception cref="ArgumentNullException">If any of the parameters is a null reference.</exception>
    public override VirtualFileInfo WriteFile(string parentFolderPath, string fileName, Stream input, bool overwrite)
    {
      if (parentFolderPath == null) throw new ArgumentNullException("parentFolderPath");
      if (fileName == null) throw new ArgumentNullException("fileName");
      if (input == null) throw new ArgumentNullException("input");


      //get the parent and make sure it exists
      string absoluteParentPath;
      var parent = GetFolderInfoInternal(parentFolderPath, true, out absoluteParentPath);

      if(RootDirectory == null && parent.IsRootFolder)
      {
        VfsLog.Debug("Blocked attempt to create a file '{0}' at system root (which is the machine itself - no root directory was set).", fileName);
        throw new ResourceAccessException("Files cannot be created at the system root.");        
      }

      //combine to file path and get virtual file (also makes sure we don't get out of scope)
      string absoluteFilePath = PathUtil.GetAbsolutePath(fileName, new DirectoryInfo(absoluteParentPath));

      FileInfo fi = new FileInfo(absoluteFilePath);
      if (fi.Exists && !overwrite)
      {
        VfsLog.Debug("Blocked attempt to overwrite file '{0}'", fi.FullName);
        string msg = String.Format("The file [{0}] already exists.", fileName);
        throw new ResourceOverwriteException(msg);
      }

      try
      {
        using (Stream writeStream = new FileStream(fi.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
        {
          input.WriteTo(writeStream);
        }
      }
      catch (Exception e)
      {
        //log exception with full path
        string msg = "Could not write write submitted content to file '{0}'.";
        VfsLog.Error(e, msg, fi.FullName);
        //generate exception with relative path
        msg = String.Format(msg, PathUtil.GetRelativePath(fi.FullName, RootDirectory));
        throw new ResourceAccessException(msg, e);
      }

      //return update file info
      var file = fi.CreateFileResourceInfo();

      //adjust and return
      if (UseRelativePaths) file.MakePathsRelativeTo(RootDirectory);
      return file;
    }