示例#1
0
        public async Task RunFileTest(SharedAccessAccountPolicy policy, int?httpsPort, OperationContext opContext = null)
        {
            CloudFileClient fileClient = GenerateCloudFileClient();
            string          shareName  = "s" + Guid.NewGuid().ToString("N");

            try
            {
                CloudStorageAccount account        = new CloudStorageAccount(fileClient.Credentials, false);
                string             accountSASToken = account.GetSharedAccessSignature(policy);
                StorageCredentials accountSAS      = new StorageCredentials(accountSASToken);

                StorageUri storageUri = fileClient.StorageUri;
                if (httpsPort != null)
                {
                    storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "https", httpsPort.Value), TransformSchemeAndPort(storageUri.SecondaryUri, "https", httpsPort.Value));
                }
                else
                {
                    storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "http", 80), TransformSchemeAndPort(storageUri.SecondaryUri, "http", 80));
                }

                CloudStorageAccount accountWithSAS    = new CloudStorageAccount(accountSAS, null, null, null, storageUri);
                CloudFileClient     fileClientWithSAS = accountWithSAS.CreateCloudFileClient();
                CloudFileShare      shareWithSAS      = fileClientWithSAS.GetShareReference(shareName);
                CloudFileShare      share             = fileClient.GetShareReference(shareName);
                await share.CreateAsync();

                string    fileName    = "file";
                CloudFile file        = share.GetRootDirectoryReference().GetFileReference(fileName);
                CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(fileName);
                byte[]    content     = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                await file.CreateAsync(content.Length);

                using (MemoryStream stream = new MemoryStream(content))
                {
                    await file.WriteRangeAsync(stream, 0, null);
                }

                byte[] result = new byte[content.Length];
                await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length, null, null, opContext);

                for (int i = 0; i < content.Length; i++)
                {
                    Assert.AreEqual(content[i], result[i]);
                }
            }
            finally
            {
                fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait();
            }
        }
示例#2
0
        public async Task <byte[]> DownloadFileAsync(string path, string share, string filename,
                                                     CancellationToken token = default)
        {
            _ = path ?? throw new ArgumentNullException(nameof(path));
            _ = share ?? throw new ArgumentNullException(nameof(share));
            _ = filename ?? throw new ArgumentNullException(nameof(filename));

            Exception error = null;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            double time             = watch.Elapsed.TotalMilliseconds;
            long   bytesTransferred = 0;

            byte[] buffer = null;

            try
            {
                CloudFileShare     choudShare = client.GetShareReference(share);
                CloudFileDirectory dir        = choudShare.GetRootDirectoryReference();
                CloudFile          file       = dir.GetFileReference(filename);

                IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                    progress =>
                {
                    bytesTransferred = bytesTransferred < progress.BytesTransferred
                            ? progress.BytesTransferred
                            : bytesTransferred;
                    if (watch.Elapsed.TotalMilliseconds > time + 1000.0 &&
                        bytesTransferred <= progress.BytesTransferred)
                    {
                        OnDownloadBytesTransferred?.Invoke(this,
                                                           new BytesTransferredEventArgs(share, filename, bytesTransferred,
                                                                                         file.Properties.Length));
                    }
                });

                buffer = new byte[file.Properties.Length];
                await file.DownloadRangeToByteArrayAsync(buffer, 0, 0, buffer.Length, default, default, default,
示例#3
0
        public async Task <byte[]> DownloadFileAsync(string path, string share, string filename, CancellationToken token = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            if (string.IsNullOrEmpty(share))
            {
                throw new ArgumentNullException("share");
            }

            if (string.IsNullOrEmpty("filename"))
            {
                throw new ArgumentNullException("filename");
            }

            Exception error = null;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            double time             = watch.Elapsed.TotalMilliseconds;
            long   bytesTransferred = 0;

            byte[] buffer = null;

            try
            {
                CloudFileShare     choudShare = client.GetShareReference(share);
                CloudFileDirectory dir        = choudShare.GetRootDirectoryReference();
                CloudFile          file       = dir.GetFileReference(filename);

                IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                    progress =>
                {
                    bytesTransferred = bytesTransferred < progress.BytesTransferred ? progress.BytesTransferred : bytesTransferred;
                    if (watch.Elapsed.TotalMilliseconds > time + 1000.0 && bytesTransferred <= progress.BytesTransferred)
                    {
                        OnDownloadBytesTransferred?.Invoke(this, new BytesTransferredEventArgs(share, filename, bytesTransferred, file.Properties.Length));
                    }
                });

                buffer = new byte[file.Properties.Length];
                await file.DownloadRangeToByteArrayAsync(buffer, 0, 0, buffer.Length, default(AccessCondition), default(FileRequestOptions), default(OperationContext), progressHandler, token);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    buffer = null;
                }
                else
                {
                    error = ex;
                    throw ex;
                }
            }
            finally
            {
                watch.Stop();
                OnDownloadCompleted?.Invoke(this, new BlobCompleteEventArgs(share, filename, token.IsCancellationRequested, error));
            }

            return(buffer);
        }
示例#4
0
        public async Task RunPermissionsTestFiles(SharedAccessAccountPolicy policy)
        {
            CloudFileClient fileClient = GenerateCloudFileClient();
            string          shareName  = "s" + Guid.NewGuid().ToString("N");

            try
            {
                CloudStorageAccount account           = new CloudStorageAccount(fileClient.Credentials, false);
                string              accountSASToken   = account.GetSharedAccessSignature(policy);
                StorageCredentials  accountSAS        = new StorageCredentials(accountSASToken);
                CloudStorageAccount accountWithSAS    = new CloudStorageAccount(accountSAS, null, null, null, fileClient.StorageUri);
                CloudFileClient     fileClientWithSAS = accountWithSAS.CreateCloudFileClient();
                CloudFileShare      shareWithSAS      = fileClientWithSAS.GetShareReference(shareName);
                CloudFileShare      share             = fileClient.GetShareReference(shareName);

                // General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared
                // Otherwise, make sure SAS fails and then do the thing with shared key.

                // Things to do:
                // Create the share (Create / Write perms, Container RT)
                // List shares with prefix (List perms, Service RT)
                // Create a new file (Create / Write, Object RT)
                // Add a range to the file (Write, Object RT)
                // Read the data from the file (Read, Object RT)
                // Overwrite a file (Write, Object RT)
                // Delete the file (Delete perms, Object RT)

                if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
                {
                    await shareWithSAS.CreateAsync();
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await shareWithSAS.CreateAsync(), "Creating a share with SAS should fail without Create or Write and Container-level perms.");

                    await share.CreateAsync();
                }
                Assert.IsTrue(await share.ExistsAsync());

                if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service))
                {
                    Assert.AreEqual(shareName, (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First().Name);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First(), "Listing shared with SAS should fail without List and Service-level perms.");
                }

                string    filename    = "fileName";
                CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(filename);
                CloudFile file        = share.GetRootDirectoryReference().GetFileReference(filename);

                //Try creating credentials using SAS Uri directly
                CloudFile fileWithSASUri = new CloudFile(new Uri(share.Uri + accountSASToken));

                byte[] content = new byte[] { 0x1, 0x2, 0x3, 0x4 };
                if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    await fileWithSAS.CreateAsync(content.Length);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.CreateAsync(content.Length), "Creating a file with SAS should fail without Create or Write and Object-level perms.");

                    await file.CreateAsync(content.Length);
                }
                Assert.IsTrue(await file.ExistsAsync());

                using (MemoryStream stream = new MemoryStream(content))
                {
                    if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) &&
                        ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                    {
                        await fileWithSAS.WriteRangeAsync(stream, 0, null);
                    }
                    else
                    {
                        await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.WriteRangeAsync(stream, 0, null), "Writing a range to a file with SAS should fail without Write and Object-level perms.");

                        stream.Seek(0, SeekOrigin.Begin);
                        await file.WriteRangeAsync(stream, 0, null);
                    }
                }

                byte[] result = new byte[content.Length];
                await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);

                for (int i = 0; i < content.Length; i++)
                {
                    Assert.AreEqual(content[i], result[i]);
                }

                if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    result = new byte[content.Length];
                    await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);

                    for (int i = 0; i < content.Length; i++)
                    {
                        Assert.AreEqual(content[i], result[i]);
                    }
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length), "Reading a file with SAS should fail without Read and Object-level perms.");
                }

                if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    await fileWithSAS.CreateAsync(2);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.CreateAsync(2), "Overwriting a file with SAS should fail without Write and Object-level perms.");

                    await file.CreateAsync(2);
                }

                result = new byte[content.Length];
                await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);

                for (int i = 0; i < content.Length; i++)
                {
                    Assert.AreEqual(0, result[i]);
                }

                if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) &&
                    ((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
                {
                    await fileWithSAS.DeleteAsync();
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync <StorageException>(async() => await fileWithSAS.DeleteAsync(), "Deleting a file with SAS should fail without Delete and Object-level perms.");

                    await file.DeleteAsync();
                }

                Assert.IsFalse(await file.ExistsAsync());
            }
            finally
            {
                fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait();
            }
        }