public void StorageCredentialsSharedKey()
        {
            StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);

            Assert.AreEqual(TestBase.TargetTenantConfig.AccountName, cred.AccountName, false);
            Assert.IsFalse(cred.IsAnonymous);
            Assert.IsFalse(cred.IsSAS);
            Assert.IsTrue(cred.IsSharedKey);

            Uri testUri = new Uri("http://test/abc?querya=1");
            Assert.AreEqual(testUri, cred.TransformUri(testUri));

            Assert.AreEqual(TestBase.TargetTenantConfig.AccountKey, Convert.ToBase64String(cred.ExportKey()));
            byte[] dummyKey = { 0, 1, 2 };
            string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            cred.UpdateKey(base64EncodedDummyKey, null);
            Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey()));

#if !RTMD
            dummyKey[0] = 3;
            base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            cred.UpdateKey(dummyKey, null);
            Assert.AreEqual(base64EncodedDummyKey, Convert.ToBase64String(cred.ExportKey()));
#endif
        }
        public void StorageCredentialsAnonymous()
        {
            StorageCredentials cred = new StorageCredentials();

            Assert.IsNull(cred.AccountName);
            Assert.IsTrue(cred.IsAnonymous);
            Assert.IsFalse(cred.IsSAS);
            Assert.IsFalse(cred.IsSharedKey);

            Uri testUri = new Uri("http://test/abc?querya=1");
            Assert.AreEqual(testUri, cred.TransformUri(testUri));

            byte[] dummyKey = { 0, 1, 2 };
            string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            TestHelper.ExpectedException<InvalidOperationException>(
                () => cred.UpdateKey(base64EncodedDummyKey, null),
                "Updating shared key on an anonymous credentials instance should fail.");
        }
        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().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 void StorageCredentialsSAS()
        {
            StorageCredentials cred = new StorageCredentials(token);

            Assert.IsNull(cred.AccountName);
            Assert.IsFalse(cred.IsAnonymous);
            Assert.IsTrue(cred.IsSAS);
            Assert.IsFalse(cred.IsSharedKey);

            Uri testUri = new Uri("http://test/abc");
            Assert.AreEqual(testUri.AbsoluteUri + token, cred.TransformUri(testUri).AbsoluteUri, true);

            testUri = new Uri("http://test/abc?query=a&query2=b");
            string expectedUri = testUri.AbsoluteUri + "&" + token.Substring(1);
            Assert.AreEqual(expectedUri, cred.TransformUri(testUri).AbsoluteUri, true);

            byte[] dummyKey = { 0, 1, 2 };
            string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
            TestHelper.ExpectedException<InvalidOperationException>(
                () => cred.UpdateKey(base64EncodedDummyKey, null),
                "Updating shared key on a SAS credentials instance should fail.");
        }
        public void CloudBlobSASApiVersionQueryParam()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();
                ICloudBlob blob;

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

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

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

                OperationContext apiVersionCheckContext = new OperationContext();
                apiVersionCheckContext.SendingRequest += (sender, e) =>
                {
                    Assert.IsNull(e.Request.Headers.Get("x-ms-version"));
                    Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version"));
                };

                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASUri, operationContext: apiVersionCheckContext);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASUri, operationContext: apiVersionCheckContext);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASStorageUri, operationContext: apiVersionCheckContext);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASStorageUri, operationContext: apiVersionCheckContext);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public void CloudBlobContainerGetBlobReferenceFromServerAPM()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

                CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab");
                appendBlob.CreateOrReplace();

                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    CloudBlobClient client;
                    ICloudBlob blob;
                    IAsyncResult result;

                    result = container.BeginGetBlobReferenceFromServer("bb",
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                    CloudBlockBlob blockBlobSnapshot = ((CloudBlockBlob)blob).CreateSnapshot();
                    blob.SetProperties();
                    Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSnapshotUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties);
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.BeginGetBlobReferenceFromServer("pb",
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                    CloudPageBlob pageBlobSnapshot = ((CloudPageBlob)blob).CreateSnapshot();
                    blob.SetProperties();
                    Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSnapshotUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties);
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.BeginGetBlobReferenceFromServer("ab",
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                    CloudAppendBlob appendBlobSnapshot = ((CloudAppendBlob)blob).CreateSnapshot();
                    blob.SetProperties();
                    Uri appendBlobSnapshotUri = new Uri(appendBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + appendBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlobSnapshotUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    AssertAreEqual(appendBlobSnapshot.Properties, blob.Properties);
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlobSnapshot.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlob.Uri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlob.Uri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlob.Uri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlob.StorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlob.StorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlob.StorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    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 pageBlobToken = pageBlob.GetSharedAccessSignature(policy);
                    StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken);
                    Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri);
                    StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri);

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

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                    Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri));
                    Assert.IsNull(blob.StorageUri.SecondaryUri);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));

                    client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    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);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    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);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    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);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                    client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                    client = new CloudBlobClient(container.ServiceClient.StorageUri, appendBlobSAS);
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(appendBlobSASStorageUri, null, null, null,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob));
                    Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri));
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public void CloudBlobContainerGetBlobReferenceFromServer()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

                CloudBlobClient client;
                ICloudBlob blob;
                
                blob = container.GetBlobReferenceFromServer("bb");
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                CloudBlockBlob blockBlobSnapshot = ((CloudBlockBlob)blob).CreateSnapshot();
                blob.SetProperties();
                Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSnapshotUri);
                AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = container.GetBlobReferenceFromServer("pb");
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                CloudPageBlob pageBlobSnapshot = ((CloudPageBlob)blob).CreateSnapshot();
                blob.SetProperties();
                Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSnapshotUri);
                AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

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

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

                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlob.StorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlob.StorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

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

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

                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASUri);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASUri);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASStorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASStorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                blob = client.GetBlobReferenceFromServer(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 = client.GetBlobReferenceFromServer(pageBlobSASUri);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                client = new CloudBlobClient(container.ServiceClient.StorageUri, blockBlobSAS);
                blob = client.GetBlobReferenceFromServer(blockBlobSASStorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob));
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS);
                blob = client.GetBlobReferenceFromServer(pageBlobSASStorageUri);
                Assert.IsInstanceOfType(blob, typeof(CloudPageBlob));
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public void CloudBlobContainerGetBlobReferenceFromServerAPM()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    IAsyncResult result = container.BeginGetBlobReferenceFromServer("bb",
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob1 = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob));

                    result = ((CloudBlockBlob)blob1).BeginCreateSnapshot(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    CloudBlockBlob blob1Snapshot = ((CloudBlockBlob)blob1).EndCreateSnapshot(result);
                    result = blob1.BeginSetProperties(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob1.EndSetProperties(result);
                    Uri blob1SnapshotUri = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob1SnapshotUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob1SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties);

                    result = container.BeginGetBlobReferenceFromServer("pb",
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob2 = container.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob));

                    result = ((CloudPageBlob)blob2).BeginCreateSnapshot(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    CloudPageBlob blob2Snapshot = ((CloudPageBlob)blob2).EndCreateSnapshot(result);
                    result = blob2.BeginSetProperties(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    blob2.EndSetProperties(result);
                    Uri blob2SnapshotUri = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o"));
                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob2SnapshotUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob2SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlob.Uri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob3 = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlob.Uri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob4 = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    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);

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob5 = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob));

                    result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob6 = container.ServiceClient.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob));

                    CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                    result = client7.BeginGetBlobReferenceFromServer(blockBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob7 = client7.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob));

                    CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS);
                    result = client8.BeginGetBlobReferenceFromServer(pageBlobSASUri,
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    ICloudBlob blob8 = client8.EndGetBlobReferenceFromServer(result);
                    Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob));
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public void TableSasUriPkRkTestSync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessTablePermissions.Add,
                };

                string sasTokenPkRk = table.GetSharedAccessSignature(policy, null, "tables_batch_0", "00",
                    "tables_batch_1", "04");
                StorageCredentials credsPkRk = new StorageCredentials(sasTokenPkRk);

                // transform uri from credentials
                CloudTable sasTableTransformed = new CloudTable(credsPkRk.TransformUri(table.Uri));

                // create uri by appending sas
                CloudTable sasTableDirect = new CloudTable(new Uri(table.Uri.ToString() + sasTokenPkRk));

                BaseEntity pkrkEnt = new BaseEntity("tables_batch_0", "00");
                sasTableTransformed.Execute(TableOperation.Insert(pkrkEnt));

                pkrkEnt = new BaseEntity("tables_batch_0", "01");
                sasTableDirect.Execute(TableOperation.Insert(pkrkEnt));

                Action<BaseEntity, CloudTable, OperationContext> insertDelegate = (tableEntity, sasTable1, ctx) =>
                {
                    sasTable1.Execute(TableOperation.Insert(tableEntity), null, ctx);
                };

                pkrkEnt = new BaseEntity("tables_batch_2", "00");
                TestHelper.ExpectedException(
                    (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                    (int)HttpStatusCode.Forbidden);
                TestHelper.ExpectedException(
                     (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                     (int)HttpStatusCode.Forbidden);

                pkrkEnt = new BaseEntity("tables_batch_1", "05");
                TestHelper.ExpectedException(
                    (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                    (int)HttpStatusCode.Forbidden);
                TestHelper.ExpectedException(
                     (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx),
                    string.Format("Inserted entity without appropriate SAS permissions."),
                     (int)HttpStatusCode.Forbidden);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for tables
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudTableSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();
                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    Permissions = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() {{"prop", new EntityProperty(4)}});
                table.Execute(new TableOperation(entity, TableOperationType.Insert));

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
                string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                StorageCredentials tableSAS = new StorageCredentials(tableToken);
                Uri tableSASUri = tableSAS.TransformUri(table.Uri);
                StorageUri tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);

                CloudTable tableWithSAS = new CloudTable(tableSASUri);
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;

                bool exceptionThrown = false;
                TableResult result = null;
                DynamicTableEntity resultEntity = new DynamicTableEntity();
                TableOperation retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                try
                {
                    result = tableWithSAS.Execute(retrieveOp, null, opContext);
                }
                catch (StorageException e)
                {
                    string[] parts = e.RequestInformation.HttpStatusMessage.Split(' ');
                    actualIP = IPAddress.Parse(parts[parts.Length - 1].Trim('.'));
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                tableSAS = new StorageCredentials(tableToken);
                tableSASUri = tableSAS.TransformUri(table.Uri);
                tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);


                tableWithSAS = new CloudTable(tableSASUri);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
    
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.PrimaryUri.Equals(tableWithSAS.Uri));
                Assert.IsNull(tableWithSAS.StorageUri.SecondaryUri);

                tableWithSAS = new CloudTable(tableSASStorageUri, null);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.Equals(tableWithSAS.StorageUri));
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
        private static async Task CloudFileCopyAsync(bool sourceIsSas, bool destinationIsSas)
        {
            CloudFileShare share = GetRandomShareReference();
            try
            {
                await share.CreateAsync();

                // Create Source on server
                CloudFile source = share.GetRootDirectoryReference().GetFileReference("source");

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

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

                // Create Destination on server
                CloudFile destination = share.GetRootDirectoryReference().GetFileReference("destination");
                await destination.CreateAsync(1);

                CloudFile copySource = source;
                CloudFile copyDestination = destination;

                if (sourceIsSas)
                {
                    // Source SAS must have read permissions
                    SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Read;
                    SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
                    {
                        SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions = permissions,
                    };
                    string sasToken = source.GetSharedAccessSignature(policy);

                    // Get source 
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copySource = new CloudFile(credentials.TransformUri(source.Uri));
                }

                if (destinationIsSas)
                {
                    Assert.IsTrue(sourceIsSas);

                    // Destination SAS must have write permissions
                    SharedAccessFilePermissions permissions = SharedAccessFilePermissions.Write;
                    SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
                    {
                        SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions = permissions,
                    };
                    string sasToken = destination.GetSharedAccessSignature(policy);

                    // Get destination 
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copyDestination = new CloudFile(credentials.TransformUri(destination.Uri));
                }

                // Start copy and wait for completion
                string copyId = await copyDestination.StartCopyAsync(TestHelper.Defiddler(copySource));
                await WaitForCopyAsync(destination);

                // Check original file references for equality
                Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, destination.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, destination.CopyState.BytesCopied);
                Assert.AreEqual(copyId, destination.CopyState.CopyId);
                Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                if (!destinationIsSas)
                {
                    // Abort Copy is not supported for SAS destination
                    OperationContext context = new OperationContext();
                    await TestHelper.ExpectedExceptionAsync(
                        async () => await copyDestination.AbortCopyAsync(copyId, null, null, context),
                        context,
                        "Aborting a copy operation after completion should fail",
                        HttpStatusCode.Conflict,
                        "NoPendingCopyOperation");
                }

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

                string copyData = await DownloadTextAsync(destination, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of file not equal.");

                await destination.FetchAttributesAsync();
                FileProperties prop1 = destination.Properties;
                FileProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                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", destination.Metadata["Test"], false, "Copied metadata not same");

                await destination.DeleteAsync();
                await source.DeleteAsync();
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public void CloudFileSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudFileShare share = GetRandomShareReference();
            try
            {
                share.Create();
                CloudFile file;
                SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
                {
                    Permissions = SharedAccessFilePermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudFile fileWithKey = share.GetRootDirectoryReference().GetFileReference("filefile");
                byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                fileWithKey.UploadFromByteArray(data, 0, 4);

                // We need an IP address that will never be a valid source
                IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
                string fileToken = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                StorageCredentials fileSAS = new StorageCredentials(fileToken);
                Uri fileSASUri = fileSAS.TransformUri(fileWithKey.Uri);
                StorageUri fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri);

                file = new CloudFile(fileSASUri);
                byte[] target = new byte[4];
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;
                opContext.ResponseReceived += (sender, e) => 
                    {
                        Stream stream = e.Response.GetResponseStream();
                        stream.Seek(0, SeekOrigin.Begin);
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            string text = reader.ReadToEnd();
                            XDocument xdocument = XDocument.Parse(text);
                            actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                        }
                    };

                bool exceptionThrown = false;
                try
                {
                    file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                fileToken = fileWithKey.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                fileSAS = new StorageCredentials(fileToken);
                fileSASUri = fileSAS.TransformUri(fileWithKey.Uri);
                fileSASStorageUri = fileSAS.TransformUri(fileWithKey.StorageUri);

                file = new CloudFile(fileSASUri);
                file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }

                Assert.IsTrue(file.StorageUri.PrimaryUri.Equals(fileWithKey.Uri));
                Assert.IsNull(file.StorageUri.SecondaryUri);

                file = new CloudFile(fileSASStorageUri, null);
                file.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }

                Assert.IsTrue(file.StorageUri.Equals(fileWithKey.StorageUri));
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        private static void CloudBlockBlobCopy(bool sourceIsSas, bool destinationIsSas)
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();

                // Create Source on server
                CloudBlockBlob source = container.GetBlockBlobReference("source");

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

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

                // Create Destination on server
                CloudBlockBlob destination = container.GetBlockBlobReference("destination");
                destination.PutBlockList(new string[] { });

                CloudBlockBlob copySource = source;
                CloudBlockBlob copyDestination = destination;
                
                if (sourceIsSas)
                {
                    // Source SAS must have read permissions
                    SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read;
                    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                    {
                        SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions = permissions,
                    };
                    string sasToken = source.GetSharedAccessSignature(policy);

                    // Get source 
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copySource = new CloudBlockBlob(credentials.TransformUri(source.Uri));
                }

                if (destinationIsSas)
                {
                    if (!sourceIsSas)
                    {
                        // Source container must be public if source is not SAS
                        BlobContainerPermissions containerPermissions = new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        };
                        container.SetPermissions(containerPermissions); 
                    }

                    // Destination SAS must have write permissions
                    SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Write;
                    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                    {
                        SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                        SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                        Permissions = permissions,
                    };
                    string sasToken = destination.GetSharedAccessSignature(policy);

                    // Get destination 
                    StorageCredentials credentials = new StorageCredentials(sasToken);
                    copyDestination = new CloudBlockBlob(credentials.TransformUri(destination.Uri));
                }

                // Start copy and wait for completion
                string copyId = copyDestination.StartCopyFromBlob(TestHelper.Defiddler(copySource));
                WaitForCopy(destination);
                
                // Check original blob references for equality
                Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status);
                Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, destination.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, destination.CopyState.BytesCopied);
                Assert.AreEqual(copyId, destination.CopyState.CopyId);
                Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));

                if (!destinationIsSas)
                {
                    // Abort Copy is not supported for SAS destination
                    TestHelper.ExpectedException(
                               () => copyDestination.AbortCopy(copyId),
                               "Aborting a copy operation after completion should fail",
                               HttpStatusCode.Conflict,
                               "NoPendingCopyOperation"); 
                }

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

                string copyData = DownloadText(destination, Encoding.UTF8);
                Assert.AreEqual(data, copyData, "Data inside copy of blob not equal.");

                destination.FetchAttributes();
                BlobProperties prop1 = destination.Properties;
                BlobProperties prop2 = source.Properties;

                Assert.AreEqual(prop1.CacheControl, prop2.CacheControl);
                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", destination.Metadata["Test"], false, "Copied metadata not same");

                destination.Delete();
                source.Delete();
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
Beispiel #15
0
        public void CloudBlobSASApiVersionQueryParam()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();
                CloudBlob blob;

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

                CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab");
                appendBlob.CreateOrReplace();

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

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

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

                OperationContext apiVersionCheckContext = new OperationContext();
                apiVersionCheckContext.SendingRequest += (sender, e) =>
                {
                    Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version"));
                };

                blob = new CloudBlob(blockBlobSASUri);
                blob.FetchAttributes(operationContext: apiVersionCheckContext);
                Assert.AreEqual(blob.BlobType, BlobType.BlockBlob);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = new CloudBlob(pageBlobSASUri);
                blob.FetchAttributes(operationContext: apiVersionCheckContext);
                Assert.AreEqual(blob.BlobType, BlobType.PageBlob);
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = new CloudBlob(blockBlobSASStorageUri, null, null);
                blob.FetchAttributes(operationContext: apiVersionCheckContext);
                Assert.AreEqual(blob.BlobType, BlobType.BlockBlob);
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

                blob = new CloudBlob(pageBlobSASStorageUri, null, null);
                blob.FetchAttributes(operationContext: apiVersionCheckContext);
                Assert.AreEqual(blob.BlobType, BlobType.PageBlob);
                Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri));

            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public void CloudBlobContainerGetBlobReferenceFromServerTask()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.CreateAsync().Wait();

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

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                blockBlob.PutBlockList(new string[] { });

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

                ICloudBlob blob1 = container.GetBlobReferenceFromServerAsync("bb").Result;
                Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob));

                ICloudBlob blob2 = container.GetBlobReferenceFromServerAsync("pb").Result;
                Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob));

                ICloudBlob blob3 = container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri).Result;
                Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob));

                ICloudBlob blob4 = container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri).Result;
                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 = container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri).Result;
                Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob));

                ICloudBlob blob6 = container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri).Result;
                Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob));

                CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS);
                ICloudBlob blob7 = client7.GetBlobReferenceFromServerAsync(blockBlobSASUri).Result;
                Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob));

                CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS);
                ICloudBlob blob8 = client8.GetBlobReferenceFromServerAsync(pageBlobSASUri).Result;
                Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob));
            }
            finally
            {
                container.DeleteIfExistsAsync().Wait();
            }
        }
Beispiel #17
0
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for blobs
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudBlobSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();
                CloudBlob blob;
                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb");
                byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                blockBlob.UploadFromByteArray(data, 0, 4);

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
                string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken);
                Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri);
                StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);

                blob = new CloudBlob(blockBlobSASUri);
                byte[] target = new byte[4];
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;
                opContext.ResponseReceived += (sender, e) => 
                    {
                        Stream stream = e.Response.GetResponseStream();
                        stream.Seek(0, SeekOrigin.Begin);
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            string text = reader.ReadToEnd();
                            XDocument xdocument = XDocument.Parse(text);
                            actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                        }
                    };

                bool exceptionThrown = false;
                try
                {
                    blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange);
                blockBlobSAS = new StorageCredentials(blockBlobToken);
                blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri);
                blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri);


                blob = new CloudBlob(blockBlobSASUri);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri));
                Assert.IsNull(blob.StorageUri.SecondaryUri);

                blob = new CloudBlob(blockBlobSASStorageUri, null, null);
                blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null);
                for (int i = 0; i < 4; i++)
                {
                    Assert.AreEqual(data[i], target[i]);
                }
                Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri));

            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for queues
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudQueueSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudQueueClient client = GenerateCloudQueueClient();
            CloudQueue queue = client.GetQueueReference(GenerateNewQueueName());

            try
            {
                queue.Create();
                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    Permissions = SharedAccessQueuePermissions.Read,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                string sampleMessageContent = "sample content";
                CloudQueueMessage message = new CloudQueueMessage(sampleMessageContent);
                queue.AddMessage(message);

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
                string queueToken = queue.GetSharedAccessSignature(policy, null, null, ipAddressOrRange);
                StorageCredentials queueSAS = new StorageCredentials(queueToken);
                Uri queueSASUri = queueSAS.TransformUri(queue.Uri);
                StorageUri queueSASStorageUri = queueSAS.TransformUri(queue.StorageUri);

                CloudQueue queueWithSAS = new CloudQueue(queueSASUri);
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;
                opContext.ResponseReceived += (sender, e) =>
                {
                    Stream stream = e.Response.GetResponseStream();
                    stream.Seek(0, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string text = reader.ReadToEnd();
                        XDocument xdocument = XDocument.Parse(text);
                        actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value);
                    }
                };

                bool exceptionThrown = false;
                CloudQueueMessage resultMessage;
                try
                {
                    resultMessage = queueWithSAS.PeekMessage(null, opContext);
                }
                catch (StorageException)
                {
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                queueToken = queue.GetSharedAccessSignature(policy, null, null, ipAddressOrRange);
                queueSAS = new StorageCredentials(queueToken);
                queueSASUri = queueSAS.TransformUri(queue.Uri);
                queueSASStorageUri = queueSAS.TransformUri(queue.StorageUri);

                queueWithSAS = new CloudQueue(queueSASUri);
                resultMessage = queue.PeekMessage();
                Assert.AreEqual(sampleMessageContent, resultMessage.AsString);
                Assert.IsTrue(queueWithSAS.StorageUri.PrimaryUri.Equals(queue.Uri));
                Assert.IsNull(queueWithSAS.StorageUri.SecondaryUri);

                queueWithSAS = new CloudQueue(queueSASStorageUri, null);
                resultMessage = queue.PeekMessage();
                Assert.AreEqual(sampleMessageContent, resultMessage.AsString);
                Assert.IsTrue(queueWithSAS.StorageUri.Equals(queue.StorageUri));

            }
            finally
            {
                queue.DeleteIfExists();
            }
        }