/// <summary>
        /// Basic operations to work with page blobs
        /// </summary>
        /// <returns>Task</returns>
        private static async Task BasicStoragePageBlobOperationsAsync()
        {
            const string PageBlobName          = "samplepageblob";
            string       pageBlobContainerName = "demopageblobcontainer-" + Guid.NewGuid();

            // Retrieve storage account information from connection string
            // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
            CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create a blob client for interacting with the blob service.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container");
            CloudBlobContainer container = blobClient.GetContainerReference(pageBlobContainerName);
            await container.CreateIfNotExistsAsync();

            // Create a page blob in the newly created container.
            Console.WriteLine("2. Creating Page Blob");
            CloudPageBlob pageBlob = container.GetPageBlobReference(PageBlobName);
            await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes

            // Write to a page blob
            Console.WriteLine("2. Write to a Page Blob");
            byte[] samplePagedata = new byte[512];
            Random random         = new Random();

            random.NextBytes(samplePagedata);
            await pageBlob.UploadFromByteArrayAsync(samplePagedata, 0, samplePagedata.Length);

            // List all blobs in this container. Because a container can contain a large number of blobs the results
            // are returned in segments (pages) with a maximum of 5000 blobs per segment. You can define a smaller size
            // using the maxResults parameter on ListBlobsSegmentedAsync.
            Console.WriteLine("3. List Blobs in Container");
            BlobContinuationToken token = null;

            do
            {
                BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);

                token = resultSegment.ContinuationToken;
                foreach (IListBlobItem blob in resultSegment.Results)
                {
                    // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                    Console.WriteLine("{0} (type: {1}", blob.Uri, blob.GetType());
                }
            } while (token != null);

            // Read from a page blob
            //Console.WriteLine("4. Read from a Page Blob");
            int bytesRead = await pageBlob.DownloadRangeToByteArrayAsync(samplePagedata, 0, 0, samplePagedata.Count());

            // Clean up after the demo
            Console.WriteLine("6. Delete page Blob");
            await pageBlob.DeleteIfExistsAsync();

            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();
        }
示例#2
0
        public UploadContext Create()
        {
            AssertIfValidhVhd(localVhd);
            AssertIfValidVhdSize(localVhd);

            this.blobObjectFactory.CreateContainer(blobDestination);

            UploadContext context   = null;
            bool          completed = false;

            try
            {
                context = new UploadContext
                {
                    DestinationBlob     = destinationBlob,
                    SingleInstanceMutex = AcquireSingleInstanceMutex(destinationBlob.Uri)
                };

                if (overWrite)
                {
                    destinationBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, requestOptions, operationContext: null)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                }

                if (destinationBlob.Exists(requestOptions))
                {
                    Program.SyncOutput.MessageResumingUpload();

                    if (destinationBlob.GetBlobMd5Hash(requestOptions) != null)
                    {
                        throw new InvalidOperationException(
                                  "An image already exists in blob storage with this name. If you want to upload again, use the Overwrite option.");
                    }
                    var metaData = destinationBlob.GetUploadMetaData();

                    AssertMetaDataExists(metaData);
                    AssertMetaDataMatch(metaData, OperationMetaData);

                    PopulateContextWithUploadableRanges(localVhd, context, true);
                    PopulateContextWithDataToUpload(localVhd, context);
                }
                else
                {
                    CreateRemoteBlobAndPopulateContext(context);
                }
                context.Md5HashOfLocalVhd = MD5HashOfLocalVhd;
                completed = true;
            }
            finally
            {
                if (!completed && context != null)
                {
                    context.Dispose();
                }
            }
            return(context);
        }
示例#3
0
        /// <summary>
        /// Deletes the page blob if it exists.
        /// </summary>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>true if it was deleted, false if it did not exist.</returns>
        public virtual async Task <bool> DeleteIfExistsAsync(CancellationToken?cancellationToken = null)
        {
            if (cancellationToken == null)
            {
                cancellationToken = CancellationToken.None;
            }

            this.EnsureInitialized();

            CloudPageBlob pageBlob = this.BlobContainer.GetPageBlobReference(this.BlobPath);

            return(await pageBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, CreateAccessCondition(),
                                                      this.RequestOptions, this.OperationContext, cancellationToken.Value));
        }
示例#4
0
        static async Task BlobAsync()
        {
            try
            {
                CloudStorageAccount sa = CloudStorageAccount.Parse(connectionString);
                CloudBlobClient     bc = sa.CreateCloudBlobClient();

                const string       CON_NAME = "smart-blob-container";
                CloudBlobContainer con      = bc.GetContainerReference(CON_NAME);
                bool rr = await con.CreateIfNotExistsAsync();

                const string  blobName = "my.txt";
                CloudPageBlob blob     = con.GetPageBlobReference(blobName);

                bool del = await blob.DeleteIfExistsAsync();

                await blob.CreateAsync(64 *1024, AccessCondition.GenerateIfNotExistsCondition(), new BlobRequestOptions(), new OperationContext());

                using (CloudBlobStream blobStream = await blob.OpenWriteAsync(null, AccessCondition.GenerateEmptyCondition(), new BlobRequestOptions(), new OperationContext()))
                {
                    byte[] sector = new byte[512];
                    for (int ii = 0; ii < sector.Length; ++ii)
                    {
                        sector[ii] = (byte)(ii % 26 + 'A');
                    }
                    MemoryStream mm = new MemoryStream(sector);
                    //byte[] buffer = Encoding.UTF8.GetBytes("zzz宏发科技恢复健康哈尔月UI风雅颂的法尔加zzz----");
                    //await blobStream.WriteAsync(buffer, 0, buffer.Length);
                    //await blobStream.WriteAsync(sector, 0, sector.Length - buffer.Length);
                    await blobStream.WriteAsync(sector, 0, sector.Length);

                    if (blobStream.CanSeek)
                    {
                        blobStream.Seek(1024, System.IO.SeekOrigin.Begin);
                    }

                    //buffer = Encoding.UTF8.GetBytes("this is some test");
                    //await blobStream.WriteAsync(buffer, 0, buffer.Length);
                    //await blobStream.WriteAsync(sector, 0, sector.Length - buffer.Length);
                    await blobStream.WriteAsync(sector, 0, sector.Length);

                    await blobStream.FlushAsync();
                }


                using (Stream blobStream = await blob.OpenReadAsync())
                {
                    byte[] buffer = new byte[2048];

                    const int firstReadCount = 8;
                    int       rc             = await blobStream.ReadAsync(buffer, 0, firstReadCount);

                    if (blobStream.CanSeek)
                    {
                        blobStream.Seek(rc, SeekOrigin.Begin);
                    }
                    rc = await blobStream.ReadAsync(buffer, 8, buffer.Length - firstReadCount);

                    string text = Encoding.UTF8.GetString(buffer);
                    Console.WriteLine(text);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex}");
            }
        }
示例#5
0
 /// <summary>
 /// Delete the blob async.
 /// </summary>
 /// <param name="blob">The cloud blob to delete.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The async task.</returns>
 public async Task <bool> DeleteBlobAsync(CloudPageBlob blob, CancellationToken cancellationToken)
 {
     return(await blob.DeleteIfExistsAsync(cancellationToken));
 }
示例#6
0
 /// <summary>
 /// Delete the blob async.
 /// </summary>
 /// <param name="blob">The cloud blob to delete.</param>
 /// <returns>The async task.</returns>
 public async Task <bool> DeleteBlobAsync(CloudPageBlob blob)
 {
     return(await blob.DeleteIfExistsAsync());
 }