public AzureOperations(string connectionString, string shareName)
 {
     var account = CloudStorageAccount.Parse(connectionString);
     client = account.CreateCloudFileClient();
     share = client.GetShareReference(shareName);
     share.CreateIfNotExists();
     root = share.GetRootDirectoryReference();
 }
Example #2
0
 public static async Task<List<string>> CreateFilesAsync(CloudFileShare share, int count)
 {
     string name;
     List<string> files = new List<string>();
     for (int i = 0; i < count; i++)
     {
         name = "ff" + Guid.NewGuid().ToString();
         CloudFile file = share.GetRootDirectoryReference().GetFileReference(name);
         await file.CreateAsync(0);
         files.Add(name);
     }
     return files;
 }
Example #3
0
        public void CloudFileDirectoryGetParentOnRoot()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            CloudFileDirectory root   = share.GetRootDirectoryReference().GetDirectoryReference("TopDir1/");
            CloudFileDirectory parent = root.Parent;

            Assert.IsNotNull(parent);

            CloudFileDirectory empty = parent.Parent;

            Assert.IsNull(empty);
        }
Example #4
0
        public void CloudFileDirectoryDelimitersInARow()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            CloudFile file = share.GetRootDirectoryReference().GetFileReference(NavigationHelper.Slash + NavigationHelper.Slash + NavigationHelper.Slash + "File1");

            ////Traverse from leaf to root
            CloudFileDirectory directory1 = file.Parent;

            Assert.AreEqual(directory1.Name, NavigationHelper.Slash + NavigationHelper.Slash + NavigationHelper.Slash);

            CloudFileDirectory directory2 = directory1.Parent;

            Assert.AreEqual(directory2.Name, NavigationHelper.Slash + NavigationHelper.Slash);

            CloudFileDirectory directory3 = directory2.Parent;

            Assert.AreEqual(directory3.Name, NavigationHelper.Slash);

            ////Traverse from root to leaf
            CloudFileDirectory directory4 = share.GetRootDirectoryReference().GetDirectoryReference(NavigationHelper.Slash);
            CloudFileDirectory directory5 = directory4.GetDirectoryReference(NavigationHelper.Slash);

            Assert.AreEqual(directory5.Name, NavigationHelper.Slash + NavigationHelper.Slash);

            CloudFileDirectory directory6 = directory5.GetDirectoryReference(NavigationHelper.Slash);

            Assert.AreEqual(directory6.Name, NavigationHelper.Slash + NavigationHelper.Slash + NavigationHelper.Slash);

            CloudFile file2 = directory6.GetFileReference("File1");

            Assert.AreEqual(file2.Name, NavigationHelper.Slash + NavigationHelper.Slash + NavigationHelper.Slash + "File1");
            Assert.AreEqual(file2.Uri, file.Uri);
        }
Example #5
0
        public static async Task <List <string> > CreateFilesAsync(CloudFileShare share, int count)
        {
            string        name;
            List <string> files = new List <string>();

            for (int i = 0; i < count; i++)
            {
                name = "ff" + Guid.NewGuid().ToString();
                CloudFile file = share.GetRootDirectoryReference().GetFileReference(name);
                await file.CreateAsync(0);

                files.Add(name);
            }

            return(files);
        }
Example #6
0
        public void MyTestInitialize()
        {
            if (TestBase.FileBufferManager != null)
            {
                TestBase.FileBufferManager.OutstandingBufferCount = 0;
            }

            this.share = GetRandomShareReference();
            this.share.CreateIfNotExists();
            CloudFileDirectory directory = share.GetRootDirectoryReference();

            this.directory = directory.GetDirectoryReference("directory");
            this.directory.Create();
            this.file = this.directory.GetFileReference("file");
            this.file.UploadText("test");
        }
Example #7
0
        public static List <string> CreateFilesTask(CloudFileShare share, int count)
        {
            string        name;
            List <string> files = new List <string>();
            List <Task>   tasks = new List <Task>();

            for (int i = 0; i < count; i++)
            {
                name = "ff" + Guid.NewGuid().ToString();
                CloudFile file = share.GetRootDirectoryReference().GetFileReference(name);
                tasks.Add(file.CreateAsync(0));
                files.Add(name);
            }
            Task.WaitAll(tasks.ToArray());
            return(files);
        }
Example #8
0
        public void CloudFileDirectoryFileParentValidate()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            CloudFile file = share.GetRootDirectoryReference().
                             GetDirectoryReference("TopDir1").
                             GetDirectoryReference("MidDir1").
                             GetDirectoryReference("EndDir1").
                             GetFileReference("EndFile1");
            CloudFileDirectory directory = file.Parent;

            Assert.AreEqual(directory.Name, "EndDir1");
            Assert.AreEqual(directory.Uri, share.Uri + "/TopDir1/MidDir1/EndDir1");
        }
Example #9
0
 public AzureSession(string connectionString, string shareName, string systemDir, int waitForLockMilliseconds = 5000, bool optimisticLocking = true,
   bool enableCache = true, CacheEnum objectCachingDefaultPolicy = CacheEnum.Yes)
   : base(systemDir, waitForLockMilliseconds, optimisticLocking, enableCache, objectCachingDefaultPolicy)
 {
   m_cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
   if (Path.IsPathRooted(systemDir) == false)
     SystemDirectory = systemDir;
   m_shareName = shareName;
   m_cloudFileClient = m_cloudStorageAccount.CreateCloudFileClient();
   m_cloudShare = m_cloudFileClient.GetShareReference(shareName);
   if (m_cloudShare.Exists())
   {
     m_rootDir = m_cloudShare.GetRootDirectoryReference();
     m_databaseDir = m_rootDir.GetDirectoryReference(systemDir);
     m_databaseDir.CreateIfNotExists();
   }
 }
Example #10
0
        public async Task CloudFileShareUpdateSASTokenAsync()
        {
            // Create a policy with read/write access and get SAS.
            SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write,
            };
            string sasToken = this.testShare.GetSharedAccessSignature(policy);
            //Thread.Sleep(35000);
            CloudFile testFile = this.testShare.GetRootDirectoryReference().GetFileReference("file");

            await UploadTextAsync(testFile, "file", Encoding.UTF8);
            await TestAccess(sasToken, SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write, null, this.testShare, testFile);

            StorageCredentials creds = new StorageCredentials(sasToken);

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

            creds.UpdateSASToken(sasToken2);

            // Extra check to make sure that we have actually updated the SAS token.
            CloudFileShare share     = new CloudFileShare(this.testShare.Uri, creds);
            CloudFile      testFile2 = share.GetRootDirectoryReference().GetFileReference("file2");

            OperationContext context = new OperationContext();
            await TestHelper.ExpectedExceptionAsync(
                async() => await UploadTextAsync(testFile2, "file", Encoding.UTF8, operationContext: context),
                context,
                "Writing to a file while SAS does not allow for writing",
                HttpStatusCode.Forbidden,
                "");

            CloudFile testFile3 = this.testShare.GetRootDirectoryReference().GetFileReference("file3");
            await testFile3.CreateAsync(0);

            await TestAccess(sasToken2, SharedAccessFilePermissions.Read, null, this.testShare, testFile);
        }
Example #11
0
        public void CloudFileDirectoryWithFilesDeleteAPM()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            try
            {
                share.Create();
                if (CloudFileDirectorySetup(share))
                {
                    CloudFileDirectory dir1  = share.GetRootDirectoryReference().GetDirectoryReference("TopDir1/MidDir1/EndDir1");
                    CloudFile          file1 = dir1.GetFileReference("EndFile1");
                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        IAsyncResult result = dir1.BeginDelete(
                            ar => waitHandle.Set(),
                            null);
                        waitHandle.WaitOne();
                        TestHelper.ExpectedException(
                            () => dir1.EndDelete(result),
                            "Delete a non-empty directory",
                            HttpStatusCode.Conflict);

                        result = file1.BeginDelete(
                            ar => waitHandle.Set(),
                            null);
                        waitHandle.WaitOne();
                        file1.EndDelete(result);

                        result = dir1.BeginDelete(
                            ar => waitHandle.Set(),
                            null);
                        waitHandle.WaitOne();
                        dir1.EndDelete(result);
                    }

                    Assert.IsFalse(file1.Exists());
                    Assert.IsFalse(dir1.Exists());
                }
            }
            finally
            {
                share.Delete();
            }
        }
        public async Task CloudFileUploadCancellationAsync()
        {
            CloudFileShare share = DefaultFileClient.GetShareReference(Guid.NewGuid().ToString("N"));

            byte[] buffer = FileTestBase.GetRandomBuffer(4 * 1024 * 1024);

            try
            {
                await share.CreateAsync();

                CloudFile          file           = share.GetRootDirectoryReference().GetFileReference("file1");
                FileRequestOptions requestOptions = new FileRequestOptions()
                {
                    RetryPolicy = new NoRetry()
                };

                CancellationTokenSource cts   = new CancellationTokenSource();
                CancellationToken       token = cts.Token;

                new Task(() =>
                {
                    new System.Threading.ManualResetEvent(false).WaitOne(10);
                    cts.Cancel(false);
                }).Start();

                using (MemoryStream ms = new MemoryStream(buffer))
                {
#if ASPNET_K
                    file.UploadFromStreamAsync(ms, ms.Length, null, requestOptions, null, token).Wait();
#else
                    file.UploadFromStreamAsync(ms.AsInputStream(), null, requestOptions, null).AsTask(token).Wait();
#endif
                }

                Assert.Fail();
            }
            catch (AggregateException e)
            {
                TaskCanceledException ex = new TaskCanceledException();
                Assert.AreEqual(ex.HResult, e.InnerException.HResult);
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task FileOpenWriteSeekReadTestAsync()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

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

                MemoryStream memoryStream = new MemoryStream(buffer);
                using (var fileStream = await file.OpenWriteAsync(2048))
                {
                    Stream fileStreamForWrite = fileStream.AsStreamForWrite();
                    await fileStreamForWrite.WriteAsync(buffer, 0, 2048);

                    Assert.AreEqual(fileStreamForWrite.Position, 2048);

                    fileStreamForWrite.Seek(1024, 0);
                    memoryStream.Seek(1024, 0);
                    Assert.AreEqual(fileStreamForWrite.Position, 1024);

                    byte[] testBuffer = GetRandomBuffer(1024);

                    await memoryStream.WriteAsync(testBuffer, 0, 1024);

                    await fileStreamForWrite.WriteAsync(testBuffer, 0, 1024);

                    Assert.AreEqual(fileStreamForWrite.Position, memoryStream.Position);

                    await fileStreamForWrite.FlushAsync();
                }

                using (var dstStream = await file.OpenReadAsync())
                {
                    Stream dstStreamForRead = dstStream.AsStreamForRead();
                    TestHelper.AssertStreamsAreEqual(memoryStream, dstStreamForRead);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Example #14
0
        public async Task FileUploadWithoutMD5ValidationAndStoreFileContentTestAsync()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile          file    = share.GetRootDirectoryReference().GetFileReference("file1");
                FileRequestOptions options = new FileRequestOptions();
                options.DisableContentMD5Validation = false;
                options.StoreFileContentMD5         = false;
                OperationContext context = new OperationContext();
                using (MemoryStream srcStream = new MemoryStream(buffer))
                {
                    await file.UploadFromStreamAsync(srcStream.AsInputStream(), null, options, context);

                    await file.FetchAttributesAsync();

                    string md5 = file.Properties.ContentMD5;
                    file.Properties.ContentMD5 = "MDAwMDAwMDA=";
                    await file.SetPropertiesAsync(null, options, context);

                    byte[]       testBuffer = new byte[2048];
                    MemoryStream dstStream  = new MemoryStream(testBuffer);
                    await TestHelper.ExpectedExceptionAsync(async() => await file.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null, null, options, context),
                                                            context,
                                                            "Try to Download a stream with a corrupted md5 and DisableMD5Validation set to false",
                                                            HttpStatusCode.OK);

                    options.DisableContentMD5Validation = true;
                    await file.SetPropertiesAsync(null, options, context);

                    byte[]       testBuffer2 = new byte[2048];
                    MemoryStream dstStream2  = new MemoryStream(testBuffer2);
                    await file.DownloadRangeToStreamAsync(dstStream2.AsOutputStream(), null, null, null, options, context);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Example #15
0
        public void FileWriteStreamRandomSeekTest()
        {
            byte[] buffer = GetRandomBuffer(3 * 1024 * 1024);

            CloudFileShare share = GetRandomShareReference();

            share.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;
            try
            {
                share.Create();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (MemoryStream wholeFile = new MemoryStream())
                {
                    using (Stream fileStream = file.OpenWrite(buffer.Length))
                    {
                        fileStream.Write(buffer, 0, buffer.Length);
                        wholeFile.Write(buffer, 0, buffer.Length);
                        Random random = new Random();
                        for (int i = 0; i < 10; i++)
                        {
                            int offset = random.Next(buffer.Length);
                            TestHelper.SeekRandomly(fileStream, offset);
                            fileStream.Write(buffer, 0, buffer.Length - offset);
                            wholeFile.Seek(offset, SeekOrigin.Begin);
                            wholeFile.Write(buffer, 0, buffer.Length - offset);
                        }
                    }

                    file.FetchAttributes();
                    Assert.IsNull(file.Properties.ContentMD5);

                    using (MemoryStream downloadedFile = new MemoryStream())
                    {
                        file.DownloadToStream(downloadedFile);
                        TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile);
                    }
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Example #16
0
        public void CloudFileDirectoryDeleteIfExists()
        {
            CloudFileShare share = GetRandomShareReference();

            share.Create();

            try
            {
                CloudFileDirectory directory = share.GetRootDirectoryReference().GetDirectoryReference("directory1");
                Assert.IsFalse(directory.DeleteIfExists());
                directory.Create();
                Assert.IsTrue(directory.DeleteIfExists());
                Assert.IsFalse(directory.DeleteIfExists());
            }
            finally
            {
                share.Delete();
            }
        }
Example #17
0
        public async Task CloudFileDirectoryDeleteIfExistsAsync()
        {
            CloudFileShare share = GetRandomShareReference();
            await share.CreateAsync();

            try
            {
                CloudFileDirectory directory = share.GetRootDirectoryReference().GetDirectoryReference("directory1");
                Assert.IsFalse(await directory.DeleteIfExistsAsync());
                await directory.CreateAsync();

                Assert.IsTrue(await directory.DeleteIfExistsAsync());
                Assert.IsFalse(await directory.DeleteIfExistsAsync());
            }
            finally
            {
                share.DeleteAsync().Wait();
            }
        }
        public async Task CloudFileCreateAndDeleteAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

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

                Assert.IsTrue(await file.ExistsAsync());
                await file.DeleteAsync();
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public async Task CloudFileClientMaximumExecutionTimeoutAsync()
        {
            CloudFileClient    fileClient    = GenerateCloudFileClient();
            CloudFileShare     share         = fileClient.GetShareReference(Guid.NewGuid().ToString("N"));
            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

            byte[] buffer = FileTestBase.GetRandomBuffer(80 * 1024 * 1024);

            try
            {
                await share.CreateAsync();

                fileClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(5);

                CloudFile file = rootDirectory.GetFileReference("file");
                file.StreamWriteSizeInBytes = 1 * 1024 * 1024;
                using (MemoryStream ms = new MemoryStream(buffer))
                {
                    try
                    {
                        await file.UploadFromStreamAsync(ms);

                        Assert.Fail();
                    }
                    catch (AggregateException ex)
                    {
#if !FACADE_NETCORE
                        Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.Message).ExceptionInfo.Message);
#else
                        Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.Message).Exception.Message);
#endif
                    }
                    catch (TaskCanceledException)
                    {
                    }
                }
            }
            finally
            {
                fileClient.DefaultRequestOptions.MaximumExecutionTime = null;
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task CloudFileApisInShareSnapshotAsync()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);
            await share.CreateAsync();

            CloudFileDirectory dir = share.GetRootDirectoryReference().GetDirectoryReference("dir1");
            await dir.CreateAsync();

            CloudFile file = dir.GetFileReference("file");
            await file.CreateAsync(1024);

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

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

            file.Metadata["key2"] = "value2";
            await file.SetMetadataAsync();

            await snapshotFile.FetchAttributesAsync();

            Assert.IsTrue(snapshotFile.Metadata.Count == 1 && snapshotFile.Metadata["key1"].Equals("value1"));
            Assert.IsNotNull(snapshotFile.Properties.ETag);

            await file.FetchAttributesAsync();

            Assert.IsTrue(file.Metadata.Count == 2 && file.Metadata["key2"].Equals("value2"));
            Assert.IsNotNull(file.Properties.ETag);
            Assert.AreNotEqual(file.Properties.ETag, snapshotFile.Properties.ETag);

            CloudFile snapshotFile2 = new CloudFile(snapshotFile.SnapshotQualifiedStorageUri, client.Credentials);

            Assert.IsTrue(snapshotFile2.ExistsAsync().Result);
            Assert.IsTrue(snapshotFile2.Share.SnapshotTime.HasValue);

            await snapshot.DeleteAsync();

            await share.DeleteAsync();
        }
Example #21
0
        public void CloudFileClientObjects()
        {
            CloudFileClient fileClient = GenerateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("share");

            Assert.AreEqual(fileClient, share.ServiceClient);
            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

            Assert.AreEqual(fileClient, rootDirectory.ServiceClient);
            CloudFileDirectory directory = rootDirectory.GetDirectoryReference("directory");

            Assert.AreEqual(fileClient, directory.ServiceClient);
            CloudFile file = directory.GetFileReference("file");

            Assert.AreEqual(fileClient, file.ServiceClient);

            CloudFileShare share2 = GetRandomShareReference();

            Assert.AreNotEqual(fileClient, share2.ServiceClient);
        }
        public async Task TestFileEncryptionAsync()
        {
            bool requestFound = false;

            OperationContext ctxt  = new OperationContext();
            CloudFileShare   share = GetRandomShareReference();

            try
            {
                await share.CreateIfNotExistsAsync();

                CloudFileDirectory directory = share.GetRootDirectoryReference();
                CloudFile          file      = directory.GetFileReference("file");

                await file.UploadTextAsync("test");

                ctxt.RequestCompleted += (sender, args) =>
                {
                    Assert.IsTrue(args.RequestInformation.IsRequestServerEncrypted);
                    requestFound = true;
                };

                await file.UploadTextAsync("test", null, null, ctxt);

                Assert.IsTrue(requestFound);

                requestFound = false;
                await file.SetPropertiesAsync(null, null, ctxt);

                Assert.IsTrue(requestFound);

                requestFound = false;
                await file.SetMetadataAsync(null, null, ctxt);

                Assert.IsTrue(requestFound);
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public void FileReadWhenOpenWrite()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                share.Create();
                CloudFile    file         = share.GetRootDirectoryReference().GetFileReference("file1");
                MemoryStream memoryStream = new MemoryStream(buffer);
                Stream       fileStream   = file.OpenWrite(2048);
                fileStream.Write(buffer, 0, 2048);
                byte[] testBuffer = new byte[2048];
                TestHelper.ExpectedException <NotSupportedException>(() => fileStream.Read(testBuffer, 0, 2048),
                                                                     "Try reading from a stream opened for Write");
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Example #24
0
        public async Task CloudFileDirectoryApisInvalidApisInShareSnapshotAsync()
        {
            CloudFileShare share = GetRandomShareReference();
            await share.CreateAsync();

            CloudFileShare snapshot = await share.SnapshotAsync();

            CloudFileDirectory dir = snapshot.GetRootDirectoryReference().GetDirectoryReference("dir1");

            try
            {
                dir.CreateAsync().Wait();
                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                dir.DeleteAsync().Wait();
                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }
            try
            {
                dir.SetMetadataAsync(null, null, null).Wait();
                Assert.Fail("API should fail in a snapshot");
            }
            catch (InvalidOperationException e)
            {
                Assert.AreEqual(SR.CannotModifyShareSnapshot, e.Message);
            }

            snapshot.DeleteAsync().Wait();
            share.DeleteAsync().Wait();
        }
Example #25
0
        public async Task CloudFileClientMaximumExecutionTimeoutAsync()
        {
            CloudFileClient    fileClient    = GenerateCloudFileClient();
            CloudFileShare     share         = fileClient.GetShareReference(Guid.NewGuid().ToString("N"));
            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

            byte[] buffer = FileTestBase.GetRandomBuffer(80 * 1024 * 1024);

            try
            {
                await share.CreateAsync();

                fileClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(5);

                CloudFile file = rootDirectory.GetFileReference("file");
                file.StreamWriteSizeInBytes = 1 * 1024 * 1024;
                using (MemoryStream ms = new MemoryStream(buffer))
                {
                    try
                    {
                        await file.UploadFromStreamAsync(ms);

                        Assert.Fail();
                    }
                    catch (TimeoutException ex)
                    {
                        Assert.IsInstanceOfType(ex, typeof(TimeoutException));
                    }
                    catch (StorageException ex)
                    {
                        Assert.IsInstanceOfType(ex.InnerException, typeof(TimeoutException));
                    }
                }
            }
            finally
            {
                fileClient.DefaultRequestOptions.MaximumExecutionTime = null;
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task CloudFileAlignmentAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile        file             = share.GetRootDirectoryReference().GetFileReference("file1");
                OperationContext operationContext = new OperationContext();

                await file.CreateAsync(511);

                await file.CreateAsync(512);

                await file.CreateAsync(513);

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

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

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.SetLength(513);
                    await file.WriteRangeAsync(stream.AsInputStream(), 0, null);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public void FileOpenReadTest()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                share.Create();
                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (MemoryStream srcStream = new MemoryStream(buffer))
                {
                    file.UploadFromStream(srcStream);

                    Stream dstStream = file.OpenRead();
                    TestHelper.AssertStreamsAreEqual(srcStream, dstStream);
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Example #28
0
        private async Task CloudFileUploadFromStreamAsync(CloudFileShare share, int size, long?copyLength, AccessCondition accessCondition, OperationContext operationContext, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(size);

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

            file.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalFileStream = new MemoryStream())
            {
                originalFileStream.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    if (copyLength.HasValue)
                    {
                        await file.UploadFromStreamAsync(sourceStream, copyLength.Value, accessCondition, null, operationContext);
                    }
                    else
                    {
                        await file.UploadFromStreamAsync(sourceStream, accessCondition, null, operationContext);
                    }
                }

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

                    Assert.AreEqual(copyLength ?? originalFileStream.Length, downloadedFileStream.Length);
                    TestHelper.AssertStreamsAreEqualAtIndex(
                        originalFileStream,
                        downloadedFileStream,
                        0,
                        0,
                        copyLength.HasValue ? (int)copyLength : (int)originalFileStream.Length);
                }
            }
        }
Example #29
0
        public async Task CloudFileDownloadToStreamCancelAsync()
        {
            byte[]         buffer = GetRandomBuffer(1 * 1024 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (MemoryStream originalFile = new MemoryStream(buffer))
                {
                    await file.UploadFromStreamAsync(originalFile);

                    using (MemoryStream downloadedFile = new MemoryStream())
                    {
                        OperationContext        operationContext = new OperationContext();
                        CancellationTokenSource source           = new CancellationTokenSource(100);
                        Task task = file.DownloadToStreamAsync(downloadedFile, null, null, operationContext, source.Token);
                        try
                        {
                            await task;
                        }
                        catch (Exception)
                        {
                            Assert.AreEqual(operationContext.LastResult.Exception.Message, "Operation was canceled by user.");
                            Assert.AreEqual(operationContext.LastResult.HttpStatusCode, 306);
                            //Assert.AreEqual(operationContext.LastResult.HttpStatusMessage, "Unused");
                        }
                        TestHelper.AssertNAttempts(operationContext, 1);
                    }
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public void CloudFileShareListFilesAndDirectoriesSegmentedAPM()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();
                List <string>      fileNames     = CreateFiles(share, 3);
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    FileContinuationToken token = null;
                    do
                    {
                        IAsyncResult result = rootDirectory.BeginListFilesAndDirectoriesSegmented(1, token, null, null,
                                                                                                  ar => waitHandle.Set(),
                                                                                                  null);
                        waitHandle.WaitOne();
                        FileResultSegment results = rootDirectory.EndListFilesAndDirectoriesSegmented(result);
                        int count = 0;
                        foreach (IListFileItem fileItem in results.Results)
                        {
                            Assert.IsInstanceOfType(fileItem, typeof(CloudFile));
                            Assert.IsTrue(fileNames.Remove(((CloudFile)fileItem).Name));
                            count++;
                        }
                        Assert.IsTrue(count <= 1);
                        token = results.ContinuationToken;
                    }while (token != null);
                    Assert.AreEqual(0, fileNames.Count);
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Example #31
0
        public void CloudFileDirectoryDeleteIfExistsAPM()
        {
            CloudFileShare share = GetRandomShareReference();

            share.Create();

            try
            {
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    CloudFileDirectory directory = share.GetRootDirectoryReference().GetDirectoryReference("directory1");
                    IAsyncResult       result    = directory.BeginDeleteIfExists(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    Assert.IsFalse(directory.EndDeleteIfExists(result));
                    result = directory.BeginCreate(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    directory.EndCreate(result);
                    result = directory.BeginDeleteIfExists(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    Assert.IsTrue(directory.EndDeleteIfExists(result));
                    result = directory.BeginDeleteIfExists(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    Assert.IsFalse(directory.EndDeleteIfExists(result));
                }
            }
            finally
            {
                share.Delete();
            }
        }
        public void FileOpenReadWriteTest()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                share.Create();
                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");

                Stream fileStream = file.OpenWrite(2048);
                fileStream.Write(buffer, 0, 2048);
                fileStream.Close();

                MemoryStream memoryStream = new MemoryStream(buffer);
                Stream       dstStream    = file.OpenRead();
                TestHelper.AssertStreamsAreEqual(memoryStream, dstStream);
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        public void CloudFileShareListFilesAndDirectories()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();
                List <string>      fileNames     = CreateFiles(share, 3);
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

                IEnumerable <IListFileItem> results = rootDirectory.ListFilesAndDirectories();
                Assert.AreEqual(fileNames.Count, results.Count());
                foreach (IListFileItem fileItem in results)
                {
                    Assert.IsInstanceOfType(fileItem, typeof(CloudFile));
                    Assert.IsTrue(fileNames.Remove(((CloudFile)fileItem).Name));
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        private async Task<bool> CloudFileDirectorySetupAsync(CloudFileShare share)
        {
            try
            {
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                for (int i = 1; i < 3; i++)
                {
                    CloudFileDirectory topDirectory = rootDirectory.GetDirectoryReference("TopDir" + i);
                    await topDirectory.CreateAsync();

                    for (int j = 1; j < 3; j++)
                    {
                        CloudFileDirectory midDirectory = topDirectory.GetDirectoryReference("MidDir" + j);
                        await midDirectory.CreateAsync();

                        for (int k = 1; k < 3; k++)
                        {
                            CloudFileDirectory endDirectory = midDirectory.GetDirectoryReference("EndDir" + k);
                            await endDirectory.CreateAsync();

                            CloudFile file1 = endDirectory.GetFileReference("EndFile" + k);
                            await file1.CreateAsync(0);
                        }
                    }

                    CloudFile file2 = topDirectory.GetFileReference("File" + i);
                    await file2.CreateAsync(0);
                }

                return true;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        private bool CloudFileDirectorySetup(CloudFileShare share)
        {
            try
            {
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                for (int i = 1; i < 3; i++)
                {
                    CloudFileDirectory topDirectory = rootDirectory.GetDirectoryReference("TopDir" + i);
                    topDirectory.Create();

                    for (int j = 1; j < 3; j++)
                    {
                        CloudFileDirectory midDirectory = topDirectory.GetDirectoryReference("MidDir" + j);
                        midDirectory.Create();

                        for (int k = 1; k < 3; k++)
                        {
                            CloudFileDirectory endDirectory = midDirectory.GetDirectoryReference("EndDir" + k);
                            endDirectory.Create();

                            CloudFile file1 = endDirectory.GetFileReference("EndFile" + k);
                            file1.Create(0);
                        }
                    }

                    CloudFile file2 = topDirectory.GetFileReference("File" + i);
                    file2.Create(0);
                }

                return true;
            }
            catch (StorageException e)
            {
                throw e;
            }

        }
        public void CloudFileShareUpdateSASToken()
        {
            // Create a policy with read/write access and get SAS.
            SharedAccessFilePolicy policy = new SharedAccessFilePolicy()
            {
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write,
            };
            string sasToken = this.testShare.GetSharedAccessSignature(policy);
            //Thread.Sleep(35000);
            CloudFile testFile = this.testShare.GetRootDirectoryReference().GetFileReference("file");
            UploadText(testFile, "file", Encoding.UTF8);
            TestAccess(sasToken, SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write, null, this.testShare, testFile);

            StorageCredentials creds = new StorageCredentials(sasToken);

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

            // Extra check to make sure that we have actually updated the SAS token.
            CloudFileShare share = new CloudFileShare(this.testShare.Uri, creds);
            CloudFile testFile2 = share.GetRootDirectoryReference().GetFileReference("file2");

            TestHelper.ExpectedException(
                () => UploadText(testFile2, "file", Encoding.UTF8),
                "Writing to a file while SAS does not allow for writing",
                HttpStatusCode.NotFound);

            CloudFile testFile3 = this.testShare.GetRootDirectoryReference().GetFileReference("file3");
            testFile3.Create(0);
            TestAccess(sasToken2, SharedAccessFilePermissions.Read, null, this.testShare, testFile);
        }
        public void FileTypesWithStorageUri()
        {
            StorageUri endpoint = new StorageUri(
                new Uri("http://" + AccountName + FileService + EndpointSuffix),
                new Uri("http://" + AccountName + SecondarySuffix + FileService + EndpointSuffix));

            CloudFileClient client = new CloudFileClient(endpoint, new StorageCredentials());
            Assert.IsTrue(endpoint.Equals(client.StorageUri));
            Assert.IsTrue(endpoint.PrimaryUri.Equals(client.BaseUri));

            StorageUri shareUri = new StorageUri(
                new Uri(endpoint.PrimaryUri + "share"),
                new Uri(endpoint.SecondaryUri + "share"));

            CloudFileShare share = client.GetShareReference("share");
            Assert.IsTrue(shareUri.Equals(share.StorageUri));
            Assert.IsTrue(shareUri.PrimaryUri.Equals(share.Uri));
            Assert.IsTrue(endpoint.Equals(share.ServiceClient.StorageUri));

            share = new CloudFileShare(shareUri, client.Credentials);
            Assert.IsTrue(shareUri.Equals(share.StorageUri));
            Assert.IsTrue(shareUri.PrimaryUri.Equals(share.Uri));
            Assert.IsTrue(endpoint.Equals(share.ServiceClient.StorageUri));

            StorageUri directoryUri = new StorageUri(
                new Uri(shareUri.PrimaryUri + "/directory"),
                new Uri(shareUri.SecondaryUri + "/directory"));

            StorageUri subdirectoryUri = new StorageUri(
                new Uri(directoryUri.PrimaryUri + "/subdirectory"),
                new Uri(directoryUri.SecondaryUri + "/subdirectory"));

            CloudFileDirectory directory = share.GetRootDirectoryReference().GetDirectoryReference("directory");
            Assert.IsTrue(directoryUri.Equals(directory.StorageUri));
            Assert.IsTrue(directoryUri.PrimaryUri.Equals(directory.Uri));
            Assert.IsNotNull(directory.Parent);
            Assert.IsTrue(shareUri.Equals(directory.Share.StorageUri));
            Assert.IsTrue(endpoint.Equals(directory.ServiceClient.StorageUri));

            CloudFileDirectory subdirectory = directory.GetDirectoryReference("subdirectory");
            Assert.IsTrue(subdirectoryUri.Equals(subdirectory.StorageUri));
            Assert.IsTrue(subdirectoryUri.PrimaryUri.Equals(subdirectory.Uri));
            Assert.IsTrue(directoryUri.Equals(subdirectory.Parent.StorageUri));
            Assert.IsTrue(shareUri.Equals(subdirectory.Share.StorageUri));
            Assert.IsTrue(endpoint.Equals(subdirectory.ServiceClient.StorageUri));

            StorageUri fileUri = new StorageUri(
                new Uri(subdirectoryUri.PrimaryUri + "/file"),
                new Uri(subdirectoryUri.SecondaryUri + "/file"));

            CloudFile file = subdirectory.GetFileReference("file");
            Assert.IsTrue(fileUri.Equals(file.StorageUri));
            Assert.IsTrue(fileUri.PrimaryUri.Equals(file.Uri));
            Assert.IsTrue(subdirectoryUri.Equals(file.Parent.StorageUri));
            Assert.IsTrue(shareUri.Equals(file.Share.StorageUri));
            Assert.IsTrue(endpoint.Equals(file.ServiceClient.StorageUri));

            file = new CloudFile(fileUri, client.Credentials);
            Assert.IsTrue(fileUri.Equals(file.StorageUri));
            Assert.IsTrue(fileUri.PrimaryUri.Equals(file.Uri));
            Assert.IsTrue(subdirectoryUri.Equals(file.Parent.StorageUri));
            Assert.IsTrue(shareUri.Equals(file.Share.StorageUri));
            Assert.IsTrue(endpoint.Equals(file.ServiceClient.StorageUri));
        }
        private async Task CloudFileUploadFromStreamAsync(CloudFileShare share, int size, long? copyLength, AccessCondition accessCondition, OperationContext operationContext, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(size);

            CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
            file.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalFileStream = new MemoryStream())
            {
                originalFileStream.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    if (copyLength.HasValue)
                    {
                        await file.UploadFromStreamAsync(sourceStream, copyLength.Value, accessCondition, null, operationContext); 
                    }
                    else
                    {
                        await file.UploadFromStreamAsync(sourceStream, accessCondition, null, operationContext); 
                    }
                }

                using (MemoryStream downloadedFileStream = new MemoryStream())
                {
                    await file.DownloadToStreamAsync(downloadedFileStream);
                    Assert.AreEqual(copyLength ?? originalFileStream.Length, downloadedFileStream.Length);
                    TestHelper.AssertStreamsAreEqualAtIndex(
                        originalFileStream,
                        downloadedFileStream,
                        0,
                        0,
                        copyLength.HasValue ? (int)copyLength : (int)originalFileStream.Length);
                }
            }
        }
        private void CloudFileUploadFromStream(CloudFileShare share, int size, long? copyLength, AccessCondition accessCondition, int startOffset, bool isAsync, bool testMd5)
        {
            byte[] buffer = GetRandomBuffer(size);

            MD5 hasher = MD5.Create();
            string md5 = string.Empty;
            if (testMd5)
            {
                md5 = Convert.ToBase64String(hasher.ComputeHash(buffer, startOffset, copyLength.HasValue ? (int)copyLength : buffer.Length - startOffset));
            }

            CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
            file.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalFile = new MemoryStream())
            {
                originalFile.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true,
                    };
                    if (isAsync)
                    {
                        using (ManualResetEvent waitHandle = new ManualResetEvent(false))
                        {
                            if (copyLength.HasValue)
                            {
                                ICancellableAsyncResult result = file.BeginUploadFromStream(
                                    sourceStream, copyLength.Value, accessCondition, options, null, ar => waitHandle.Set(), null);
                                waitHandle.WaitOne();
                                file.EndUploadFromStream(result);
                            }
                            else
                            {
                                ICancellableAsyncResult result = file.BeginUploadFromStream(
                                    sourceStream, accessCondition, options, null, ar => waitHandle.Set(), null);
                                waitHandle.WaitOne();
                                file.EndUploadFromStream(result);
                            }
                        }
                    }
                    else
                    {
                        if (copyLength.HasValue)
                        {
                            file.UploadFromStream(sourceStream, copyLength.Value, accessCondition, options);
                        }
                        else
                        {
                            file.UploadFromStream(sourceStream, accessCondition, options);
                        }
                    }
                }

                file.FetchAttributes();
                if (testMd5)
                {
                    Assert.AreEqual(md5, file.Properties.ContentMD5);
                }

                using (MemoryStream downloadedFile = new MemoryStream())
                {
                    if (isAsync)
                    {
                        using (ManualResetEvent waitHandle = new ManualResetEvent(false))
                        {
                            ICancellableAsyncResult result = file.BeginDownloadToStream(downloadedFile,
                                ar => waitHandle.Set(),
                                null);
                            waitHandle.WaitOne();
                            file.EndDownloadToStream(result);
                        }
                    }
                    else
                    {
                        file.DownloadToStream(downloadedFile);
                    }

                    TestHelper.AssertStreamsAreEqualAtIndex(
                        originalFile,
                        downloadedFile,
                        0,
                        0,
                        copyLength.HasValue ? (int)copyLength : (int)originalFile.Length);
                }
            }
        }
        private async Task CloudFileUploadFromStreamAsync(CloudFileShare share, int size, long? copyLength, AccessCondition accessCondition, OperationContext operationContext, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(size);
#if NETCORE
            MD5 hasher = MD5.Create();
            string md5 = Convert.ToBase64String(hasher.ComputeHash(buffer, startOffset, copyLength.HasValue ? (int)copyLength : buffer.Length - startOffset));
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer(startOffset, copyLength.HasValue ? (int)copyLength.Value : buffer.Length - startOffset));
            string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif

            CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
            file.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalFileStream = new MemoryStream())
            {
                originalFileStream.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true,
                    };
                    if (copyLength.HasValue)
                    {
                        await file.UploadFromStreamAsync(sourceStream, copyLength.Value, accessCondition, options, operationContext);
                    }
                    else
                    {
                        await file.UploadFromStreamAsync(sourceStream, accessCondition, options, operationContext);
                    }
                }

                await file.FetchAttributesAsync();
                Assert.AreEqual(md5, file.Properties.ContentMD5);

                using (MemoryStream downloadedFileStream = new MemoryStream())
                {
                    await file.DownloadToStreamAsync(downloadedFileStream);
                    Assert.AreEqual(copyLength ?? originalFileStream.Length, downloadedFileStream.Length);
                    TestHelper.AssertStreamsAreEqualAtIndex(
                        originalFileStream,
                        downloadedFileStream,
                        0,
                        0,
                        copyLength.HasValue ? (int)copyLength : (int)originalFileStream.Length);
                }
            }
        }
        private void CloudFileUploadFromStreamTask(CloudFileShare share, int size, long? copyLength, AccessCondition accessCondition, int startOffset, bool testMd5)
        {
            try
            {
                byte[] buffer = GetRandomBuffer(size);

                MD5 hasher = MD5.Create();
                string md5 = string.Empty;
                if (testMd5)
                {
                    md5 = Convert.ToBase64String(hasher.ComputeHash(buffer, startOffset, copyLength.HasValue ? (int)copyLength : buffer.Length - startOffset));
                }

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                file.StreamWriteSizeInBytes = 512;

                using (MemoryStream originalFile = new MemoryStream())
                {
                    originalFile.Write(buffer, startOffset, buffer.Length - startOffset);

                    using (MemoryStream sourceStream = new MemoryStream(buffer))
                    {
                        sourceStream.Seek(startOffset, SeekOrigin.Begin);
                        FileRequestOptions options = new FileRequestOptions()
                        {
                            StoreFileContentMD5 = true,
                        };

                        if (copyLength.HasValue)
                        {
                            file.UploadFromStreamAsync(sourceStream, copyLength.Value, accessCondition, options, null).Wait();
                        }
                        else
                        {
                            file.UploadFromStreamAsync(sourceStream, accessCondition, options, null).Wait();
                        }
                    }

                    file.FetchAttributesAsync().Wait();
                    if (testMd5)
                    {
                        Assert.AreEqual(md5, file.Properties.ContentMD5);
                    }

                    using (MemoryStream downloadedFile = new MemoryStream())
                    {
                        file.DownloadToStreamAsync(downloadedFile).Wait();

                        TestHelper.AssertStreamsAreEqualAtIndex(
                            originalFile,
                            downloadedFile,
                            0,
                            0,
                            copyLength.HasValue ? (int)copyLength : (int)originalFile.Length);
                    }
                }
            }
            catch (AggregateException ex)
            {
                throw ex.InnerException;
            }
        }
        private static void TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file)
        {
            CloudFileShare SASshare = null;
            CloudFile SASfile;
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);
            string fileText = "file";

            if (share != null)
            {
                SASshare = new CloudFileShare(credentials.TransformUri(share.Uri));
                SASfile = SASshare.GetRootDirectoryReference().GetFileReference(file.Name);
            }
            else
            {
                SASfile = new CloudFile(credentials.TransformUri(file.Uri));
            }

            if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write)
            {
                UploadText(SASfile, fileText, Encoding.UTF8);
            }
            else if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create)
            {
                SASfile.Create(Encoding.UTF8.GetBytes(fileText).Length);
                TestHelper.ExpectedException(
                    () => UploadText(SASfile, fileText, Encoding.UTF8),
                    "UploadText SAS does not allow for writing",
                    HttpStatusCode.Forbidden);
                UploadText(file, fileText, Encoding.UTF8);

            }
            else 
            {
                TestHelper.ExpectedException(
                        () => SASfile.Create(Encoding.UTF8.GetBytes(fileText).Length),
                        "Create file succeeded but SAS does not allow for writing/creating",
                        HttpStatusCode.Forbidden);
                TestHelper.ExpectedException(
                        () => UploadText(SASfile, fileText, Encoding.UTF8),
                        "UploadText SAS does not allow for writing/creating",
                        HttpStatusCode.Forbidden);
                UploadText(file, fileText, Encoding.UTF8);
            }

            if (SASshare != null)
            {
                if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List)
                {
                    SASshare.GetRootDirectoryReference().ListFilesAndDirectories().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => SASshare.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(),
                        "List files while SAS does not allow for listing",
                        HttpStatusCode.Forbidden);
                }
            }

            if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read)
            {
                SASfile.FetchAttributes();
                
                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, SASfile.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, SASfile.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, SASfile.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, SASfile.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, SASfile.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASfile.FetchAttributes(),
                    "Fetch file attributes while SAS does not allow for reading",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write)
            {
                SASfile.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASfile.SetMetadata(),
                    "Set file metadata while SAS does not allow for writing",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete)
            {
                SASfile.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASfile.Delete(),
                    "Delete file while SAS does not allow for deleting",
                    HttpStatusCode.Forbidden);
            }
        }
        private static void TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file)
        {
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);

            if (share != null)
            {
                share = new CloudFileShare(credentials.TransformUri(share.Uri));
                file = share.GetRootDirectoryReference().GetFileReference(file.Name);
            }
            else
            {
                file = new CloudFile(credentials.TransformUri(file.Uri));
            }

            if (share != null)
            {
                if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List)
                {
                    share.GetRootDirectoryReference().ListFilesAndDirectories().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => share.GetRootDirectoryReference().ListFilesAndDirectories().ToArray(),
                        "List files while SAS does not allow for listing",
                        HttpStatusCode.NotFound);
                }
            }

            if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read)
            {
                file.FetchAttributes();
                
                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, file.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, file.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, file.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, file.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, file.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => file.FetchAttributes(),
                    "Fetch file attributes while SAS does not allow for reading",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write)
            {
                file.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => file.SetMetadata(),
                    "Set file metadata while SAS does not allow for writing",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete)
            {
                file.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => file.Delete(),
                    "Delete file while SAS does not allow for deleting",
                    HttpStatusCode.NotFound);
            }
        }
        private static async Task TestAccess(string sasToken, SharedAccessFilePermissions permissions, SharedAccessFileHeaders headers, CloudFileShare share, CloudFile file)
        {
            CloudFileShare SASshare = null;
            CloudFile SASfile;
            OperationContext context = new OperationContext();
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);
            string fileText = "file";

            if (share != null)
            {
                SASshare = new CloudFileShare(credentials.TransformUri(share.Uri));
                SASfile = SASshare.GetRootDirectoryReference().GetFileReference(file.Name);
            }
            else
            {
                SASfile = new CloudFile(credentials.TransformUri(file.Uri));
            }

            if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write)
            {
                await UploadTextAsync(SASfile, fileText, Encoding.UTF8);
            }
            else if ((permissions & SharedAccessFilePermissions.Create) == SharedAccessFilePermissions.Create)
            {
                await SASfile.CreateAsync(Encoding.UTF8.GetBytes(fileText).Length);
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await UploadTextAsync(SASfile, fileText, Encoding.UTF8, operationContext:context),
                    context,
                    "UploadText SAS does not allow for writing",
                    HttpStatusCode.Forbidden,
                    "");
                await UploadTextAsync(file, fileText, Encoding.UTF8);

            }
            else
            {
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                        async () => await SASfile.CreateAsync(Encoding.UTF8.GetBytes(fileText).Length, null /* accessCondition */, null /* options */, context),
                        context,
                        "Create file succeeded but SAS does not allow for writing/creating",
                        HttpStatusCode.Forbidden,
                        "");
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await UploadTextAsync(SASfile, fileText, Encoding.UTF8, operationContext:context),
                        context,
                        "UploadText SAS does not allow for writing/creating",
                        HttpStatusCode.Forbidden,
                        "");
                await UploadTextAsync(file, fileText, Encoding.UTF8);
            }

            if (SASshare != null)
            {
                if ((permissions & SharedAccessFilePermissions.List) == SharedAccessFilePermissions.List)
                {
                    var results = await SASshare.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(null);
                }
                else
                {
                    context = new OperationContext();
                    await TestHelper.ExpectedExceptionAsync(
                        async () => { var results = await SASshare.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(null /* maxResults */, null /* currentToken */, null /* options */, context); },
                        context,
                        "List files while SAS does not allow for listing",
                        HttpStatusCode.Forbidden,
                        "");
                }
            }

            if ((permissions & SharedAccessFilePermissions.Read) == SharedAccessFilePermissions.Read)
            {
                await SASfile.FetchAttributesAsync();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, SASfile.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, SASfile.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, SASfile.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, SASfile.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, SASfile.Properties.ContentType);
                    }
                }
            }
            else
            {
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await SASfile.FetchAttributesAsync(null /* accessCondition */, null /* options */, context),
                    context,
                    "Fetch file attributes while SAS does not allow for reading",
                    HttpStatusCode.Forbidden,
                    "");
            }

            if ((permissions & SharedAccessFilePermissions.Write) == SharedAccessFilePermissions.Write)
            {
                await SASfile.SetMetadataAsync();
            }
            else
            {
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await SASfile.SetMetadataAsync(null /* accessCondition */, null /* options */, context),
                    context,
                    "Set file metadata while SAS does not allow for writing",
                    HttpStatusCode.Forbidden,
                    "");
            }

            if ((permissions & SharedAccessFilePermissions.Delete) == SharedAccessFilePermissions.Delete)
            {
                await SASfile.DeleteAsync();
            }
            else
            {
                context = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async () => await SASfile.DeleteAsync(null /* accessCondition */, null /* options */, context),
                    context,
                    "Delete file while SAS does not allow for deleting",
                    HttpStatusCode.Forbidden,
                    "");
            }
        }