Exemplo n.º 1
0
        public async Task CloudPageBlobAlignmentAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob    blob             = container.GetPageBlobReference("blob1");
                OperationContext operationContext = new OperationContext();

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.CreateAsync(511, null, null, operationContext),
                    operationContext,
                    "Page operations that are not 512-byte aligned should fail",
                    HttpStatusCode.BadRequest);

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.CreateAsync(513, null, null, operationContext),
                    operationContext,
                    "Page operations that are not 512-byte aligned should fail",
                    HttpStatusCode.BadRequest);

                await blob.CreateAsync(512);

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.SetLength(511);
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await blob.WritePagesAsync(stream.AsInputStream(), 0, null, null, null, operationContext),
                        "Page operations that are not 512-byte aligned should fail");
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.SetLength(513);
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await blob.WritePagesAsync(stream.AsInputStream(), 0, null, null, null, operationContext),
                        "Page operations that are not 512-byte aligned should fail");
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.SetLength(512);
                    await blob.WritePagesAsync(stream.AsInputStream(), 0, null);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 2
0
        public async Task CloudPageBlobResizeAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob  = container.GetPageBlobReference("blob1");
                CloudPageBlob blob2 = container.GetPageBlobReference("blob1");

                await blob.CreateAsync(1024);

                Assert.AreEqual(1024, blob.Properties.Length);
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(1024, blob2.Properties.Length);
                await blob.ResizeAsync(2048);

                Assert.AreEqual(2048, blob.Properties.Length);
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(2048, blob2.Properties.Length);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        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);
        }
Exemplo n.º 5
0
        public async Task CloudBlobDirectoryGetParentAsync()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                string             name      = GetRandomContainerName();
                CloudBlobContainer container = client.GetContainerReference(name);
                try
                {
                    await container.CreateAsync();

                    CloudPageBlob blob = container.GetPageBlobReference("Dir1" + delimiter + "Blob1");
                    await blob.CreateAsync(0);

                    Assert.IsTrue(await blob.ExistsAsync());
                    Assert.AreEqual("Dir1" + delimiter + "Blob1", blob.Name);

                    // get the blob's parent
                    CloudBlobDirectory parent = blob.Parent;
                    Assert.AreEqual(parent.Prefix, "Dir1" + delimiter);

                    // get container as parent
                    CloudBlobDirectory root = parent.Parent;
                    Assert.AreEqual(root.Prefix, "");

                    // make sure the parent of the container dir is null
                    CloudBlobDirectory empty = root.Parent;
                    Assert.IsNull(empty);

                    // from container, get directory reference to container
                    root = container.GetDirectoryReference("");
                    Assert.AreEqual("", root.Prefix);
                    Assert.AreEqual(container.Uri.AbsoluteUri, root.Uri.AbsoluteUri);

                    BlobResultSegment segment = await root.ListBlobsSegmentedAsync(null);

                    List <IListBlobItem> list = new List <IListBlobItem>();
                    list.AddRange(segment.Results);
                    while (segment.ContinuationToken != null)
                    {
                        segment = await container.ListBlobsSegmentedAsync(segment.ContinuationToken);

                        list.AddRange(segment.Results);
                    }

                    Assert.AreEqual(1, list.Count);

                    // make sure the parent of the container dir is null
                    empty = root.Parent;
                    Assert.IsNull(empty);

                    await blob.DeleteIfExistsAsync();
                }
                finally
                {
                    container.DeleteIfExistsAsync().AsTask().Wait();
                }
            }
        }
Exemplo n.º 6
0
        private async Task <bool> CloudBlobDirectorySetupWithDelimiterAsync(CloudBlobContainer container, string delimiter = "/")
        {
            try
            {
                for (int i = 1; i < 3; i++)
                {
                    for (int j = 1; j < 3; j++)
                    {
                        for (int k = 1; k < 3; k++)
                        {
                            String        directory = "TopDir" + i + delimiter + "MidDir" + j + delimiter + "EndDir" + k + delimiter + "EndBlob" + k;
                            CloudPageBlob blob1     = container.GetPageBlobReference(directory);
                            await blob1.CreateAsync(0);
                        }
                    }

                    CloudPageBlob blob2 = container.GetPageBlobReference("TopDir" + i + delimiter + "Blob" + i);
                    await blob2.CreateAsync(0);
                }

                return(true);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public async Task CloudBlobDirectoryGetParentAsync()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                string             name      = GetRandomContainerName();
                CloudBlobContainer container = client.GetContainerReference(name);
                try
                {
                    await container.CreateAsync();

                    CloudPageBlob blob = container.GetPageBlobReference("Dir1" + delimiter + "Blob1");
                    await blob.CreateAsync(0);

                    Assert.IsTrue(await blob.ExistsAsync());
                    Assert.AreEqual("Dir1" + delimiter + "Blob1", blob.Name);
                    CloudBlobDirectory parent = blob.Parent;
                    Assert.AreEqual(parent.Prefix, "Dir1" + delimiter);
                    await blob.DeleteAsync();
                }
                finally
                {
                    container.DeleteIfExistsAsync().Wait();
                }
            }
        }
        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();
            }
        }
Exemplo n.º 9
0
        public async Task CloudPageBlobSetMetadataAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                CloudPageBlob blob2 = container.GetPageBlobReference("blob1");
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(0, blob2.Metadata.Count);

                OperationContext operationContext = new OperationContext();
                blob.Metadata["key1"] = null;

                Assert.ThrowsException <AggregateException>(
                    () => blob.SetMetadataAsync(null, null, operationContext).AsTask().Wait(),
                    "Metadata keys should have a non-null value");
                Assert.IsInstanceOfType(operationContext.LastResult.Exception.InnerException, typeof(ArgumentException));

                blob.Metadata["key1"] = "";
                Assert.ThrowsException <AggregateException>(
                    () => blob.SetMetadataAsync(null, null, operationContext).AsTask().Wait(),
                    "Metadata keys should have a non-empty value");
                Assert.IsInstanceOfType(operationContext.LastResult.Exception.InnerException, typeof(ArgumentException));

                blob.Metadata["key1"] = "value1";
                await blob.SetMetadataAsync();

                await blob2.FetchAttributesAsync();

                Assert.AreEqual(1, blob2.Metadata.Count);
                Assert.AreEqual("value1", blob2.Metadata["key1"]);

                BlobResultSegment results = await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.Metadata, null, null, null, null);

                CloudPageBlob blob3 = (CloudPageBlob)results.Results.First();
                Assert.AreEqual(1, blob3.Metadata.Count);
                Assert.AreEqual("value1", blob3.Metadata["key1"]);

                blob.Metadata.Clear();
                await blob.SetMetadataAsync();

                await blob2.FetchAttributesAsync();

                Assert.AreEqual(0, blob2.Metadata.Count);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 10
0
        public async Task CloudPageBlobSetPropertiesAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                string         eTag         = blob.Properties.ETag;
                DateTimeOffset lastModified = blob.Properties.LastModified.Value;

                await Task.Delay(1000);

                blob.Properties.CacheControl    = "no-transform";
                blob.Properties.ContentEncoding = "gzip";
                blob.Properties.ContentLanguage = "tr,en";
                blob.Properties.ContentMD5      = "MDAwMDAwMDA=";
                blob.Properties.ContentType     = "text/html";
                await blob.SetPropertiesAsync();

                Assert.IsTrue(blob.Properties.LastModified > lastModified);
                Assert.AreNotEqual(eTag, blob.Properties.ETag);

                CloudPageBlob blob2 = container.GetPageBlobReference("blob1");
                await blob2.FetchAttributesAsync();

                Assert.AreEqual("no-transform", blob2.Properties.CacheControl);
                Assert.AreEqual("gzip", blob2.Properties.ContentEncoding);
                Assert.AreEqual("tr,en", blob2.Properties.ContentLanguage);
                Assert.AreEqual("MDAwMDAwMDA=", blob2.Properties.ContentMD5);
                Assert.AreEqual("text/html", blob2.Properties.ContentType);

                CloudPageBlob blob3 = container.GetPageBlobReference("blob1");
                using (MemoryStream stream = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        DisableContentMD5Validation = true,
                    };
                    await blob3.DownloadToStreamAsync(stream.AsOutputStream(), null, options, null);
                }
                AssertAreEqual(blob2.Properties, blob3.Properties);

                BlobResultSegment results = await container.ListBlobsSegmentedAsync(null);

                CloudPageBlob blob4 = (CloudPageBlob)results.Results.First();
                AssertAreEqual(blob2.Properties, blob4.Properties);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 11
0
        public async Task CloudPageBlobUploadFromStreamWithAccessConditionAsync()
        {
            OperationContext   operationContext = new OperationContext();
            CloudBlobContainer container        = GetRandomContainerReference();
            await container.CreateAsync();

            try
            {
                AccessCondition accessCondition = AccessCondition.GenerateIfNoneMatchCondition("\"*\"");
                await this.CloudPageBlobUploadFromStreamAsync(container, 6 * 512, accessCondition, operationContext, 0);

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition(blob.Properties.ETag);
                await TestHelper.ExpectedExceptionAsync(
                    async() => await this.CloudPageBlobUploadFromStreamAsync(container, 6 * 512, accessCondition, operationContext, 0),
                    operationContext,
                    "Uploading a blob on top of an existing blob should fail if the ETag matches",
                    HttpStatusCode.PreconditionFailed);

                accessCondition = AccessCondition.GenerateIfMatchCondition(blob.Properties.ETag);
                await this.CloudPageBlobUploadFromStreamAsync(container, 6 * 512, accessCondition, operationContext, 0);

                blob = container.GetPageBlobReference("blob3");
                await blob.CreateAsync(1024);

                accessCondition = AccessCondition.GenerateIfMatchCondition(blob.Properties.ETag);
                await TestHelper.ExpectedExceptionAsync(
                    async() => await this.CloudPageBlobUploadFromStreamAsync(container, 6 * 512, accessCondition, operationContext, 0),
                    operationContext,
                    "Uploading a blob on top of an non-existing blob should fail when the ETag doesn't match",
                    HttpStatusCode.PreconditionFailed);

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition(blob.Properties.ETag);
                await this.CloudPageBlobUploadFromStreamAsync(container, 6 * 512, accessCondition, operationContext, 0);
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
Exemplo n.º 12
0
        public async Task CloudPageBlobSnapshotAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                CloudPageBlob snapshot1 = await blob.CreateSnapshotAsync();

                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);

                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");

                CloudPageBlob snapshot2 = await blob.CreateSnapshotAsync();

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

                await snapshot1.FetchAttributesAsync();

                await snapshot2.FetchAttributesAsync();

                await blob.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, blob.Properties);

                CloudPageBlob snapshotCopy = container.GetPageBlobReference("blob2");
                await snapshotCopy.StartCopyFromBlobAsync(TestHelper.Defiddler(snapshot1.Uri));
                await WaitForCopyAsync(snapshotCopy);

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

                await TestHelper.ExpectedExceptionAsync <InvalidOperationException>(
                    async() => await snapshot1.OpenWriteAsync(1024),
                    "Trying to write to a blob snapshot should fail");

                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, (ICloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (ICloudBlob)blobs[1]);
                AssertAreEqual(blob, (ICloudBlob)blobs[2]);
                AssertAreEqual(snapshotCopy, (ICloudBlob)blobs[3]);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 13
0
        public async Task CloudBlobContainerUpdateSASTokenAsync()
        {
            // Create a policy with read/write acces and get SAS.
            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,
            };
            string         sasToken      = this.testContainer.GetSharedAccessSignature(policy);
            CloudBlockBlob testBlockBlob = this.testContainer.GetBlockBlobReference("blockblob");

            await UploadTextAsync(testBlockBlob, "blob", Encoding.UTF8);
            await TestAccessAsync(sasToken, SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write, null, this.testContainer, testBlockBlob);

            StorageCredentials creds = new StorageCredentials(sasToken);

            // Change the policy to only read and update SAS.
            SharedAccessBlobPolicy policy2 = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions            = SharedAccessBlobPermissions.Read
            };
            string sasToken2 = this.testContainer.GetSharedAccessSignature(policy2);

            creds.UpdateSASToken(sasToken2);

            // Extra check to make sure that we have actually uopdated the SAS token.
            CloudBlobContainer container        = new CloudBlobContainer(this.testContainer.Uri, creds);
            CloudBlockBlob     blob             = container.GetBlockBlobReference("blockblob2");
            OperationContext   operationContext = new OperationContext();

            await TestHelper.ExpectedExceptionAsync(
                async() => await UploadTextAsync(blob, "blob", Encoding.UTF8, null, null, operationContext),
                operationContext,
                "Writing to a blob while SAS does not allow for writing",
                HttpStatusCode.NotFound);

            CloudPageBlob testPageBlob = this.testContainer.GetPageBlobReference("pageblob");
            await testPageBlob.CreateAsync(0);

            await TestAccessAsync(sasToken2, SharedAccessBlobPermissions.Read, null, this.testContainer, testPageBlob);
        }
Exemplo n.º 14
0
        public async Task CloudPageBlobCreateAndDeleteAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(0);

                Assert.IsTrue(await blob.ExistsAsync());
                await blob.DeleteAsync();
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudBlobContainerCreateWithPrivateAccessTypeAsyncOverload()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync(BlobContainerPublicAccessType.Off, null, null);
                CloudPageBlob blob1 = container.GetPageBlobReference("blob1");
                await blob1.CreateAsync(0);
                CloudPageBlob blob2 = container.GetPageBlobReference("blob2");
                await blob2.CreateAsync(0);

                await TestAccessAsync(BlobContainerPublicAccessType.Off, container, blob1);
                await TestAccessAsync(BlobContainerPublicAccessType.Off, container, blob2);
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
Exemplo n.º 16
0
        public async Task CloudPageBlobFetchAttributesAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                Assert.AreEqual(1024, blob.Properties.Length);
                Assert.IsNotNull(blob.Properties.ETag);
                Assert.IsTrue(blob.Properties.LastModified > DateTimeOffset.UtcNow.AddMinutes(-5));
                Assert.IsNull(blob.Properties.CacheControl);
                Assert.IsNull(blob.Properties.ContentEncoding);
                Assert.IsNull(blob.Properties.ContentLanguage);
                Assert.IsNull(blob.Properties.ContentType);
                Assert.IsNull(blob.Properties.ContentMD5);
                Assert.AreEqual(LeaseStatus.Unspecified, blob.Properties.LeaseStatus);
                Assert.AreEqual(BlobType.PageBlob, blob.Properties.BlobType);

                CloudPageBlob blob2 = container.GetPageBlobReference("blob1");
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(1024, blob2.Properties.Length);
                Assert.AreEqual(blob.Properties.ETag, blob2.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, blob2.Properties.LastModified);
                Assert.IsNull(blob2.Properties.CacheControl);
                Assert.IsNull(blob2.Properties.ContentEncoding);
                Assert.IsNull(blob2.Properties.ContentLanguage);
                Assert.AreEqual("application/octet-stream", blob2.Properties.ContentType);
                Assert.IsNull(blob2.Properties.ContentMD5);
                Assert.AreEqual(LeaseStatus.Unlocked, blob2.Properties.LeaseStatus);
                Assert.AreEqual(BlobType.PageBlob, blob2.Properties.BlobType);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 17
0
        public async Task CloudPageBlobSnapshotMetadataAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                blob.Metadata["Hello"] = "World";
                blob.Metadata["Marco"] = "Polo";
                await blob.SetMetadataAsync();

                IDictionary <string, string> snapshotMetadata = new Dictionary <string, string>();
                snapshotMetadata["Hello"] = "Dolly";
                snapshotMetadata["Yoyo"]  = "Ma";

                CloudPageBlob snapshot = await blob.CreateSnapshotAsync(snapshotMetadata, null, null, null);

                // Test the client view against the expected metadata
                // None of the original metadata should be present
                Assert.AreEqual("Dolly", snapshot.Metadata["Hello"]);
                Assert.AreEqual("Ma", snapshot.Metadata["Yoyo"]);
                Assert.IsFalse(snapshot.Metadata.ContainsKey("Marco"));

                // Test the server view against the expected metadata
                await snapshot.FetchAttributesAsync();

                Assert.AreEqual("Dolly", snapshot.Metadata["Hello"]);
                Assert.AreEqual("Ma", snapshot.Metadata["Yoyo"]);
                Assert.IsFalse(snapshot.Metadata.ContainsKey("Marco"));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 18
0
        public async Task CloudPageBlobCreateWithMetadataAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                blob.Metadata["key1"] = "value1";
                await blob.CreateAsync(1024);

                CloudPageBlob blob2 = container.GetPageBlobReference("blob1");
                await blob2.FetchAttributesAsync();

                Assert.AreEqual(1, blob2.Metadata.Count);
                Assert.AreEqual("value1", blob2.Metadata["key1"]);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 19
0
        public async Task CloudBlobDirectoryValidateInRootContainerAsync()
        {
            foreach (String delimiter in Delimiters)
            {
                CloudBlobClient client = GenerateCloudBlobClient();
                client.DefaultDelimiter = delimiter;
                CloudBlobContainer container = client.GetContainerReference("$root");

                CloudPageBlob    pageBlob = container.GetPageBlobReference("Dir1" + delimiter + "Blob1");
                OperationContext context  = new OperationContext();
                if (delimiter == "/")
                {
                    await TestHelper.ExpectedExceptionAsync(
                        async() => await pageBlob.CreateAsync(0, null, null, context), context,
                        "Try to create a CloudBlobDirectory/blob which has a slash in its name in the root container",
                        HttpStatusCode.BadRequest);
                }
                else
                {
                    CloudPageBlob      blob      = container.GetPageBlobReference("TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter + "EndBlob1");
                    CloudBlobDirectory directory = blob.Parent;
                    Assert.AreEqual(directory.Prefix, "TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter);
                    Assert.AreEqual(directory.Uri, container.Uri + "/TopDir1" + delimiter + "MidDir1" + delimiter + "EndDir1" + delimiter);

                    CloudBlobDirectory directory1 = container.GetDirectoryReference("TopDir1" + delimiter);
                    CloudBlobDirectory subdir1    = directory1.GetDirectoryReference("MidDir" + delimiter);
                    CloudBlobDirectory parent1    = subdir1.Parent;
                    Assert.AreEqual(parent1.Prefix, directory1.Prefix);
                    Assert.AreEqual(parent1.Uri, directory1.Uri);

                    CloudBlobDirectory subdir2 = subdir1.GetDirectoryReference("EndDir" + delimiter);
                    CloudBlobDirectory parent2 = subdir2.Parent;
                    Assert.AreEqual(parent2.Prefix, subdir1.Prefix);
                    Assert.AreEqual(parent2.Uri, subdir1.Uri);
                }
            }
        }
Exemplo n.º 20
0
        public async Task CloudPageBlobFetchAttributesInvalidTypeAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                CloudBlockBlob   blob2            = container.GetBlockBlobReference("blob1");
                OperationContext operationContext = new OperationContext();

                Assert.ThrowsException <AggregateException>(
                    () => blob2.FetchAttributesAsync(null, null, operationContext).AsTask().Wait(),
                    "Fetching attributes of a page blob using a block blob reference should fail");
                Assert.IsInstanceOfType(operationContext.LastResult.Exception.InnerException, typeof(InvalidOperationException));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        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 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();
            }
        }
Exemplo n.º 23
0
        public async Task CloudPageBlobGetPageRangesAsync()
        {
            byte[]             buffer    = GetRandomBuffer(1024);
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(4 * 1024);

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    await blob.WritePagesAsync(memoryStream.AsInputStream(), 512, null);
                }

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    await blob.WritePagesAsync(memoryStream.AsInputStream(), 3 * 1024, null);
                }

                await blob.ClearPagesAsync(1024, 1024);

                await blob.ClearPagesAsync(0, 512);

                IEnumerable <PageRange> pageRanges = await blob.GetPageRangesAsync();

                List <string> expectedPageRanges = new List <string>()
                {
                    new PageRange(512, 1023).ToString(),
                    new PageRange(3 * 1024, 4 * 1024 - 1).ToString(),
                };
                foreach (PageRange pageRange in pageRanges)
                {
                    Assert.IsTrue(expectedPageRanges.Remove(pageRange.ToString()));
                }
                Assert.AreEqual(0, expectedPageRanges.Count);

                pageRanges = await blob.GetPageRangesAsync(1024, 1024, null, null, null);

                Assert.AreEqual(0, pageRanges.Count());

                pageRanges = await blob.GetPageRangesAsync(512, 3 * 1024, null, null, null);

                expectedPageRanges = new List <string>()
                {
                    new PageRange(512, 1023).ToString(),
                    new PageRange(3 * 1024, 7 * 512 - 1).ToString(),
                };
                foreach (PageRange pageRange in pageRanges)
                {
                    Assert.IsTrue(expectedPageRanges.Remove(pageRange.ToString()));
                }
                Assert.AreEqual(0, expectedPageRanges.Count);

                OperationContext opContext = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.GetPageRangesAsync(1024, null, null, null, opContext),
                    opContext,
                    "Get Page Ranges with an offset but no count should fail",
                    HttpStatusCode.Unused);

                Assert.IsInstanceOfType(opContext.LastResult.Exception.InnerException, typeof(ArgumentNullException));
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 24
0
        public async Task PageBlobWriteStreamOpenWithAccessConditionAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            await container.CreateAsync();

            try
            {
                OperationContext context = new OperationContext();

                CloudPageBlob existingBlob = container.GetPageBlobReference("blob");
                await existingBlob.CreateAsync(1024);

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

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

                blobStream.Dispose();

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

                blobStream.Dispose();

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

                blobStream.Dispose();

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

                blobStream.Dispose();

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

                blobStream.Dispose();

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

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

                blobStream.Dispose();

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

                accessCondition = AccessCondition.GenerateIfNoneMatchCondition("*");
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(1024, accessCondition, null, context),
                    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(1024, accessCondition, null, context);

                blobStream.Dispose();

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

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

                blobStream.Dispose();

                accessCondition = AccessCondition.GenerateIfNotModifiedSinceCondition(existingBlob.Properties.LastModified.Value.AddMinutes(-1));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await existingBlob.OpenWriteAsync(1024, accessCondition, null, context),
                    context,
                    "OpenWriteAsync with a non-met condition should fail",
                    HttpStatusCode.PreconditionFailed);
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
Exemplo n.º 25
0
        private async Task IncrementalCopyAsyncImpl(int overload)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob source = container.GetPageBlobReference("source");
                await source.CreateAsync(1024);

                string data = new string('a', 512);
                await UploadTextAsync(source, data, Encoding.UTF8);

                CloudPageBlob sourceSnapshot = await source.CreateSnapshotAsync(null, null, null, null);

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

                string sasToken = sourceSnapshot.GetSharedAccessSignature(policy);

                StorageCredentials blobSAS = new StorageCredentials(sasToken);
                Uri sourceSnapshotUri      = blobSAS.TransformUri(TestHelper.Defiddler(sourceSnapshot).SnapshotQualifiedUri);

                StorageCredentials  accountSAS     = new StorageCredentials(sasToken);
                CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, source.ServiceClient.StorageUri, null, null, null);

                CloudPageBlob snapshotWithSas = await accountWithSAS.CreateCloudBlobClient().GetBlobReferenceFromServerAsync(sourceSnapshot.SnapshotQualifiedUri) as CloudPageBlob;

                CloudPageBlob copy   = container.GetPageBlobReference("copy");
                string        copyId = null;
                if (overload == 0)
                {
#if !FACADE_NETCORE
                    copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    copyId = await copy.StartIncrementalCopyAsync(new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null));
#endif
                }
                else if (overload == 1)
                {
#if !FACADE_NETCORE
                    CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
#endif
                    copyId = await copy.StartIncrementalCopyAsync(blob);
                }
                else if (overload == 2)
                {
#if !FACADE_NETCORE
                    CloudPageBlob blob = new CloudPageBlob(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri));
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
#endif
                    copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None);
                }
                else
                {
#if !FACADE_NETCORE
                    copyId = await copy.StartIncrementalCopyAsync(accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri), null, null, null, CancellationToken.None);
#else
                    Uri           snapShotQualifiedUri = accountSAS.TransformUri(TestHelper.Defiddler(snapshotWithSas).SnapshotQualifiedUri);
                    CloudPageBlob blob = new CloudPageBlob(new StorageUri(snapShotQualifiedUri), null, null);
                    copyId = await copy.StartIncrementalCopyAsync(blob, null, null, null, CancellationToken.None);
#endif
                }

                await WaitForCopyAsync(copy);

                Assert.AreEqual(BlobType.PageBlob, copy.BlobType);
                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.Properties.IsIncrementalCopy);
                Assert.IsTrue(copy.CopyState.DestinationSnapshotTime.HasValue);
                Assert.IsTrue(copy.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Test page blob creation, expecting success.
 /// </summary>
 /// <param name="testBlob">The page blob.</param>
 /// <param name="testAccessCondition">The test access condition.</param>
 private async Task PageBlobCreateExpectSuccessAsync(CloudPageBlob testBlob, AccessCondition testAccessCondition)
 {
     await testBlob.CreateAsync(8 * 512, testAccessCondition, null /* options */, null);
 }
Exemplo n.º 27
0
 /// <summary>
 /// Test page blob creation, expecting lease failure.
 /// </summary>
 /// <param name="testBlob">The page blob to test.</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 PageBlobCreateExpectLeaseFailureAsync(CloudPageBlob testBlob, AccessCondition testAccessCondition, HttpStatusCode expectedStatusCode, string expectedErrorCode, string description)
 {
     OperationContext operationContext = new OperationContext();
     await TestHelper.ExpectedExceptionAsync(
         async () => await testBlob.CreateAsync(8 * 512, testAccessCondition, null /* options */, operationContext),
         operationContext,
         description + " (Create Page Blob)",
         expectedStatusCode,
         expectedErrorCode);
 }
Exemplo n.º 28
0
        public async Task CloudPageBlobWritePagesAsync()
        {
            byte[]            buffer = GetRandomBuffer(4 * 1024 * 1024);
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();

            hasher.Append(buffer.AsBuffer());
            string contentMD5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());

            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(4 * 1024 * 1024);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null),
                        "Zero-length WritePages should fail");

                    memoryStream.SetLength(4 * 1024 * 1024 + 1);
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null),
                        ">4MB WritePages should fail");
                }

                using (MemoryStream resultingData = new MemoryStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        OperationContext opContext = new OperationContext();
                        await TestHelper.ExpectedExceptionAsync(
                            async() => await blob.WritePagesAsync(memoryStream.AsInputStream(), 512, null, null, null, opContext),
                            opContext,
                            "Writing out-of-range pages should fail",
                            HttpStatusCode.RequestedRangeNotSatisfiable,
                            "InvalidPageRange");

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, contentMD5);

                        resultingData.Write(buffer, 0, buffer.Length);

                        int offset = buffer.Length - 1024;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await TestHelper.ExpectedExceptionAsync(
                            async() => await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, contentMD5, null, null, opContext),
                            opContext,
                            "Invalid MD5 should fail with mismatch",
                            HttpStatusCode.BadRequest,
                            "Md5Mismatch");

                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 0, null);

                        resultingData.Seek(0, SeekOrigin.Begin);
                        resultingData.Write(buffer, offset, buffer.Length - offset);

                        offset = buffer.Length - 2048;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await blob.WritePagesAsync(memoryStream.AsInputStream(), 1024, null);

                        resultingData.Seek(1024, SeekOrigin.Begin);
                        resultingData.Write(buffer, offset, buffer.Length - offset);
                    }

                    using (MemoryStream blobData = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(blobData.AsOutputStream());

                        Assert.AreEqual(resultingData.Length, blobData.Length);

                        Assert.IsTrue(blobData.ToArray().SequenceEqual(resultingData.ToArray()));
                    }
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 29
0
        public async Task CloudPageBlobSnapshotAsync()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                MemoryStream  originalData = new MemoryStream(GetRandomBuffer(1024));
                CloudPageBlob blob         = container.GetPageBlobReference("blob1");
                await blob.UploadFromStreamAsync(originalData.AsInputStream());

                CloudPageBlob snapshot1 = await blob.CreateSnapshotAsync();

                Assert.AreEqual(blob.Properties.ETag, snapshot1.Properties.ETag);
                Assert.AreEqual(blob.Properties.LastModified, snapshot1.Properties.LastModified);

                Assert.IsNotNull(snapshot1.SnapshotTime, "Snapshot does not have SnapshotTime set");

                CloudPageBlob snapshot2 = await blob.CreateSnapshotAsync();

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

                await snapshot1.FetchAttributesAsync();

                await snapshot2.FetchAttributesAsync();

                await blob.FetchAttributesAsync();

                AssertAreEqual(snapshot1.Properties, blob.Properties);

                CloudPageBlob snapshot1Clone = new CloudPageBlob(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);

                CloudPageBlob snapshotCopy = container.GetPageBlobReference("blob2");
                await snapshotCopy.StartCopyFromBlobAsync(TestHelper.Defiddler(snapshot1.Uri));
                await WaitForCopyAsync(snapshotCopy);

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

                await TestHelper.ExpectedExceptionAsync <InvalidOperationException>(
                    async() => await snapshot1.OpenWriteAsync(1024),
                    "Trying to write to a blob snapshot should fail");

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

                await blob.CreateAsync(1024);

                using (Stream snapshotStream = (await snapshot1.OpenReadAsync()).AsStreamForRead())
                {
                    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, (ICloudBlob)blobs[0]);
                AssertAreEqual(snapshot2, (ICloudBlob)blobs[1]);
                AssertAreEqual(blob, (ICloudBlob)blobs[2]);
                AssertAreEqual(snapshotCopy, (ICloudBlob)blobs[3]);
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 30
0
        public async Task CloudPageBlobConditionalAccessAsync()
        {
            OperationContext   operationContext = new OperationContext();
            CloudBlobContainer container        = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob = container.GetPageBlobReference("blob1");
                await blob.CreateAsync(1024);

                await blob.FetchAttributesAsync();

                string         currentETag         = blob.Properties.ETag;
                DateTimeOffset currentModifiedTime = blob.Properties.LastModified.Value;

                // ETag conditional tests
                blob.Metadata["ETagConditionalName"] = "ETagConditionalValue";
                await blob.SetMetadataAsync(AccessCondition.GenerateIfMatchCondition(currentETag), null, null);

                await blob.FetchAttributesAsync();

                string newETag = blob.Properties.ETag;
                Assert.AreNotEqual(newETag, currentETag, "ETage should be modified on write metadata");

                blob.Metadata["ETagConditionalName"] = "ETagConditionalValue2";

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfNoneMatchCondition(newETag), null, operationContext),
                    operationContext,
                    "If none match on conditional test should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                string invalidETag = "\"0x10101010\"";
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfMatchCondition(invalidETag), null, operationContext),
                    operationContext,
                    "Invalid ETag on conditional test should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                currentETag = blob.Properties.ETag;
                await blob.SetMetadataAsync(AccessCondition.GenerateIfNoneMatchCondition(invalidETag), null, null);

                await blob.FetchAttributesAsync();

                newETag = blob.Properties.ETag;

                // LastModifiedTime tests
                currentModifiedTime = blob.Properties.LastModified.Value;

                blob.Metadata["DateConditionalName"] = "DateConditionalValue";

                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfModifiedSinceCondition(currentModifiedTime), null, operationContext),
                    operationContext,
                    "IfModifiedSince conditional on current modified time should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                DateTimeOffset pastTime = currentModifiedTime.Subtract(TimeSpan.FromMinutes(5));
                await blob.SetMetadataAsync(AccessCondition.GenerateIfModifiedSinceCondition(pastTime), null, null);

                pastTime = currentModifiedTime.Subtract(TimeSpan.FromHours(5));
                await blob.SetMetadataAsync(AccessCondition.GenerateIfModifiedSinceCondition(pastTime), null, null);

                pastTime = currentModifiedTime.Subtract(TimeSpan.FromDays(5));
                await blob.SetMetadataAsync(AccessCondition.GenerateIfModifiedSinceCondition(pastTime), null, null);

                currentModifiedTime = blob.Properties.LastModified.Value;

                pastTime = currentModifiedTime.Subtract(TimeSpan.FromMinutes(5));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfNotModifiedSinceCondition(pastTime), null, operationContext),
                    operationContext,
                    "IfNotModifiedSince conditional on past time should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                pastTime = currentModifiedTime.Subtract(TimeSpan.FromHours(5));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfNotModifiedSinceCondition(pastTime), null, operationContext),
                    operationContext,
                    "IfNotModifiedSince conditional on past time should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                pastTime = currentModifiedTime.Subtract(TimeSpan.FromDays(5));
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(AccessCondition.GenerateIfNotModifiedSinceCondition(pastTime), null, operationContext),
                    operationContext,
                    "IfNotModifiedSince conditional on past time should throw",
                    HttpStatusCode.PreconditionFailed,
                    "ConditionNotMet");

                blob.Metadata["DateConditionalName"] = "DateConditionalValue2";

                currentETag = blob.Properties.ETag;
                await blob.SetMetadataAsync(AccessCondition.GenerateIfNotModifiedSinceCondition(currentModifiedTime), null, null);

                await blob.FetchAttributesAsync();

                newETag = blob.Properties.ETag;
                Assert.AreNotEqual(newETag, currentETag, "ETage should be modified on write metadata");
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }