Example #1
0
 private async Task Delete(CloudBlobContainer container, Uri blobUri)
 {
     CloudBlockBlob blob = new CloudBlockBlob(blobUri);
     if (blob.Container == container)
     {
         await blob.DeleteAsync();
     }
 }
        public async Task CloudBlockBlobCreateAndDeleteAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                await CreateForTestAsync(blob, 0, 0);

                Assert.IsTrue(await blob.ExistsAsync());
                await blob.DeleteAsync();
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Example #3
0
        public async Task ParallelDownloadToEmptyFileTest()
        {
            string             inputFileName  = Path.GetTempFileName();
            string             outputFileName = Path.GetTempPath() + "output.tmp";
            CloudBlobContainer container      = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

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


                FileStream fs = File.Create(inputFileName);
                fs.Close();

                BlobRequestOptions options = new BlobRequestOptions();
                options.ParallelOperationThreadCount = 16;
                await blob.UploadFromFileAsync(inputFileName, null, options, null);

                Assert.IsFalse(File.Exists(outputFileName));
                await blob.DownloadToFileParallelAsync(
                    outputFileName,
                    FileMode.Create,
                    16,
                    null);

                Assert.IsTrue(File.Exists(outputFileName));

                await blob.DeleteAsync();
            }
            finally
            {
                container.DeleteIfExists();
                File.Delete(inputFileName);
                File.Delete(outputFileName);
            }
        }
        public async Task CloudBlockBlobCopyFromSnapshotTestAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob source = container.GetBlockBlobReference("source");

                string data = "String data";
                await UploadTextAsync(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                await source.SetMetadataAsync();

                CloudBlockBlob snapshot = await source.CreateSnapshotAsync();

                //Modify source
                string newData = "Hello";
                source.Metadata["Test"] = "newvalue";
                await source.SetMetadataAsync();

                source.Properties.ContentMD5 = null;
                await UploadTextAsync(source, newData, Encoding.UTF8);

                Assert.AreEqual(newData, await DownloadTextAsync(source, Encoding.UTF8), "Source is modified correctly");
                Assert.AreEqual(data, await DownloadTextAsync(snapshot, Encoding.UTF8), "Modifying source blob should not modify snapshot");

                await source.FetchAttributesAsync();

                await snapshot.FetchAttributesAsync();

                Assert.AreNotEqual(source.Metadata["Test"], snapshot.Metadata["Test"], "Source and snapshot metadata should be independent");

                CloudBlockBlob copy = container.GetBlockBlobReference("copy");
                await copy.StartCopyFromBlobAsync(TestHelper.Defiddler(snapshot));
                await WaitForCopyAsync(copy);

                Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status);
                Assert.AreEqual(data, await DownloadTextAsync(copy, Encoding.UTF8), "Data inside copy of blob not similar");

                await copy.FetchAttributesAsync();

                BlobProperties prop1 = copy.Properties;
                BlobProperties prop2 = snapshot.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentDisposition, prop2.ContentDisposition);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);

                Assert.AreEqual("value", copy.Metadata["Test"], false, "Copied metadata not same");

                await copy.DeleteAsync();
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlockBlobCopyTestAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudBlockBlob source = container.GetBlockBlobReference("source");

                string data = "String data";
                await UploadTextAsync(source, data, Encoding.UTF8);

                source.Metadata["Test"] = "value";
                await source.SetMetadataAsync();

                CloudBlockBlob copy   = container.GetBlockBlobReference("copy");
                string         copyId = await copy.StartCopyFromBlobAsync(TestHelper.Defiddler(source));
                await WaitForCopyAsync(copy);

                Assert.AreEqual(CopyStatus.Success, copy.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, copy.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, copy.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, copy.CopyState.BytesCopied);
                Assert.AreEqual(copyId, copy.CopyState.CopyId);
                Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                OperationContext opContext = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async() => await copy.AbortCopyAsync(copyId, null, null, opContext),
                    opContext,
                    "Aborting a copy operation after completion should fail",
                    HttpStatusCode.Conflict,
                    "NoPendingCopyOperation");

                await source.FetchAttributesAsync();

                Assert.IsNotNull(copy.Properties.ETag);
                Assert.AreNotEqual(source.Properties.ETag, copy.Properties.ETag);
                Assert.IsTrue(copy.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                string copyData = await DownloadTextAsync(copy, Encoding.UTF8);

                Assert.AreEqual(data, copyData, "Data inside copy of blob not similar");

                await copy.FetchAttributesAsync();

                BlobProperties prop1 = copy.Properties;
                BlobProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                Assert.AreEqual(prop1.ContentDisposition, prop2.ContentDisposition);
                Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding);
                Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage);
                Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5);
                Assert.AreEqual(prop1.ContentType, prop2.ContentType);

                Assert.AreEqual("value", copy.Metadata["Test"], false, "Copied metadata not same");

                await copy.DeleteAsync();
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        /// <summary>
        /// Tests a blob SAS to determine which operations it allows.
        /// </summary>
        /// <param name="sasUri">A string containing a URI with a SAS appended.</param>
        /// <param name="blobContent">A string content content to write to the blob.</param>
        /// <returns>A Task object.</returns>
        private static async Task TestBlobSASAsync(string sasUri, string blobContent)
        {
            // Try performing blob operations using the SAS provided.

            // Return a reference to the blob using the SAS URI.
            CloudBlockBlob blob = new CloudBlockBlob(new Uri(sasUri));

            // Create operation: Upload a blob with the specified name to the container.
            // If the blob does not exist, it will be created. If it does exist, it will be overwritten.
            try
            {
                MemoryStream msWrite = new MemoryStream(Encoding.UTF8.GetBytes(blobContent));
                msWrite.Position = 0;
                using (msWrite)
                {
                    await blob.UploadFromStreamAsync(msWrite);
                }

                Console.WriteLine("Create operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Create operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Write operation: Add metadata to the blob
            try
            {
                await blob.FetchAttributesAsync();
                string rnd = new Random().Next().ToString();
                string metadataName = "name";
                string metadataValue = "value";
                blob.Metadata.Add(metadataName, metadataValue);
                await blob.SetMetadataAsync();

                Console.WriteLine("Write operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Write operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Read operation: Read the contents of the blob.
            try
            {
                MemoryStream msRead = new MemoryStream();
                using (msRead)
                {
                    await blob.DownloadToStreamAsync(msRead);
                    msRead.Position = 0;
                    using (StreamReader reader = new StreamReader(msRead, true))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            Console.WriteLine(line);
                        }
                    }

                    Console.WriteLine();
                }

                Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Read operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Delete operation: Delete the blob.
            try
            {
                await blob.DeleteAsync();
                Console.WriteLine("Delete operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Delete operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }
        }
        /// <summary>
        /// Test blob writing, expecting success.
        /// </summary>
        /// <param name="testBlob">The blob to test.</param>
        /// <param name="sourceBlob">A blob to use as the source of a copy.</param>
        /// <param name="testAccessCondition">The access condition to use.</param>
        private async Task BlobWriteExpectLeaseSuccessAsync(CloudBlockBlob testBlob, CloudBlob sourceBlob, AccessCondition testAccessCondition)
        {
            await testBlob.SetMetadataAsync(testAccessCondition, null /* options */, null);
            await testBlob.SetPropertiesAsync(testAccessCondition, null /* options */, null);
            await UploadTextAsync(testBlob, "No Problem", Encoding.UTF8, testAccessCondition, null /* options */, null);
            await testBlob.StartCopyAsync(TestHelper.Defiddler(sourceBlob.Uri), null /* source access condition */, testAccessCondition, null /* options */, null);

            while (testBlob.CopyState.Status == CopyStatus.Pending)
            {
                await Task.Delay(1000);
                await testBlob.FetchAttributesAsync();
            }

            var writeStream = await testBlob.OpenWriteAsync(testAccessCondition, null /* options */, null);
            Stream stream = writeStream.AsStreamForWrite();
            stream.WriteByte(0);
            await stream.FlushAsync();

            await testBlob.DeleteAsync(DeleteSnapshotsOption.None, testAccessCondition, null /* options */, null);
        }
        /// <summary>
        /// Test blob write and creation, expecting lease failure.
        /// </summary>
        /// <param name="testBlob">The blob to test.</param>
        /// <param name="sourceBlob">A blob to use as the source of a copy.</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 BlobWriteExpectLeaseFailureAsync(CloudBlockBlob testBlob, CloudBlockBlob sourceBlob, AccessCondition testAccessCondition, HttpStatusCode expectedStatusCode, string expectedErrorCode, string description)
        {
            await this.BlobCreateExpectLeaseFailureAsync(testBlob, sourceBlob, testAccessCondition, expectedStatusCode, expectedErrorCode, description);

            OperationContext operationContext = new OperationContext();
            await TestHelper.ExpectedExceptionAsync(
                async () => await testBlob.SetMetadataAsync(testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Set Metadata)",
                expectedStatusCode,
                expectedErrorCode);
            await TestHelper.ExpectedExceptionAsync(
                async () => await testBlob.SetPropertiesAsync(testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Set Properties)",
                expectedStatusCode,
                expectedErrorCode);
            await TestHelper.ExpectedExceptionAsync(
                async () => await testBlob.DeleteAsync(DeleteSnapshotsOption.None, testAccessCondition, null /* options */, operationContext),
                operationContext,
                description + " (Delete)",
                expectedStatusCode,
                expectedErrorCode);
        }
        /// <summary>
        /// Test blob writing, expecting success.
        /// </summary>
        /// <param name="testBlob">The blob to test.</param>
        /// <param name="sourceBlob">A blob to use as the source of a copy.</param>
        /// <param name="testAccessCondition">The access condition to use.</param>
        private void BlobWriteExpectLeaseSuccessTask(CloudBlockBlob testBlob, CloudBlob sourceBlob, AccessCondition testAccessCondition)
        {
            testBlob.SetMetadataAsync(testAccessCondition, null /* options */, new OperationContext()).Wait();
            testBlob.SetPropertiesAsync(testAccessCondition, null /* options */, new OperationContext()).Wait();
            UploadTextTask(testBlob, "No Problem", Encoding.UTF8, testAccessCondition, null /* options */, new OperationContext());
            testBlob.StartCopyAsync(
                TestHelper.Defiddler(sourceBlob.Uri),
                null /* source access condition */,
                testAccessCondition,
                null /* options */,
                new OperationContext()).Wait();

            while (testBlob.CopyState.Status == CopyStatus.Pending)
            {
                Thread.Sleep(1000);
                testBlob.FetchAttributesAsync().Wait();
            }

            Stream stream = testBlob.OpenWriteAsync(testAccessCondition, null /* options */, new OperationContext()).Result;
            stream.WriteByte(0);
            stream.Flush();

            testBlob.DeleteAsync(DeleteSnapshotsOption.None, testAccessCondition, null /* options */, new OperationContext());
        }
        public async Task<bool> DeletePictureFormCloud(PictureViewModel pictureViewModel)
        {
            try
            {
                var blob = new CloudBlockBlob(new Uri(pictureViewModel.PictureUrl), App.credentials);
                await blob.DeleteAsync();

                var tableClient = App.account.CreateCloudTableClient();
                var table = tableClient.GetTableReference(App.tableName);

                var operation = TableOperation.Delete(pictureViewModel.PictureTableEntity);
                await table.ExecuteAsync(operation);

                allImages.Remove(pictureViewModel);
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }