public async Task CloudFileWriteRangeAsync()
        {
            byte[] buffer = GetRandomBuffer(4 * 1024 * 1024);
#if NETCORE
            MD5    md5        = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer());
            string contentMD5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif

            CloudFileShare share = GetRandomShareReference();
            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                await file.CreateAsync(4 * 1024 * 1024);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await file.WriteRangeAsync(memoryStream, 0, null),
                        "Zero-length WriteRange should fail");
                }

                using (MemoryStream resultingData = new MemoryStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream(buffer))
                    {
                        OperationContext opContext = new OperationContext();
                        await TestHelper.ExpectedExceptionAsync(
                            async() => await file.WriteRangeAsync(memoryStream, 512, null, null, null, opContext),
                            opContext,
                            "Writing out-of-range ranges should fail",
                            HttpStatusCode.RequestedRangeNotSatisfiable,
                            "InvalidRange");

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await file.WriteRangeAsync(memoryStream, 0, contentMD5);

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

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

                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await file.WriteRangeAsync(memoryStream, 0, null);

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

                        offset = buffer.Length - 2048;
                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await file.WriteRangeAsync(memoryStream, 1024, null);

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

                    using (MemoryStream fileData = new MemoryStream())
                    {
                        await file.DownloadToStreamAsync(fileData);

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

                        Assert.IsTrue(fileData.ToArray().SequenceEqual(resultingData.ToArray()));
                    }
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task CloudFileListRangesAsync()
        {
            byte[]         buffer = GetRandomBuffer(1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                await file.CreateAsync(4 * 1024);

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    await file.WriteRangeAsync(memoryStream, 512, null);
                }

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    await file.WriteRangeAsync(memoryStream, 3 * 1024, null);
                }

                await file.ClearRangeAsync(1024, 1024);

                await file.ClearRangeAsync(0, 512);

                IEnumerable <FileRange> fileRanges = await file.ListRangesAsync();

                List <string> expectedFileRanges = new List <string>()
                {
                    new FileRange(512, 1023).ToString(),
                    new FileRange(3 * 1024, 4 * 1024 - 1).ToString(),
                };
                foreach (FileRange fileRange in fileRanges)
                {
                    Assert.IsTrue(expectedFileRanges.Remove(fileRange.ToString()));
                }
                Assert.AreEqual(0, expectedFileRanges.Count);

                fileRanges = await file.ListRangesAsync(1024, 1024, null, null, null);

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

                fileRanges = await file.ListRangesAsync(512, 3 * 1024, null, null, null);

                expectedFileRanges = new List <string>()
                {
                    new FileRange(512, 1023).ToString(),
                    new FileRange(3 * 1024, 7 * 512 - 1).ToString(),
                };
                foreach (FileRange fileRange in fileRanges)
                {
                    Assert.IsTrue(expectedFileRanges.Remove(fileRange.ToString()));
                }
                Assert.AreEqual(0, expectedFileRanges.Count);

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

                Assert.IsInstanceOfType(opContext.LastResult.Exception.InnerException, typeof(ArgumentNullException));
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task CloudFileInvalidApisInShareSnapshotAsync()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);
            await share.CreateAsync();

            CloudFileShare snapshot = share.SnapshotAsync().Result;
            CloudFile      file     = snapshot.GetRootDirectoryReference().GetDirectoryReference("dir1").GetFileReference("file");

            try
            {
                await file.CreateAsync(1024);

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.DeleteAsync();

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.SetMetadataAsync();

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.AbortCopyAsync(null);

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.ClearRangeAsync(0, 1024);

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.StartCopyAsync(file);

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                await file.UploadFromByteArrayAsync(new byte[1024], 0, 1024);

                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }

            await snapshot.DeleteAsync();

            await share.DeleteAsync();
        }
        public async Task CloudFileSetPropertiesAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                await file.CreateAsync(1024);

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

                await Task.Delay(1000);

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

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

                CloudFile file2 = share.GetRootDirectoryReference().GetFileReference("file1");
                await file2.FetchAttributesAsync();

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

                CloudFile file3 = share.GetRootDirectoryReference().GetFileReference("file1");
                using (MemoryStream stream = new MemoryStream())
                {
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        DisableContentMD5Validation = true,
                    };
                    await file3.DownloadToStreamAsync(stream, null, options, null);
                }
                AssertAreEqual(file2.Properties, file3.Properties);

                CloudFileDirectory          rootDirectory = share.GetRootDirectoryReference();
                IEnumerable <IListFileItem> results       = await ListFilesAndDirectoriesAsync(rootDirectory, null, null, null, null);

                CloudFile file4 = (CloudFile)results.First();
                Assert.AreEqual(file2.Properties.Length, file4.Properties.Length);

                CloudFile file5 = share.GetRootDirectoryReference().GetFileReference("file1");
                Assert.IsNull(file5.Properties.ContentMD5);
                byte[] target = new byte[4];
                await file5.DownloadRangeToByteArrayAsync(target, 0, 0, 4);

                Assert.AreEqual("MDAwMDAwMDA=", file5.Properties.ContentMD5);
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
示例#5
0
        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().Wait();
            }
        }