Beispiel #1
0
        public static async Task <List <string> > CreateBlobsAsync(CloudBlobContainer container, int count, BlobType type)
        {
            string        name;
            List <string> blobs = new List <string>();

            for (int i = 0; i < count; i++)
            {
                switch (type)
                {
                case BlobType.BlockBlob:
                    name = "bb" + Guid.NewGuid().ToString();
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);
                    await blockBlob.PutBlockListAsync(new string[] { });

                    blobs.Add(name);
                    break;

                case BlobType.PageBlob:
                    name = "pb" + Guid.NewGuid().ToString();
                    CloudPageBlob pageBlob = container.GetPageBlobReference(name);
                    await pageBlob.CreateAsync(0);

                    blobs.Add(name);
                    break;
                }
            }
            return(blobs);
        }
        public static List <string> CreateBlobsTask(CloudBlobContainer container, int count, BlobType type)
        {
            string        name;
            List <string> blobs = new List <string>();

            for (int i = 0; i < count; i++)
            {
                switch (type)
                {
                case BlobType.BlockBlob:
                    name = "bb" + Guid.NewGuid().ToString();
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);
                    blockBlob.PutBlockListAsync(new string[] { }).Wait();
                    blobs.Add(name);
                    break;

                case BlobType.PageBlob:
                    name = "pb" + Guid.NewGuid().ToString();
                    CloudPageBlob pageBlob = container.GetPageBlobReference(name);
                    pageBlob.CreateAsync(0).Wait();
                    blobs.Add(name);
                    break;

                case BlobType.AppendBlob:
                    name = "ab" + Guid.NewGuid().ToString();
                    CloudAppendBlob appendBlob = container.GetAppendBlobReference(name);
                    appendBlob.CreateOrReplaceAsync().Wait();
                    blobs.Add(name);
                    break;
                }
            }
            return(blobs);
        }
        public async Task CloudBlobContainerGetBlobReferenceFromServerAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                await blockBlob.PutBlockListAsync(new List <string>());

                CloudPageBlob pageBlob = container.GetPageBlobReference("pb");
                await pageBlob.CreateAsync(0);

                ICloudBlob blob1 = await container.GetBlobReferenceFromServerAsync("bb");

                Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob));

                ICloudBlob blob2 = await container.GetBlobReferenceFromServerAsync("pb");

                Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob));

                ICloudBlob blob3 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri);

                Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob));

                ICloudBlob blob4 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri);

                Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobDownloadBlockListAsync()
        {
            byte[]             buffer      = GetRandomBuffer(1024);
            List <string>      blocks      = GetBlockIdList(3);
            List <string>      extraBlocks = GetBlockIdList(2);
            CloudBlobContainer container   = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                foreach (string block in blocks)
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        await blob.PutBlockAsync(block, memoryStream.AsInputStream(), null);
                    }
                }
                await blob.PutBlockListAsync(blocks);

                foreach (string block in extraBlocks)
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        await blob.PutBlockAsync(block, memoryStream.AsInputStream(), null);
                    }
                }

                CloudBlockBlob blob2 = container.GetBlockBlobReference("blob1");
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(1024 * blocks.Count, blob2.Properties.Length);

                IEnumerable <ListBlockItem> blockList = await blob2.DownloadBlockListAsync();

                foreach (ListBlockItem blockItem in blockList)
                {
                    Assert.IsTrue(blockItem.Committed);
                    Assert.IsTrue(blocks.Remove(blockItem.Name));
                }
                Assert.AreEqual(0, blocks.Count);

                blockList = await blob2.DownloadBlockListAsync(BlockListingFilter.Uncommitted, null, null, null);

                foreach (ListBlockItem blockItem in blockList)
                {
                    Assert.IsFalse(blockItem.Committed);
                    Assert.IsTrue(extraBlocks.Remove(blockItem.Name));
                }
                Assert.AreEqual(0, extraBlocks.Count);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobUploadAsync()
        {
            byte[]             buffer      = GetRandomBuffer(1024);
            List <string>      blocks      = GetBlockIdList(3);
            List <string>      extraBlocks = GetBlockIdList(2);
            CloudBlobContainer container   = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    CloudBlockBlob blob = container.GetBlockBlobReference("blob1");

                    foreach (string block in blocks)
                    {
                        using (MemoryStream memoryStream = new MemoryStream(buffer))
                        {
                            await blob.PutBlockAsync(block, memoryStream.AsInputStream(), null);
                        }
                        wholeBlob.Write(buffer, 0, buffer.Length);
                    }
                    foreach (string block in extraBlocks)
                    {
                        using (MemoryStream memoryStream = new MemoryStream(buffer))
                        {
                            await blob.PutBlockAsync(block, memoryStream.AsInputStream(), null);
                        }
                    }

                    await blob.PutBlockListAsync(blocks);

                    CloudBlockBlob blob2 = container.GetBlockBlobReference("blob1");
                    using (MemoryStream downloadedBlob = new MemoryStream())
                    {
                        await blob2.DownloadToStreamAsync(downloadedBlob.AsOutputStream());

                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob);
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        private static async Task CreateForTestAsync(CloudBlockBlob blob, int blockCount, int blockSize, bool commit = true)
        {
            byte[] buffer = GetRandomBuffer(blockSize);
            List<string> blocks = GetBlockIdList(blockCount);

            foreach (string block in blocks)
            {
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    await blob.PutBlockAsync(block, stream.AsInputStream(), null);
                }
            }

            if (commit)
            {
                await blob.PutBlockListAsync(blocks);
            }
        }
        internal static async Task CreateForTestAsync(CloudBlockBlob blob, int blockCount, int blockSize, bool commit = true)
        {
            byte[]        buffer = GetRandomBuffer(blockSize);
            List <string> blocks = GetBlockIdList(blockCount);

            foreach (string block in blocks)
            {
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    await blob.PutBlockAsync(block, stream, null);
                }
            }

            if (commit)
            {
                await blob.PutBlockListAsync(blocks);
            }
        }
        public async Task CloudBlockBlobMethodsOnPageBlobAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                List <string> blobs = await CreateBlobsAsync(container, 1, BlobType.PageBlob);

                CloudBlockBlob blob      = container.GetBlockBlobReference(blobs.First());
                List <string>  blockList = GetBlockIdList(1);

                OperationContext operationContext = new OperationContext();
                byte[]           buffer           = new byte[1];
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    await TestHelper.ExpectedExceptionAsync(
                        async() => await blob.PutBlockAsync(blockList.First(), stream.AsInputStream(), null, null, null, operationContext),
                        operationContext,
                        "Block operations should fail on page blobs",
                        HttpStatusCode.Conflict,
                        "InvalidBlobType");
                }

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.PutBlockListAsync(blockList, null, null, operationContext),
                    operationContext,
                    "Block operations should fail on page blobs",
                    HttpStatusCode.Conflict,
                    "InvalidBlobType");

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.DownloadBlockListAsync(BlockListingFilter.Committed, null, null, operationContext),
                    operationContext,
                    "Block operations should fail on page blobs",
                    HttpStatusCode.Conflict,
                    "InvalidBlobType");
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
 /// <summary>
 /// Test block blob creation (block list setting), expecting lease failure.
 /// </summary>
 /// <param name="testBlob">The block blob.</param>
 /// <param name="blockList">An appropriate block list to set.</param>
 /// <param name="testAccessCondition">The failing access condition to use.</param>
 /// <param name="expectedErrorCode">The expected error code.</param>
 /// <param name="description">The reason why these calls should fail.</param>
 private async Task BlockBlobWriteExpectLeaseFailureAsync(CloudBlockBlob testBlob, IEnumerable<string> blockList, AccessCondition testAccessCondition, HttpStatusCode expectedStatusCode, string expectedErrorCode, string description)
 {
     OperationContext operationContext = new OperationContext();
     await TestHelper.ExpectedExceptionAsync(
         async () => await testBlob.PutBlockListAsync(blockList, testAccessCondition, null /* options */, operationContext),
         operationContext,
         description + " (Put Block List)",
         expectedStatusCode,
         expectedErrorCode);
 }
        /// <summary>
        /// Sends every chunk of the .fcs file and sends an sms to the user
        /// </summary>
        /// <param name="model"></param>
        /// <param name="blockBlob"></param>
        /// <returns></returns>
        private async Task<ActionResult> CommitAllChunks(CloudFile model, CloudBlockBlob blockBlob)
        {
            model.IsUploadCompleted = true;

            var errorInOperation = false;

            try
            {
                var blockList = Enumerable.Range(1, (int)model.BlockCount).ToList().Select(rangeElement =>
                               Convert.ToBase64String(Encoding.UTF8.GetBytes(
                               string.Format(CultureInfo.InvariantCulture, "{0:D4}", rangeElement))));

                //model.BlockBlob.PutBlockListAsync(blockList);
                await blockBlob.PutBlockListAsync(blockList);

                var duration = DateTime.Now - model.StartTime;

                float fileSizeInKb = model.Size / 1024;

                var fileSizeMessage = fileSizeInKb > 1024 ?
                    string.Concat((fileSizeInKb / 1024).ToString(CultureInfo.CurrentCulture), " MB") :
                    string.Concat(fileSizeInKb.ToString(CultureInfo.CurrentCulture), " KB");

                var message = string.Format(CultureInfo.CurrentCulture,
                    "File uploaded successfully. {0} took {1} seconds to upload\n",
                    fileSizeMessage, duration.TotalSeconds);

                //Get the user
                var user = GetUser();
                //var fcsPath = user.LastName.ToLower() + "-" + user.FirstName.ToLower() + "-" + user.Id + "/" + model.FileName;
                var fcsPath = user.LastName.ToLower() + "-" + user.FirstName.ToLower() + "/" + model.FileName;

                var storedPatient = _context.Patients.First(x => x.Id == model.Patient);

                var analysis = new Analysis
                {
                    Date = DateTime.Now.Date,
                    FcsFilePath = fcsPath,
                    FcsUploadDate = DateTime.Now.Date.ToString("MM-dd-yyyy-hh-mm"),
                    ResultFilePath = "",
                    ResultDate = DateTime.Now.Date,
                    Delta = 0.00
                };

                storedPatient.Analyses.Add(analysis);
                user.Analyses.Add(analysis);
                _context.SaveChanges();

                if (!string.IsNullOrWhiteSpace(user.Phone))
                {
                    //send message to the user
                    _smsSender.SendSms(new AuthMessageSender.Message
                    {
                        Body = "Greetings" + "\nStatus on: " + model.OriginalFileName + "\n" + message
                    }, _sid, _authToken, _number, user.Phone);
                }

                model.UploadStatusMessage = message;
            }
            catch (StorageException e)
            {
                model.UploadStatusMessage = "Failed to Upload file. Exception - " + e.Message;
                errorInOperation = true;
            }
            finally
            {
                HttpContext.Session.Remove("CurrentFile");
            }
            return Json(new
            {
                error = errorInOperation,
                isLastBlock = model.IsUploadCompleted,
                message = model.UploadStatusMessage
            });
        }
        public async Task CloudBlobContainerGetBlobReferenceFromServerAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                await blockBlob.PutBlockListAsync(new List <string>());

                CloudPageBlob pageBlob = container.GetPageBlobReference("pb");
                await pageBlob.CreateAsync(0);

                CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab");
                await appendBlob.CreateOrReplaceAsync();

                CloudBlobClient client;
                ICloudBlob      blob;

                blob = await container.GetBlobReferenceFromServerAsync("bb");

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                CloudBlockBlob blockBlobSnapshot = await((CloudBlockBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSnapshotUri);

                AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.GetBlobReferenceFromServerAsync("pb");

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                CloudPageBlob pageBlobSnapshot = await((CloudPageBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSnapshotUri);

                AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.GetBlobReferenceFromServerAsync("ab");

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                CloudAppendBlob appendBlobSnapshot = await((CloudAppendBlob)blob).CreateSnapshotAsync();
                await blob.SetPropertiesAsync();

                Uri appendBlobSnapshotUri = new Uri(appendBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + appendBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSnapshotUri);

                AssertAreEqual(appendBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.Uri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.StorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                string             blockBlobToken = blockBlob.GetSharedAccessSignature(policy);
                StorageCredentials blockBlobSAS   = new StorageCredentials(blockBlobToken);
                Uri        blockBlobSASUri        = blockBlobSAS.TransformUri(blockBlob.Uri);
                StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);

                string             appendBlobToken = appendBlob.GetSharedAccessSignature(policy);
                StorageCredentials appendBlobSAS   = new StorageCredentials(appendBlobToken);
                Uri        appendBlobSASUri        = appendBlobSAS.TransformUri(appendBlob.Uri);
                StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri);

                string             pageBlobToken = pageBlob.GetSharedAccessSignature(policy);
                StorageCredentials pageBlobSAS   = new StorageCredentials(pageBlobToken);
                Uri        pageBlobSASUri        = pageBlobSAS.TransformUri(pageBlob.Uri);
                StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.BaseUri, appendBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(appendBlobSASUri);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.StorageUri, blockBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.StorageUri, appendBlobSAS);
                blob   = await client.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null);

                Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Beispiel #12
0
        private static async Task AppendToBlob(CloudBlockBlob blockBlob, string content, string md5)
        {
            var leaseId = await blockBlob.AcquireLeaseAsync(TimeSpan.FromSeconds(30), null);
            var access = AccessCondition.GenerateLeaseCondition(leaseId);
            var options = new BlobRequestOptions();
            var context = new OperationContext();

            try
            {
                var blockId = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
                {
                    stream.Position = 0;
                    await blockBlob.PutBlockAsync(blockId, stream, md5, access, options, context);
                }

                var blockList = await blockBlob.DownloadBlockListAsync(BlockListingFilter.Committed, access, options, context);
                var blockIds = blockList.Select(x => x.Name).ToList();
                blockIds.Add(blockId);
                await blockBlob.PutBlockListAsync(blockIds, access, options, context);
            }
            catch(Exception ex)
            {
                //TODO - logging
            }
            finally
            {
                await blockBlob.ReleaseLeaseAsync(access);
            }
        }
Beispiel #13
0
        public async Task CloudBlobSnapshotAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                MemoryStream   originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudBlockBlob blockBlob    = container.GetBlockBlobReference(BlobName);
                await blockBlob.UploadFromStreamAsync(originalData);

                CloudBlob blob = container.GetBlobReference(BlobName);
                await blob.FetchAttributesAsync();

                Assert.IsFalse(blob.IsSnapshot);
                Assert.IsNull(blob.SnapshotTime, "Root blob has SnapshotTime set");
                Assert.IsFalse(blob.SnapshotQualifiedUri.Query.Contains("snapshot"));
                Assert.AreEqual(blob.Uri, blob.SnapshotQualifiedUri);

                CloudBlob snapshot1 = await blob.SnapshotAsync();

                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);
                Assert.IsTrue(snapshot1.IsSnapshot);
                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");
                Assert.AreEqual(blob.Uri, snapshot1.Uri);
                Assert.AreNotEqual(blob.SnapshotQualifiedUri, snapshot1.SnapshotQualifiedUri);
                Assert.AreNotEqual(snapshot1.Uri, snapshot1.SnapshotQualifiedUri);
                Assert.IsTrue(snapshot1.SnapshotQualifiedUri.Query.Contains("snapshot"));

                CloudBlob snapshot2 = await blob.SnapshotAsync();

                Assert.IsTrue(snapshot2.SnapshotTime.Value > snapshot1.SnapshotTime.Value);

                await snapshot1.FetchAttributesAsync();

                await snapshot2.FetchAttributesAsync();

                await blob.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, blob.Properties);

                CloudBlob snapshot1Clone = new CloudBlob(new Uri(blob.Uri + "?snapshot=" + snapshot1.SnapshotTime.Value.ToString("O")), blob.ServiceClient.Credentials);
                Assert.IsNotNull(snapshot1Clone.SnapshotTime, "Snapshot clone does not have SnapshotTime set");
                Assert.AreEqual(snapshot1.SnapshotTime.Value, snapshot1Clone.SnapshotTime.Value);
                await snapshot1Clone.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, snapshot1Clone.Properties);

                CloudBlob snapshotCopy = container.GetBlobReference("blob2");
                await snapshotCopy.StartCopyAsync(TestHelper.Defiddler(snapshot1.Uri));
                await WaitForCopyAsync(snapshotCopy);

                Assert.AreEqual(CopyStatus.Success, snapshotCopy.CopyState.Status);

                using (Stream snapshotStream = (await snapshot1.OpenReadAsync()))
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                await blockBlob.PutBlockListAsync(new List <string>());

                await blob.FetchAttributesAsync();

                using (Stream snapshotStream = (await snapshot1.OpenReadAsync()))
                {
                    snapshotStream.Seek(0, SeekOrigin.End);
                    TestHelper.AssertStreamsAreEqual(originalData, snapshotStream);
                }

                BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, null, null);

                List <IListBlobItem> blobs = resultSegment.Results.ToList();
                Assert.AreEqual(4, blobs.Count);
                AssertAreEqual(snapshot1, (CloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (CloudBlob)blobs[1]);
                AssertAreEqual(blob, (CloudBlob)blobs[2]);
                AssertAreEqual(snapshotCopy, (CloudBlob)blobs[3]);
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task BlockBlobWriteStreamOpenWithAccessConditionAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            await container.CreateAsync();

            try
            {
                OperationContext context = new OperationContext();

                CloudBlockBlob existingBlob = container.GetBlockBlobReference("blob");
                await existingBlob.PutBlockListAsync(new List <string>());

                CloudBlockBlob  blob            = container.GetBlockBlobReference("blob2");
                AccessCondition accessCondition = AccessCondition.GenerateIfMatchCondition(existingBlob.Properties.ETag);
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.OpenWriteAsync(accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.NotFound);

                blob            = container.GetBlockBlobReference("blob3");
                accessCondition = AccessCondition.GenerateIfNoneMatchCondition(existingBlob.Properties.ETag);
                IOutputStream blobStream = await blob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                blob            = container.GetBlockBlobReference("blob4");
                accessCondition = AccessCondition.GenerateIfNoneMatchCondition("*");
                blobStream      = await blob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                blob            = container.GetBlockBlobReference("blob5");
                accessCondition = AccessCondition.GenerateIfModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(1));
                blobStream      = await blob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                blob            = container.GetBlockBlobReference("blob6");
                accessCondition = AccessCondition.GenerateIfNotModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(-1));
                blobStream      = await blob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfMatchCondition(existingBlob.Properties.ETag);
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfMatchCondition(blob.Properties.ETag);
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.PreconditionFailed);

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition(blob.Properties.ETag);
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition(existingBlob.Properties.ETag);
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.NotModified);

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition("*");
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                await TestHelper.ExpectedExceptionAsync(
                    () =>
                {
                    blobStream.Dispose();
                    return(Task.FromResult(true));
                },
                    context,
                    "BlobWriteStream.Dispose with a non-met condition should fail",
                    HttpStatusCode.Conflict);

                accessCondition = AccessCondition.GenerateIfModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(-1));
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(1));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.NotModified);

                accessCondition = AccessCondition.GenerateIfNotModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(1));
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfNotModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(-1));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.PreconditionFailed);

                accessCondition = AccessCondition.GenerateIfMatchCondition(existingBlob.Properties.ETag);
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                await existingBlob.SetPropertiesAsync();

                await TestHelper.ExpectedExceptionAsync(
                    () =>
                {
                    blobStream.Dispose();
                    return(Task.FromResult(true));
                },
                    context,
                    "BlobWriteStream.Dispose with a non-met condition should fail",
                    HttpStatusCode.PreconditionFailed);

                blob            = container.GetBlockBlobReference("blob7");
                accessCondition = AccessCondition.GenerateIfNoneMatchCondition("*");
                blobStream      = await blob.OpenWriteAsync(accessCondition, null, context);

                await blob.PutBlockListAsync(new List <string>());

                await TestHelper.ExpectedExceptionAsync(
                    () =>
                {
                    blobStream.Dispose();
                    return(Task.FromResult(true));
                },
                    context,
                    "BlobWriteStream.Dispose with a non-met condition should fail",
                    HttpStatusCode.Conflict);

                blob            = container.GetBlockBlobReference("blob8");
                accessCondition = AccessCondition.GenerateIfNotModifiedSinceCondition(existingBlob.Properties.LastModified.Value);
                blobStream      = await existingBlob.OpenWriteAsync(accessCondition, null, context);

                await existingBlob.SetPropertiesAsync();

                await TestHelper.ExpectedExceptionAsync(
                    () =>
                {
                    blobStream.Dispose();
                    return(Task.FromResult(true));
                },
                    context,
                    "BlobWriteStream.Dispose with a non-met condition should fail",
                    HttpStatusCode.PreconditionFailed);
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
 /// <summary>
 /// Test block blob creation (set block list), expecting success.
 /// </summary>
 /// <param name="testBlob">The block blob.</param>
 /// <param name="blockList">The block list to set.</param>
 /// <param name="testAccessCondition">The access condition to use.</param>
 private async Task BlockBlobWriteExpectSuccessAsync(CloudBlockBlob testBlob, IEnumerable<string> blockList, AccessCondition testAccessCondition)
 {
     await testBlob.PutBlockListAsync(blockList, testAccessCondition, null /* options */, null);
 }
        public async Task CloudBlobContainerGetBlobReferenceFromServerAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                await blockBlob.PutBlockListAsync(new List <string>());

                CloudPageBlob pageBlob = container.GetPageBlobReference("pb");
                await pageBlob.CreateAsync(0);

                ICloudBlob blob1 = await container.GetBlobReferenceFromServerAsync("bb");

                Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob));

                CloudBlockBlob blob1Snapshot = await((CloudBlockBlob)blob1).CreateSnapshotAsync();
                await blob1.SetPropertiesAsync();

                Uri        blob1SnapshotUri       = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                ICloudBlob blob1SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob1SnapshotUri);

                AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties);

                ICloudBlob blob2 = await container.GetBlobReferenceFromServerAsync("pb");

                Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob));

                CloudPageBlob blob2Snapshot = await((CloudPageBlob)blob2).CreateSnapshotAsync();
                await blob2.SetPropertiesAsync();

                Uri        blob2SnapshotUri       = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                ICloudBlob blob2SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob2SnapshotUri);

                AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties);

                ICloudBlob blob3 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri);

                Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob));

                ICloudBlob blob4 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri);

                Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob));

                string             blockBlobToken = blockBlob.GetSharedAccessSignature(policy);
                StorageCredentials blockBlobSAS   = new StorageCredentials(blockBlobToken);
                Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri);

                string             pageBlobToken = pageBlob.GetSharedAccessSignature(policy);
                StorageCredentials pageBlobSAS   = new StorageCredentials(pageBlobToken);
                Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri);

                ICloudBlob blob5 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob));

                ICloudBlob blob6 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob));

                CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                ICloudBlob      blob7   = await client7.GetBlobReferenceFromServerAsync(blockBlobSASUri);

                Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob));

                CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS);
                ICloudBlob      blob8   = await client8.GetBlobReferenceFromServerAsync(pageBlobSASUri);

                Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobBlockReorderingAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");

                List <string> originalBlockIds = GetBlockIdList(10);
                List <string> blockIds         = new List <string>(originalBlockIds);
                List <byte[]> blocks           = new List <byte[]>();
                for (int i = 0; i < blockIds.Count; i++)
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(i.ToString());
                    using (MemoryStream stream = new MemoryStream(buffer))
                    {
                        await blob.PutBlockAsync(blockIds[i], stream.AsInputStream(), null);
                    }
                    blocks.Add(buffer);
                }
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("0123456789", await DownloadTextAsync(blob, Encoding.UTF8));

                blockIds.RemoveAt(0);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("123456789", await DownloadTextAsync(blob, Encoding.UTF8));

                blockIds.RemoveAt(8);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("12345678", await DownloadTextAsync(blob, Encoding.UTF8));

                blockIds.RemoveAt(3);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("1235678", await DownloadTextAsync(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[9]))
                {
                    await blob.PutBlockAsync(originalBlockIds[9], stream.AsInputStream(), null);
                }
                blockIds.Insert(0, originalBlockIds[9]);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("91235678", await DownloadTextAsync(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[0]))
                {
                    await blob.PutBlockAsync(originalBlockIds[0], stream.AsInputStream(), null);
                }
                blockIds.Add(originalBlockIds[0]);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("912356780", await DownloadTextAsync(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[4]))
                {
                    await blob.PutBlockAsync(originalBlockIds[4], stream.AsInputStream(), null);
                }
                blockIds.Insert(2, originalBlockIds[4]);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("9142356780", await DownloadTextAsync(blob, Encoding.UTF8));

                blockIds.Insert(0, originalBlockIds[0]);
                await blob.PutBlockListAsync(blockIds);

                Assert.AreEqual("09142356780", await DownloadTextAsync(blob, Encoding.UTF8));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }