public async ValueTask <IFileReference> SaveAsync(byte[] data, IPrivateFileReference file, string contentType, OverwritePolicy overwritePolicy = OverwritePolicy.Always, IDictionary <string, string> metadata = null)
 {
     using (var stream = new SyncMemoryStream(data, 0, data.Length))
     {
         return(await this.SaveAsync(stream, file, contentType, overwritePolicy, metadata));
     }
 }
Example #2
0
 /// <summary>
 /// Downloads string content of the given blob. If encoding is not specified, it removes the BOM mark from beginning of the string if exists.
 /// </summary>
 /// <param name="blob">CloudBlockBlob to download contents.</param>
 /// <param name="encoding">Encoding which should be used to convert the content of blob to string. If encoding is not specified, it removes the BOM mark from beginning of the string if exists.</param>
 /// <returns>string content of the given blob.</returns>
 public static string DownloadString(this CloudBlockBlob blob, System.Text.Encoding encoding = null, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     using (SyncMemoryStream stream = new SyncMemoryStream())
     {
         blob.DownloadToStream(stream, accessCondition, options, operationContext);
         byte[] streamAsBytes = stream.GetBuffer();
         return(GetStringUsingEncoding(streamAsBytes, encoding));
     }
 }
        public async Task WriteAsync(string filePath, byte[] bytes)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            filePath = Url.DirToUrlSeparator(filePath);

            //Ensure the directory exists
            var directory = Url.GetDirectoryName(filePath);

            if (!string.IsNullOrWhiteSpace(directory) && !await GetDirectoryExistsAsync(directory))
            {
                await CreateDirectoryAsync(directory);
            }

            var file = await GetFileAsync(filePath);

            var stream = new SyncMemoryStream(bytes, 0, bytes.Length);
            await file.UploadFromStreamAsync(stream);
        }
        public ICancellableAsyncResult BeginDownloadRangeToByteArray(byte[] target, int index, long? blobOffset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            SyncMemoryStream stream = new SyncMemoryStream(target, index);
            StorageAsyncResult<int> storageAsyncResult = new StorageAsyncResult<int>(callback, state) { OperationState = stream };

            ICancellableAsyncResult result = this.BeginDownloadRangeToStream(
                stream,
                blobOffset,
                length,
                accessCondition,
                options,
                operationContext,
                this.DownloadRangeToByteArrayCallback,
                storageAsyncResult);

            storageAsyncResult.CancelDelegate = result.Cancel;
            return storageAsyncResult;
        }
 public int DownloadRangeToByteArray(byte[] target, int index, long? blobOffset, long? length, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     using (SyncMemoryStream stream = new SyncMemoryStream(target, index))
     {
         this.DownloadRangeToStream(stream, blobOffset, length, accessCondition, options, operationContext);
         return (int)stream.Position;
     }
 }
        /// <summary>
        /// Begins an asynchronous operation to download the blob's contents as a string.
        /// </summary>
        /// <param name="encoding">An object that indicates the text encoding to use.</param>
        /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the blob.</param>
        /// <param name="options">An object that specifies any additional options for the request.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
        /// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
        /// <returns>An <see cref="ICancellableAsyncResult"/> that references the asynchronous operation.</returns>
        public ICancellableAsyncResult BeginDownloadText(Encoding encoding, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            SyncMemoryStream stream = new SyncMemoryStream();
            StorageAsyncResult<string> storageAsyncResult = new StorageAsyncResult<string>(callback, state) { OperationState = Tuple.Create(stream, encoding) };

            ICancellableAsyncResult result = this.BeginDownloadToStream(
                stream,
                accessCondition,
                options,
                operationContext,
                this.DownloadTextCallback,
                storageAsyncResult);

            storageAsyncResult.CancelDelegate = result.Cancel;
            return storageAsyncResult;
        }
 /// <summary>
 /// Downloads the blob's contents as a string.
 /// </summary>
 /// <param name="encoding">An object that indicates the text encoding to use.</param>
 /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the blob.</param>
 /// <param name="options">An object that specifies any additional options for the request.</param>
 /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
 /// <returns>The contents of the blob, as a string.</returns>
 public string DownloadText(Encoding encoding = null, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     using (SyncMemoryStream stream = new SyncMemoryStream())
     {
         this.DownloadToStream(stream, accessCondition, options, operationContext);
         byte[] streamAsBytes = stream.GetBuffer();
         return (encoding ?? Encoding.UTF8).GetString(streamAsBytes, 0, (int)stream.Length);
     }
 }
        public ICancellableAsyncResult BeginUploadFromByteArray(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            CommonUtility.AssertNotNull("buffer", buffer);

            SyncMemoryStream stream = new SyncMemoryStream(buffer, index, count);
            return this.BeginUploadFromStream(stream, accessCondition, options, operationContext, callback, state);
        }
        public void UploadFromByteArray(byte[] buffer, int index, int count, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
        {
            CommonUtility.AssertNotNull("buffer", buffer);

            using (SyncMemoryStream stream = new SyncMemoryStream(buffer, index, count))
            {
                this.UploadFromStream(stream, accessCondition, options, operationContext);
            }
        }
Example #10
0
        public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNull("buffer", buffer);

            SyncMemoryStream stream = new SyncMemoryStream(buffer, index, count);
            return this.UploadFromStreamAsync(stream, accessCondition, options, operationContext, cancellationToken);
        }
        internal ICancellableAsyncResult BeginUploadFromStreamHelper(Stream source, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            CommonUtility.AssertNotNull("source", source);

            if (length.HasValue)
            {
                CommonUtility.AssertInBounds("length", length.Value, 1);

                if (source.CanSeek && length > source.Length - source.Position)
                {
                    throw new ArgumentOutOfRangeException("length", SR.StreamLengthShortError);
                }
            }

            this.attributes.AssertNoSnapshot();
            BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.BlockBlob, this.ServiceClient);

            ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions);
            StorageAsyncResult<NullType> storageAsyncResult = new StorageAsyncResult<NullType>(callback, state);

            bool lessThanSingleBlobThreshold = CloudBlockBlob.IsLessThanSingleBlobThreshold(source, length, modifiedOptions, false);
            modifiedOptions.AssertPolicyIfRequired();
            
            if (modifiedOptions.ParallelOperationThreadCount.Value == 1 && lessThanSingleBlobThreshold)
            {
                // Because we may or may not want to calculate the MD5, and we may or may not want to encrypt, rather than have four branching code
                // paths, here we have an action that we will run, which continually gets added to, depending on which operations we need to do.
                // The confusing part is that we have to build it from the bottom up.

                string md5 = null;
                Stream sourceStream = source;
                Action actionToRun = null;

                Action uploadAction = () =>
                    {
                        if (md5 == null && modifiedOptions.UseTransactionalMD5.Value)
                        {
                            throw new ArgumentException(SR.PutBlobNeedsStoreBlobContentMD5, "options");
                        }

                        this.UploadFromStreamHandler(
                                            sourceStream,
                                            length,
                                            md5,
                                            accessCondition,
                                            operationContext,
                                            modifiedOptions,
                                            storageAsyncResult);

                    };
                actionToRun = uploadAction;

                if (modifiedOptions.StoreBlobContentMD5.Value)
                {
                    Action<Action> calculateMD5 = (continuation) =>
                    {
                        long startPosition = sourceStream.Position;
                        StreamDescriptor streamCopyState = new StreamDescriptor();
                        sourceStream.WriteToAsync(
                            Stream.Null,
                            length,
                            null /* maxLength */,
                            true,
                            tempExecutionState,
                            streamCopyState,
                            completedState =>
                            {
                                ContinueAsyncOperation(storageAsyncResult, completedState, () =>
                                    {
                                        if (completedState.ExceptionRef != null)
                                        {
                                            storageAsyncResult.OnComplete(completedState.ExceptionRef);
                                        }
                                        else
                                        {
                                            sourceStream.Position = startPosition;
                                            md5 = streamCopyState.Md5;
                                            continuation();
                                        }
                                    });
                            });

                        storageAsyncResult.CancelDelegate = tempExecutionState.Cancel;
                        if (storageAsyncResult.CancelRequested)
                        {
                            storageAsyncResult.Cancel();
                        }
                    };
                    Action oldActionToRun = actionToRun;
                    actionToRun = () => calculateMD5(oldActionToRun);
                }

                if (modifiedOptions.EncryptionPolicy != null)
                {
                    Action<Action> encryptStream = continuation =>
                        {
                            SyncMemoryStream syncMemoryStream = new SyncMemoryStream();
                            options.AssertPolicyIfRequired();

                            sourceStream = syncMemoryStream;

                            if (modifiedOptions.EncryptionPolicy.EncryptionMode != BlobEncryptionMode.FullBlob)
                            {
                                throw new InvalidOperationException(SR.InvalidEncryptionMode, null);
                            }

                            ICryptoTransform transform = options.EncryptionPolicy.CreateAndSetEncryptionContext(this.Metadata, false /* noPadding */);
                            CryptoStream cryptoStream = new CryptoStream(syncMemoryStream, transform, CryptoStreamMode.Write);
                            StreamDescriptor streamCopyState = new StreamDescriptor();

                            source.WriteToAsync(cryptoStream, length, null, false, tempExecutionState, streamCopyState, completedState =>
                                {
                                    ContinueAsyncOperation(storageAsyncResult, completedState, () =>
                                        {
                                            if (completedState.ExceptionRef != null)
                                            {
                                                storageAsyncResult.OnComplete(completedState.ExceptionRef);
                                            }
                                            else
                                            {
                                                // Flush the CryptoStream in order to make sure that the last block of data is flushed. This call is a sync call
                                                // but it is ok to have it because we're just writing to a memory stream.
                                                cryptoStream.FlushFinalBlock();

                                                // After the tempStream has been written to, we need to seek back to the beginning, so that it can be read from.
                                                sourceStream.Seek(0, SeekOrigin.Begin);
                                                length = syncMemoryStream.Length;
                                                continuation();
                                            }
                                        });
                                });

                            storageAsyncResult.CancelDelegate = tempExecutionState.Cancel;
                            if (storageAsyncResult.CancelRequested)
                            {
                                storageAsyncResult.Cancel();
                            }
                        };
                    Action oldActionToRun = actionToRun;
                    actionToRun = () => encryptStream(oldActionToRun);
                }

                actionToRun();
            }
            else
            {
                ICancellableAsyncResult result = this.BeginOpenWrite(
                    accessCondition,
                    modifiedOptions,
                    operationContext,
                    ar =>
                    {
                        ContinueAsyncOperation(storageAsyncResult, ar, () =>
                            {
                                CloudBlobStream blobStream = this.EndOpenWrite(ar);
                                storageAsyncResult.OperationState = blobStream;

                                source.WriteToAsync(
                                    blobStream,
                                    length,
                                    null /* maxLength */,
                                    false,
                                    tempExecutionState,
                                    null /* streamCopyState */,
                                    completedState =>
                                    {
                                        ContinueAsyncOperation(storageAsyncResult, completedState, () =>
                                        {
                                            if (completedState.ExceptionRef != null)
                                            {
                                                storageAsyncResult.OnComplete(completedState.ExceptionRef);
                                            }
                                            else
                                            {
                                                ICancellableAsyncResult commitResult = blobStream.BeginCommit(
                                                        CloudBlob.BlobOutputStreamCommitCallback,
                                                        storageAsyncResult);

                                                storageAsyncResult.CancelDelegate = commitResult.Cancel;
                                                if (storageAsyncResult.CancelRequested)
                                                {
                                                    storageAsyncResult.Cancel();
                                                }
                                            }
                                        });
                                    });

                                storageAsyncResult.CancelDelegate = tempExecutionState.Cancel;
                                if (storageAsyncResult.CancelRequested)
                                {
                                    storageAsyncResult.Cancel();
                                }
                            });
                    },
                    null /* state */);

                // We do not need to do this inside a lock, as storageAsyncResult is
                // not returned to the user yet.
                storageAsyncResult.CancelDelegate = result.Cancel;
            }

            return storageAsyncResult;
        }
Example #12
0
 public IAsyncOperation<int> DownloadRangeToByteArrayAsync([WriteOnlyArray] byte[] target, int index, long? fileOffset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
 {
     return AsyncInfo.Run(async (token) =>
     {
         using (SyncMemoryStream stream = new SyncMemoryStream(target, index))
         {
             await this.DownloadRangeToStreamAsync(stream.AsOutputStream(), fileOffset, length, accessCondition, options, operationContext).AsTask(token);
             return (int)stream.Position;
         }
     });
 }
Example #13
0
 /// <summary>
 /// Downloads the file's contents as a string.
 /// </summary>
 /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the file.</param>
 /// <param name="options">An object that specifies additional options for the request.</param>
 /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
 /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param>
 /// <returns>The contents of the file, as a string.</returns>
 public Task<string> DownloadTextAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return Task.Run(async () =>
     {
         using (SyncMemoryStream stream = new SyncMemoryStream())
         {
             await this.DownloadToStreamAsync(stream, accessCondition, options, operationContext, cancellationToken);
             byte[] streamAsBytes = stream.ToArray();
             return Encoding.UTF8.GetString(streamAsBytes, 0, streamAsBytes.Length);
         }
     }, cancellationToken);
 }
Example #14
0
 public IAsyncOperation<string> DownloadTextAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
 {
     return AsyncInfo.Run(async (token) =>
     {
         using (SyncMemoryStream stream = new SyncMemoryStream())
         {
             await this.DownloadToStreamAsync(stream.AsOutputStream(), accessCondition, options, operationContext).AsTask(token);
             byte[] streamAsBytes = stream.ToArray();
             return Encoding.UTF8.GetString(streamAsBytes, 0, streamAsBytes.Length);
         }
     });
 }
Example #15
0
        public IAsyncAction UploadFromByteArrayAsync([ReadOnlyArray] byte[] buffer, int index, int count, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("buffer", buffer);

            SyncMemoryStream stream = new SyncMemoryStream(buffer, index, count);
            return this.UploadFromStreamAsync(stream.AsInputStream(), accessCondition, options, operationContext);
        }
Example #16
0
 public Task<int> DownloadRangeToByteArrayAsync(byte[] target, int index, long? fileOffset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return Task.Run(async () =>
     {
         using (SyncMemoryStream stream = new SyncMemoryStream(target, index))
         {
             await this.DownloadRangeToStreamAsync(stream, fileOffset, length, accessCondition, options, operationContext, cancellationToken);
             return (int)stream.Position;
         }
     }, cancellationToken);
 }