Esempio n. 1
0
        public async Task CreateContainer(string containerName, bool isPublic, int retries, int millisecondsBetweenRetries)
        {
            HttpStatusCode statusCode;
            StorageExtendedErrorInformation error;

            while (true)
            {
                HttpRequestMessage request = BlobTests.CreateContainerRequest(BlobContext, containerName);
                Assert.IsTrue(request != null, "Failed to create HttpRequestMessage");
                if (isPublic)
                {
                    request.Headers.Add("x-ms-blob-public-access", "container");
                }

                using (HttpResponseMessage response = await BlobTestUtils.GetResponse(request, BlobContext))
                {
                    statusCode = response.StatusCode;
                    string statusDescription = response.ReasonPhrase;
                    error = await StorageExtendedErrorInformation.ReadFromStreamAsync(
                        HttpResponseParsers.GetResponseStream(response));
                }

                // if the container is being deleted, retry up to the specified times.
                if (statusCode == HttpStatusCode.Conflict && error != null && error.ErrorCode == BlobErrorCodeStrings.ContainerBeingDeleted && retries > 0)
                {
                    await Task.Delay(millisecondsBetweenRetries);

                    retries--;
                    continue;
                }

                break;
            }
        }
        public async Task GetBlockListScenarioTest(string containerName, string blobName, BlockListingFilter typesOfBlocks, string leaseId, HttpStatusCode?expectedError, params string[] expectedBlocks)
        {
            HttpRequestMessage request = BlobTests.GetBlockListRequest(BlobContext, containerName, blobName, typesOfBlocks, AccessCondition.GenerateLeaseCondition(leaseId));

            Assert.IsTrue(request != null, "Failed to create HttpRequestMessage");
            using (HttpResponseMessage response = await BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.GetBlockListResponse(response, BlobContext, expectedError);
                var getBlockListResponse = await GetBlockListResponse.ParseAsync(HttpResponseParsers.GetResponseStream(response), CancellationToken.None);

                int i = 0;
                foreach (ListBlockItem item in getBlockListResponse)
                {
                    if (expectedBlocks == null)
                    {
                        Assert.Fail("Should not have blocks.");
                    }
                    Assert.IsTrue(i < expectedBlocks.Length, "Unexpected block: " + item.Name);
                    Assert.AreEqual <string>(expectedBlocks[i++], item.Name, "Incorrect block.");
                }
                if (expectedBlocks != null && i < expectedBlocks.Length)
                {
                    Assert.Fail("Missing block: " + expectedBlocks[i] + "(and " + (expectedBlocks.Length - i - 1) + " more).");
                }
            }
        }
Esempio n. 3
0
        public static void Contents(HttpResponseMessage response, byte[] expectedContent)
        {
            Assert.IsNotNull(response);
            Assert.IsTrue(long.Parse(HttpResponseParsers.GetContentLength(response)) >= 0);
            byte[] buf    = new byte[long.Parse(HttpResponseParsers.GetContentLength(response))];
            Stream stream = HttpResponseParsers.GetResponseStream(response);

            // Have to read one byte each time because of an issue of this stream.
            for (int i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)(stream.ReadByte());
            }
            stream.Close();
            Assert.IsTrue(buf.SequenceEqual(expectedContent));
        }
Esempio n. 4
0
        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 = HttpResponseParsers.GetResponseStream(e.Response);
                    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;
                    //The IP should not be included in the error details for security reasons
                    Assert.IsNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange  = null;
                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();
            }
        }
Esempio n. 5
0
        public async Task ListContainersScenarioTest(ListingContext listingContext, HttpStatusCode?expectedError, params string[] expectedContainers)
        {
            HttpRequestMessage request = BlobTests.ListContainersRequest(BlobContext, listingContext);

            Assert.IsTrue(request != null, "Failed to create HttpRequestMessage");
            using (HttpResponseMessage response = await BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.ListContainersResponse(response, BlobContext, expectedError);
                ListContainersResponse listContainersResponse = await ListContainersResponse.ParseAsync(HttpResponseParsers.GetResponseStream(response), CancellationToken.None);

                int i = 0;
                foreach (BlobContainerEntry item in listContainersResponse.Containers)
                {
                    if (expectedContainers == null)
                    {
                        Assert.Fail("Should not have containers.");
                    }
                    Assert.IsTrue(i < expectedContainers.Length, "Unexpected container: " + item.Name);
                    Assert.AreEqual <string>(expectedContainers[i++], item.Name, "Incorrect container.");
                }
                if (expectedContainers != null && i < expectedContainers.Length)
                {
                    Assert.Fail("Missing container: " + expectedContainers[i] + "(and " + (expectedContainers.Length - i - 1) + " more).");
                }
            }
        }
Esempio n. 6
0
        public async Task ClearPageRangeScenarioTest(string containerName, string blobName, HttpStatusCode?expectedError)
        {
            // 1. Create Sparse Page Blob
            int blobSize = 128 * 1024;

            BlobProperties properties = new BlobProperties()
            {
                BlobType = BlobType.PageBlob
            };
            Uri uri = BlobTests.ConstructPutUri(BlobContext.Address, containerName, blobName);
            OperationContext   opContext  = new OperationContext();
            HttpRequestMessage webRequest = BlobHttpRequestMessageFactory.Put(uri, BlobContext.Timeout, properties, BlobType.PageBlob, blobSize, null, null, null, opContext, null, null);


            using (HttpResponseMessage response = await BlobTestUtils.GetResponse(webRequest, BlobContext))
            {
                BlobTests.PutBlobResponse(response, BlobContext, expectedError);
            }

            // 2. Now upload some page ranges
            for (int m = 0; m * 512 * 4 < blobSize; m++)
            {
                int startOffset = 512 * 4 * m;
                int length      = 512;

                PageRange range = new PageRange(startOffset, startOffset + length - 1);
                opContext = new OperationContext();
                HttpRequestMessage pageRequest = BlobHttpRequestMessageFactory.PutPage(uri, BlobContext.Timeout, range, PageWrite.Update, null, null, opContext, null, null);
                HttpRequestHandler.SetContentLength(pageRequest, 512);

                byte[] content = new byte[length];
                random.NextBytes(content);

                pageRequest.Content = new ByteArrayContent(content);

                using (HttpResponseMessage pageResponse = await BlobTestUtils.GetResponse(pageRequest, BlobContext))
                {
                }
            }

            // 3. Now do a Get Page Ranges
            List <PageRange> pageRanges = new List <PageRange>();

            opContext = new OperationContext();
            HttpRequestMessage pageRangeRequest = BlobHttpRequestMessageFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, null, opContext, null, null);

            using (HttpResponseMessage pageRangeResponse = await BlobTestUtils.GetResponse(pageRangeRequest, BlobContext))
            {
                IEnumerable <PageRange> ranges = await GetPageRangesResponse.ParseAsync(HttpResponseParsers.GetResponseStream(pageRangeResponse), CancellationToken.None);

                pageRanges.AddRange(ranges);
            }

            // 4. Now Clear some pages
            bool skipFlag = false;

            foreach (PageRange pRange in pageRanges)
            {
                skipFlag = !skipFlag;
                if (skipFlag)
                {
                    continue;
                }

                opContext = new OperationContext();
                HttpRequestMessage clearPageRequest = BlobHttpRequestMessageFactory.PutPage(uri, BlobContext.Timeout, pRange, PageWrite.Clear, null, null, opContext, null, null);
                HttpRequestHandler.SetContentLength(clearPageRequest, 0);
                using (HttpResponseMessage clearResponse = await BlobTestUtils.GetResponse(clearPageRequest, BlobContext))
                {
                }
            }

            // 5. Get New Page ranges and verify
            List <PageRange> newPageRanges = new List <PageRange>();

            opContext = new OperationContext();
            HttpRequestMessage newPageRangeRequest = BlobHttpRequestMessageFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, null, opContext, null, null);

            using (HttpResponseMessage newPageRangeResponse = await BlobTestUtils.GetResponse(newPageRangeRequest, BlobContext))
            {
                IEnumerable <PageRange> ranges = await GetPageRangesResponse.ParseAsync(HttpResponseParsers.GetResponseStream(newPageRangeResponse), CancellationToken.None);

                newPageRanges.AddRange(ranges);
            }

            Assert.AreEqual(pageRanges.Count(), newPageRanges.Count() * 2);
            for (int l = 0; l < newPageRanges.Count(); l++)
            {
                Assert.AreEqual(pageRanges[2 * l].StartOffset, newPageRanges[l].StartOffset);
                Assert.AreEqual(pageRanges[2 * l].EndOffset, newPageRanges[l].EndOffset);
            }
        }