/// <summary>
 /// Constructs a web request to delete the container and all of the blobs within it.
 /// </summary>
 /// <param name="uri">The absolute URI to the container.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpWebRequest Delete(Uri uri, int? timeout, AccessCondition accessCondition, OperationContext operationContext)
 {
     UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
     HttpWebRequest request = HttpWebRequestFactory.Delete(uri, containerBuilder, timeout, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 /// <summary>
 /// Constructs a web request to delete the directory and all of the files within it.
 /// </summary>
 /// <param name="uri">The absolute URI to the directory.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <param name="useVersionHeader">A boolean value indicating whether to set the <i>x-ms-version</i> HTTP header.</param>
 /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
 /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns>
 public static HttpWebRequest Delete(Uri uri, int? timeout, AccessCondition accessCondition, bool useVersionHeader, OperationContext operationContext)
 {
     UriQueryBuilder directoryBuilder = GetDirectoryUriQueryBuilder();
     HttpWebRequest request = HttpWebRequestFactory.Delete(uri, directoryBuilder, timeout, useVersionHeader, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 /// <summary>
 /// Generates a web request to return the properties and user-defined metadata for this directory.
 /// </summary>
 /// <param name="uri">The absolute URI to the directory.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpRequestMessage GetProperties(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
 {
     UriQueryBuilder directoryBuilder = GetDirectoryUriQueryBuilder();
     HttpRequestMessage request = HttpRequestMessageFactory.GetProperties(uri, timeout, directoryBuilder, content, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 /// <summary>
 /// Generates a web request to return the user-defined metadata for this container.
 /// </summary>
 /// <param name="uri">The absolute URI to the container.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static StorageRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
 {
     UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
     StorageRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext, canonicalizer, credentials);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
        /// <summary>
        /// Applies the condition to the web request.
        /// </summary>
        /// <param name="request">The request to be modified.</param>
        /// <param name="accessCondition">Access condition to be added to the request.</param>
        internal static void ApplyAccessCondition(this HttpWebRequest request, AccessCondition accessCondition)
        {
            if (accessCondition != null)
            {
                if (!string.IsNullOrEmpty(accessCondition.IfMatchETag))
                {
                    request.Headers[HttpRequestHeader.IfMatch] = accessCondition.IfMatchETag;
                }

                if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchETag))
                {
                    request.Headers[HttpRequestHeader.IfNoneMatch] = accessCondition.IfNoneMatchETag;
                }

                if (accessCondition.IfModifiedSinceTime.HasValue)
                {
                    // Not using this property will cause Restricted property exception to be thrown
                    request.IfModifiedSince = accessCondition.IfModifiedSinceTime.Value.UtcDateTime;
                }

                if (accessCondition.IfNotModifiedSinceTime.HasValue)
                {
                    request.Headers[HttpRequestHeader.IfUnmodifiedSince] =
                        HttpUtility.ConvertDateTimeToHttpString(accessCondition.IfNotModifiedSinceTime.Value);
                }

                if (!string.IsNullOrEmpty(accessCondition.LeaseId))
                {
                    request.Headers[Constants.HeaderConstants.LeaseIdHeader] = accessCondition.LeaseId;
                }
            }
        }
 /// <summary>
 /// Generates a web request to return the user-defined metadata for this container.
 /// </summary>
 /// <param name="uri">The absolute URI to the container.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
 {
     UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
     HttpRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
        public async virtual void UploadBlockBlobAsync(string blobName, Stream streamToUpload, string contentType, AccessCondition accessCondition = null)
        {
            var blockBlob = GetBlockBlobReference(blobName);
            blockBlob.Properties.ContentType = contentType;

            await blockBlob.UploadFromStreamAsync(streamToUpload, accessCondition, null, null);
        }
 /// <summary>
 /// Constructs a web request to delete the share and all of the files within it.
 /// </summary>
 /// <param name="uri">The absolute URI to the share.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpRequestMessage Delete(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
 {
     UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();
     HttpRequestMessage request = HttpRequestMessageFactory.Delete(uri, timeout, shareBuilder, content, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 /// <summary>
 /// Generates a web request to return the user-defined metadata for this share.
 /// </summary>
 /// <param name="uri">The absolute URI to the share.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <param name="useVersionHeader">A flag indicating whether to set the x-ms-version HTTP header.</param>
 /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpWebRequest GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, bool useVersionHeader, OperationContext operationContext)
 {
     UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();
     HttpWebRequest request = HttpWebRequestFactory.GetMetadata(uri, timeout, shareBuilder, useVersionHeader, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
 static async Task UploadTextAsync(ICloudBlob blob, string text, AccessCondition accessCondition)
 {
     blob.Properties.ContentEncoding = "UTF-8";
     blob.Properties.ContentType = "text/plain";
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text))) {
         await blob.UploadFromStreamAsync(stream, accessCondition, null, null);
     }
 }
        /// <summary>
        /// Constructs a web request to delete the share and all of the files within it.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Delete(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            StorageRequestMessage request = HttpRequestMessageFactory.Delete(uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);
            request.ApplyAccessCondition(accessCondition);
            return request;
        }
        public static void Run()
        {
            #region Obtain a client from the connection string

              CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
              CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
              Console.WriteLine("Parsed connection string and created blob client.");

              #endregion

              #region Obtain reference to images container

              CloudBlobContainer imageContainer = blobClient.GetContainerReference("images");
              Console.WriteLine("Obtained reference to images container.");

              #endregion

              #region Show concurrency management using ETag property

              Console.WriteLine();

              CloudBlockBlob blockBlob1 = imageContainer.GetBlockBlobReference(@"rocks/WhitePocketFocus.jpg");
              CloudBlockBlob blockBlob2 = imageContainer.GetBlockBlobReference(@"rocks/WhitePocketFocus.jpg");
              blockBlob1.FetchAttributes();
              blockBlob2.FetchAttributes();
              Console.WriteLine("[1] Obtained ETag {0} for rocks/WhitePocketFocus.jpg in images container.", blockBlob1.Properties.ETag);
              Console.WriteLine("[2] Obtained ETag {0} for rocks/WhitePocketFocus.jpg in images container.", blockBlob2.Properties.ETag);

              var etag = blockBlob1.Properties.ETag;
              var accessCondition = new AccessCondition {IfMatchETag = etag};

              var metadata = new Dictionary<string, string>()
              {
            { "License",  "snowpeak" },
            { "URL",      "http://www.flickr.com/photos/snowpeak/7394540572/sizes/l/in/pool-809956@N25/"}
              };

              Console.WriteLine("[1] Setting metadata on rocks/WhitePocketFocus.jpg in images container.");
              foreach (KeyValuePair<string, string> pair in metadata) { blockBlob1.Metadata.Add(pair); }
              blockBlob1.SetMetadata(accessCondition);

              blockBlob1.FetchAttributes();
              Console.WriteLine("[1] New ETag {0} for rocks/WhitePocketFocus.jpg in images container.", blockBlob1.Properties.ETag);

              try
              {
            Console.WriteLine("[2] Setting metadata on rocks/WhitePocketFocus.jpg in images container.");
            foreach (KeyValuePair<string, string> pair in metadata) { blockBlob2.Metadata.Add(pair); }
            blockBlob2.SetMetadata(accessCondition);
              }
              catch (Exception exception)
              {
            Console.WriteLine("[2] Caught exception '" + exception.GetType() + "' while trying to set metadata on rocks/WhitePocketFocus.jpg in images container.");
            Console.WriteLine(exception.StackTrace);
              }

              #endregion
        }
     public async static Task UploadFromStreamEncryptedAsync(this ICloudBlob blob, IBlobCryptoProvider provider, Stream stream,
 AccessCondition accessCondition = null, BlobRequestOptions options = null,
 OperationContext operationContext = null)
     {
         using (Stream encryptedStream = provider.EncryptedStream(stream))
         {
             await blob.UploadFromStreamAsync(encryptedStream, accessCondition, options, operationContext);
         }
     }
 static void UploadText(ICloudBlob blob, string text, AccessCondition accessCondition)
 {
     blob.Properties.ContentEncoding = "UTF-8";
     blob.Properties.ContentType = "text/plain";
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
     {
         blob.UploadFromStream(stream, accessCondition);
     }
 }
     public async static Task DownloadToFileEncryptedAsync(this ICloudBlob blob, IBlobCryptoProvider provider, string path, FileMode mode,
 AccessCondition accessCondition = null, BlobRequestOptions options = null,
 OperationContext operationContext = null)
     {
         using (FileStream fileStream = new FileStream(path, mode))
         {
             await blob.DownloadToStreamEncryptedAsync(provider, fileStream, accessCondition, options, operationContext);
         }
     }
        public AzureWriteBlockBlobStream(CloudBlockBlob blob, AccessCondition condition)
        {
            _blob = blob;
            _condition = condition;

            long min = Math.Min(blob.Properties.Length, AzureBlockSize);
            if (min < 0) { min = 0; }
            _buff = new MemoryStream((int)min);
            _partNumber = 1;
        }
 public static void DownloadToStreamEncrypted(this ICloudBlob blob, IBlobCryptoProvider provider, Stream stream,
     AccessCondition accessCondition = null, BlobRequestOptions options = null,
     OperationContext operationContext = null)
 {
     using (Stream blobStream = blob.OpenRead(accessCondition, options, operationContext))
     using (Stream decryptedStream = provider.DecryptedStream(blobStream))
     {
         decryptedStream.CopyTo(stream);
     }
 }
     public async static Task UploadFromFileEncryptedAsync(this ICloudBlob blob, IBlobCryptoProvider provider, string path, FileMode mode,
 AccessCondition accessCondition = null, BlobRequestOptions options = null,
 OperationContext operationContext = null)
     {
         using (FileStream fileStream = new FileStream(path, mode))
         using (Stream encryptedStream = provider.EncryptedStream(fileStream))
         {
             await blob.UploadFromStreamAsync(encryptedStream, accessCondition, options, operationContext);
         }
     }
 public static CloudBlockBlob Upload(this CloudBlockBlob blob, string text
     , AccessCondition accessCondition = null, BlobRequestOptions blobRequestOptions = null, OperationContext operationContext = null)
 {
     var bytes = Encoding.UTF8.GetBytes(text);
     using (var ms = new MemoryStream(bytes))
     {
         blob.UploadFromStream(ms, accessCondition, blobRequestOptions, operationContext);
     }
     return blob;
 }
Exemple #20
0
 public static CloudBlob GetBlobReferenceFromServer(
     CloudBlobContainer container, 
     string blobName, 
     AccessCondition accessCondition = null,
     BlobRequestOptions options = null,
     OperationContext operationContext = null)
 {
     CloudBlob blob = container.GetBlobReference(blobName);
     return GetBlobReferenceFromServer(blob, accessCondition, options, operationContext);
 }
 public Task FetchShareAttributesAsync(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken token)
 {
     if (this.availableShareNames.Contains(share.Name))
     {
         return TaskEx.FromResult(true);
     }
     else
     {
         throw new MockupException("ShareNotExist");
     }
 }
 public async Task UploadFromByteArrayAsync(string blobName, byte[] buffer, int index, int count,
     AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     var blob = await CreateCloudBlockBlobAsync(blobName);
     await blob.UploadFromByteArrayAsync(
         buffer,
         index,
         count,
         accessCondition,
         options,
         operationContext);
 }
        public static void UploadText(this CloudBlockBlob blockBlob, string content, AccessCondition accessCondition = null)
        {
            using (var stream = blockBlob.OpenWrite(accessCondition))
            {
                var encoding = new UTF8Encoding();
                var buffer = encoding.GetBytes(content);

                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
            }
        }
        /// <summary>
        /// UploadFromStreamAsync
        /// </summary>
        /// <param name="blob"></param>
        /// <param name="sourceStream"></param>
        /// <param name="accessCondition"></param>
        /// <param name="options"></param>
        /// <param name="operationContext"></param>
        /// <returns></returns>
        public static async Task UploadFromStreamAsync(this ICloudBlob blob, Stream sourceStream, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
        {
            Func<AsyncCallback, Object, IAsyncResult> beginMethod = (cb, state) =>
            {
                return blob.BeginUploadFromStream(sourceStream, accessCondition, options, operationContext, cb, state);
            };

            Action<IAsyncResult> endMethod = (r) =>
            {
                blob.EndUploadFromStream(r);
            };

            await Task.Factory.FromAsync(beginMethod, endMethod, null);
        }
        public static byte[] GetBlobBinary(this CloudBlockBlob blob, AccessCondition accessCondition = null, BlobRequestOptions blobRequestOptions = null, OperationContext operationContext = null)
        {
            byte[] bytes;

            blob.FetchAttributes();
            var blobSize = blob.Properties.Length;
            using (var memoryStream = new MemoryStream((int)blobSize))
            {
                blob.DownloadToStream(memoryStream, accessCondition, blobRequestOptions, operationContext);
                bytes = memoryStream.ToArray();
            }

            return bytes;
        }
        /// <summary>
        ///     Returns an enumerable collection of the blob's blocks, using the specified block list filter asynchronously.
        /// </summary>
        /// <param name="blockBlob">Cloud block blob.</param>
        /// <param name="blockListingFilter">
        ///     One of the enumeration values that indicates whether to return
        ///     committed blocks, uncommitted blocks, or both.
        /// </param>
        /// <param name="accessCondition">
        ///     An <see cref="T:Microsoft.WindowsAzure.Storage.AccessCondition" /> object that represents the access conditions for the blob. If <c>null</c>, no condition is used.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     An enumerable collection of objects implementing <see cref="T:Microsoft.WindowsAzure.Storage.Blob.ListBlockItem" />.
        /// </returns>
        public static Task<IEnumerable<ListBlockItem>> DownloadBlockListAsync(
            this CloudBlockBlob blockBlob,
            BlockListingFilter blockListingFilter = BlockListingFilter.Committed,
            AccessCondition accessCondition = null,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            ICancellableAsyncResult asyncResult = blockBlob.BeginDownloadBlockList(blockListingFilter, accessCondition, null, null, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return Task<IEnumerable<ListBlockItem>>.Factory.FromAsync(
                asyncResult,
                result =>
                    {
                        registration.Dispose();
                        return blockBlob.EndDownloadBlockList(result);
                    });
        }
        /// <summary>
        ///     Creates a snapshot of the blob asynchronously.
        /// </summary>
        /// <param name="blockBlob">Cloud block blob.</param>
        /// <param name="metadata">A collection of name-value pairs defining the metadata of the snapshot.</param>
        /// <param name="accessCondition">
        ///     An <see cref="T:Microsoft.WindowsAzure.Storage.AccessCondition" /> object that represents the access conditions for the blob. If <c>null</c>, no condition is used.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     A blob snapshot.
        /// </returns>
        public static Task<CloudBlockBlob> CreateSnapshotAsync(
            this CloudBlockBlob blockBlob,
            IDictionary<string, string> metadata = null,
            AccessCondition accessCondition = null,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            ICancellableAsyncResult asyncResult = blockBlob.BeginCreateSnapshot(metadata, accessCondition, null, null, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return Task<CloudBlockBlob>.Factory.FromAsync(
                asyncResult,
                result =>
                    {
                        registration.Dispose();
                        return blockBlob.EndCreateSnapshot(result);
                    });
        }
        /// <summary>
        ///     Creates a page blob asynchronously.
        /// </summary>
        /// <param name="pageBlob">Cloud page blob.</param>
        /// <param name="size">The maximum size of the page blob, in bytes.</param>
        /// <param name="accessCondition">
        ///     An <see cref="T:Microsoft.WindowsAzure.Storage.AccessCondition" /> object that represents the access conditions for the blob. If <c>null</c>, no condition is used.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public static Task CreateAsync(
            this CloudPageBlob pageBlob,
            long size,
            AccessCondition accessCondition = null,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            ICancellableAsyncResult asyncResult = pageBlob.BeginCreate(size, accessCondition, null, null, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return Task.Factory.FromAsync(
                asyncResult,
                result =>
                    {
                        registration.Dispose();
                        pageBlob.EndCreate(result);
                    });
        }
        /// <summary>
        ///     Aborts an ongoing blob copy operation asynchronously.
        /// </summary>
        /// <param name="cloudBlob">Cloud blob client.</param>
        /// <param name="copyId">A string identifying the copy operation.</param>
        /// <param name="accessCondition">
        ///     An <see cref="T:Microsoft.WindowsAzure.Storage.AccessCondition" /> object that represents the access conditions for the blob.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public static Task AbortCopyAsync(
            this ICloudBlob cloudBlob,
            string copyId,
            AccessCondition accessCondition = null,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            ICancellableAsyncResult asyncResult = cloudBlob.BeginAbortCopy(copyId, accessCondition, null, null, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return Task.Factory.FromAsync(
                asyncResult,
                result =>
                    {
                        registration.Dispose();
                        cloudBlob.EndAbortCopy(result);
                    });
        }
        /// <summary>
        ///     Gets a reference to a blob in this container asynchronously.
        /// </summary>
        /// <param name="blobClient">Cloud blob client.</param>
        /// <param name="blobUri">The URI of the blob.</param>
        /// <param name="accessCondition">
        ///     An object that represents the access conditions for the container. If <c>null</c>, no condition is used.
        /// </param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        ///     A reference to the blob.
        /// </returns>
        public static Task<ICloudBlob> GetBlobReferenceFromServerAsync(
            this CloudBlobClient blobClient,
            Uri blobUri,
            AccessCondition accessCondition = null,
            CancellationToken cancellationToken = default (CancellationToken))
        {
            ICancellableAsyncResult asyncResult = blobClient.BeginGetBlobReferenceFromServer(blobUri, accessCondition, null, null, null, null);
            CancellationTokenRegistration registration = cancellationToken.Register(p => asyncResult.Cancel(), null);

            return Task<ICloudBlob>.Factory.FromAsync(
                asyncResult,
                result =>
                    {
                        registration.Dispose();
                        return blobClient.EndGetBlobReferenceFromServer(result);
                    });
        }