Exemplo n.º 1
0
 public AzureOperations(string connectionString, string shareName)
 {
     var account = CloudStorageAccount.Parse(connectionString);
     client = account.CreateCloudFileClient();
     share = client.GetShareReference(shareName);
     share.CreateIfNotExists();
     root = share.GetRootDirectoryReference();
 }
Exemplo n.º 2
0
 public void TestCleanup()
 {
     this.testShare.Delete();
     this.testShare = null;
     if (TestBase.FileBufferManager != null)
     {
         Assert.AreEqual(0, TestBase.FileBufferManager.OutstandingBufferCount);
     }
 }
Exemplo n.º 3
0
        public void TestInitialize()
        {
            this.testShare = GetRandomShareReference();
            this.testShare.Create();

            if (TestBase.FileBufferManager != null)
            {
                TestBase.FileBufferManager.OutstandingBufferCount = 0;
            }
        }
 public async Task TestInitialize()
 {
     this.testShare = GetRandomShareReference();
     await this.testShare.CreateIfNotExistsAsync();
     
     if (TestBase.FileBufferManager != null)
     {
         TestBase.FileBufferManager.OutstandingBufferCount = 0;
     }
 }
 public Task FetchShareAttributesAsync(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken token)
 {
     if (this.availableShareNames.Contains(share.Name))
     {
         return TaskEx.FromResult(true);
     }
     else
     {
         throw new MockupException("ShareNotExist");
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudFileDirectory"/> class given an address and a client.
        /// </summary>
        /// <param name="uri">The file directory's Uri.</param>
        /// <param name="directoryName">Name of the directory.</param>
        /// <param name="share">The share for the directory.</param>
        internal CloudFileDirectory(StorageUri uri, string directoryName, CloudFileShare share)
        {
            CommonUtility.AssertNotNull("uri", uri);
            CommonUtility.AssertNotNull("directoryName", directoryName);
            CommonUtility.AssertNotNull("share", share);

            this.Properties = new FileDirectoryProperties();
            this.StorageUri = uri;
            this.ServiceClient = share.ServiceClient;
            this.share = share;
            this.Name = directoryName;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudFile"/> class using the specified file name and
        /// the parent share reference.
        /// </summary>
        /// <param name="uri">The file's Uri.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="share">The reference to the parent share.</param>
        internal CloudFile(StorageUri uri, string fileName, CloudFileShare share)
        {
            CommonUtility.AssertNotNull("uri", uri);
            CommonUtility.AssertNotNullOrEmpty("fileName", fileName);
            CommonUtility.AssertNotNull("share", share);

            this.attributes = new CloudFileAttributes();
            this.attributes.StorageUri = uri;
            this.ServiceClient = share.ServiceClient;
            this.share = share;
            this.Name = fileName;
        }
Exemplo n.º 8
0
        public FileStorage(string fileShareName, string storageConnectionString )
        {
            Validate.String(fileShareName, "fileShareName");
            Validate.String(storageConnectionString, "storageConnectionString");

            var cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);

            var fileClient = cloudStorageAccount.CreateCloudFileClient();

            cloudFileShare = fileClient.GetShareReference(fileShareName);
            cloudFileShare.CreateIfNotExists();
        }
Exemplo n.º 9
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;
 }
Exemplo n.º 10
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();
   }
 }
        private void Initialise(LoggingEvent loggingEvent)
        {
            if (_storageAccount == null || AzureStorageConnectionString != _thisConnectionString) {
                _storageAccount = CloudStorageAccount.Parse(AzureStorageConnectionString);
                _thisConnectionString = AzureStorageConnectionString;
                _client = null;
                _share = null;
                _folder = null;
                _file = null;
            }

            if (_client == null) {
                _client = _storageAccount.CreateCloudFileClient();
                _share = null;
                _folder = null;
                _file = null;
            }

            if (_share == null || _share.Name != ShareName) {
                _share = _client.GetShareReference(ShareName);
                _share.CreateIfNotExists();
                _folder = null;
                _file = null;
            }

            if (_folder == null || Path != _thisFolder) {
                var pathElements = Path.Split(new[] {'\\', '/'}, StringSplitOptions.RemoveEmptyEntries);

                _folder = _share.GetRootDirectoryReference();
                foreach (var element in pathElements) {
                    _folder = _folder.GetDirectoryReference(element);
                    _folder.CreateIfNotExists();
                }

                _thisFolder = Path;
                _file = null;
            }

            var filename = Regex.Replace(File, @"\{(.+?)\}", _ => loggingEvent.TimeStamp.ToString(_.Result("$1")));
            if (_file == null || filename != _thisFile) {
                _file = _folder.GetFileReference(filename);
                if (!_file.Exists()) _file.Create(0);
                _thisFile = filename;
            }
        }
Exemplo n.º 12
0
        public async Task CloudFileDirectoryGetParentAsync()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetDirectoryReference("Dir1").GetFileReference("File1");
                Assert.AreEqual("File1", file.Name);

                // get the file's parent
                CloudFileDirectory parent = file.Parent;
                Assert.AreEqual(parent.Name, "Dir1");

                // get share as parent
                CloudFileDirectory root = parent.Parent;
                Assert.AreEqual(root.Name, "");

                // make sure the parent of the share dir is null
                CloudFileDirectory empty = root.Parent;
                Assert.IsNull(empty);

                // from share, get directory reference to share
                root = share.GetRootDirectoryReference();
                Assert.AreEqual("", root.Name);
                Assert.AreEqual(share.Uri.AbsoluteUri, root.Uri.AbsoluteUri);

                // make sure the parent of the share dir is null
                empty = root.Parent;
                Assert.IsNull(empty);
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 13
0
        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();
            }
        }
        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();
            }
        }
Exemplo n.º 15
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();
            }
        }
Exemplo n.º 16
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();
            }
        }
Exemplo n.º 17
0
        public void CloudFileClientMaximumExecutionTimeout()
        {
            CloudFileClient    fileClient    = GenerateCloudFileClient();
            CloudFileShare     share         = fileClient.GetShareReference(GetRandomShareName());
            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

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

            try
            {
                share.Create();
                fileClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(5);

                CloudFile file = rootDirectory.GetFileReference("file1");
                file.StreamWriteSizeInBytes = 1 * 1024 * 1024;
                using (MemoryStream ms = new MemoryStream(buffer))
                {
                    try
                    {
                        file.UploadFromStream(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.DeleteIfExists();
            }
        }
Exemplo n.º 18
0
        public async Task CloudFileShareCreateWithMetadataAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Metadata.Add("key1", "value1");
                await share.CreateAsync();

                CloudFileShare share2 = share.ServiceClient.GetShareReference(share.Name);
                await share2.FetchAttributesAsync();

                Assert.AreEqual(1, share2.Metadata.Count);
                Assert.AreEqual("value1", share2.Metadata["key1"]);

                Assert.IsTrue(share2.Properties.LastModified.Value.AddHours(1) > DateTimeOffset.Now);
                Assert.IsNotNull(share2.Properties.ETag);
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
        public async Task CloudFileCreateWithMetadataAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                file.Metadata["key1"] = "value1";
                await file.CreateAsync(1024);

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

                Assert.AreEqual(1, file2.Metadata.Count);
                Assert.AreEqual("value1", file2.Metadata["key1"]);
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        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();
            }
        }
        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 async Task CloudFileUploadTimeoutAsync()
        {
            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()
                {
                    MaximumExecutionTime = TimeSpan.FromMilliseconds(10),
                    RetryPolicy          = new NoRetry()
                };

                using (MemoryStream ms = new MemoryStream(buffer))
                {
                    await file.UploadFromStreamAsync(ms.AsInputStream(), null, requestOptions, null);
                }

                Assert.Fail();
            }
            catch (Exception e)
            {
#if ASPNET_K
                Assert.AreEqual(WindowsAzureErrorCode.TimeoutException, e.InnerException.InnerException.HResult);
#else
                Assert.AreEqual(WindowsAzureErrorCode.HttpRequestTimeout, e.InnerException.InnerException.HResult);
#endif
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        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;
            }

        }
Exemplo n.º 24
0
        public async Task FileWriteWhenOpenReadAsync()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

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

                    bool   thrown     = false;
                    byte[] testBuffer = new byte[2048];
                    using (var fileStream = await file.OpenReadAsync())
                    {
                        Stream fileStreamForRead = fileStream.AsStreamForRead();
                        try
                        {
                            await fileStreamForRead.WriteAsync(testBuffer, 0, 2048);
                        }
                        catch (NotSupportedException)
                        {
                            thrown = true;
                        }

                        Assert.IsTrue(thrown);
                    }
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        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;
            }

        }
        public async Task CloudFileFetchAttributesAsync()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

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

                Assert.AreEqual(1024, file.Properties.Length);
                Assert.IsNotNull(file.Properties.ETag);
                Assert.IsTrue(file.Properties.LastModified > DateTimeOffset.UtcNow.AddMinutes(-5));
                Assert.IsNull(file.Properties.CacheControl);
                Assert.IsNull(file.Properties.ContentEncoding);
                Assert.IsNull(file.Properties.ContentLanguage);
                Assert.IsNull(file.Properties.ContentType);
                Assert.IsNull(file.Properties.ContentMD5);

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

                Assert.AreEqual(1024, file2.Properties.Length);
                Assert.AreEqual(file.Properties.ETag, file2.Properties.ETag);
                Assert.AreEqual(file.Properties.LastModified, file2.Properties.LastModified);
                Assert.IsNull(file2.Properties.CacheControl);
                Assert.IsNull(file2.Properties.ContentEncoding);
                Assert.IsNull(file2.Properties.ContentLanguage);
                Assert.AreEqual("application/octet-stream", file2.Properties.ContentType);
                Assert.IsNull(file2.Properties.ContentMD5);
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 27
0
        public void CopyFileUsingUnicodeFileName()
        {
            string _unicodeFileName    = "繁体字14a6c";
            string _nonUnicodeFileName = "sample_file";

            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();
                CloudFile fileUnicodeSource = share.GetRootDirectoryReference().GetFileReference(_unicodeFileName);
                string    data = "Test content";
                UploadText(fileUnicodeSource, data, Encoding.UTF8);
                CloudFile fileAsciiSource = share.GetRootDirectoryReference().GetFileReference(_nonUnicodeFileName);
                UploadText(fileAsciiSource, data, Encoding.UTF8);

                //Copy files over
                CloudFile fileAsciiDest = share.GetRootDirectoryReference().GetFileReference(_nonUnicodeFileName + "_copy");
                string    copyId        = fileAsciiDest.StartCopy(TestHelper.Defiddler(fileAsciiSource));
                WaitForCopy(fileAsciiDest);

                CloudFile fileUnicodeDest = share.GetRootDirectoryReference().GetFileReference(_unicodeFileName + "_copy");
                copyId = fileUnicodeDest.StartCopy(TestHelper.Defiddler(fileUnicodeSource));
                WaitForCopy(fileUnicodeDest);

                Assert.AreEqual(CopyStatus.Success, fileUnicodeDest.CopyState.Status);
                Assert.AreEqual(fileUnicodeSource.Uri.AbsolutePath, fileUnicodeDest.CopyState.Source.AbsolutePath);
                Assert.AreEqual(data.Length, fileUnicodeDest.CopyState.TotalBytes);
                Assert.AreEqual(data.Length, fileUnicodeDest.CopyState.BytesCopied);
                Assert.AreEqual(copyId, fileUnicodeDest.CopyState.CopyId);
                Assert.IsTrue(fileUnicodeDest.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)));
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
0
        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;
            }
        }
Exemplo n.º 30
0
        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;
            }
        }
Exemplo n.º 31
0
        public void CloudFileDirectoryCreateDirectoryUsingPrefix()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            try
            {
                share.Create();
                CloudFileDirectory dir1 = share.GetRootDirectoryReference().GetDirectoryReference("Dir1");
                CloudFileDirectory dir2 = share.GetRootDirectoryReference().GetDirectoryReference("Dir1/Dir2");
                TestHelper.ExpectedException(
                    () => dir2.Create(),
                    "Try to create directory hierarchy by specifying prefix",
                    HttpStatusCode.NotFound);

                dir1.Create();
                dir2.Create();
            }
            finally
            {
                share.Delete();
            }
        }
        public void CloudFileShareExistsAPM()
        {
            CloudFileShare share  = GetRandomShareReference();
            CloudFileShare share2 = share.ServiceClient.GetShareReference(share.Name);

            using (AutoResetEvent waitHandle = new AutoResetEvent(false))
            {
                IAsyncResult result = share2.BeginExists(
                    ar => waitHandle.Set(),
                    null);
                waitHandle.WaitOne();
                Assert.IsFalse(share2.EndExists(result));

                share.Create();

                try
                {
                    result = share2.BeginExists(
                        ar => waitHandle.Set(),
                        null);
                    waitHandle.WaitOne();
                    Assert.IsTrue(share2.EndExists(result));
                    Assert.IsNotNull(share2.Properties.ETag);
                }
                finally
                {
                    share.Delete();
                }

                result = share2.BeginExists(
                    ar => waitHandle.Set(),
                    null);
                waitHandle.WaitOne();
                Assert.IsFalse(share2.EndExists(result));
            }
        }
        public void FileSeekTest()
        {
            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 fileStream = file.OpenRead();
                    fileStream.Seek(2048, 0);
                    byte[] buff    = new byte[100];
                    int    numRead = fileStream.Read(buff, 0, 100);
                    Assert.AreEqual(numRead, 0);
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        public void CloudFileShareSetMetadataTask()
        {
            CloudFileShare share = GetRandomShareReference();

            try
            {
                share.Create();

                CloudFileShare share2 = share.ServiceClient.GetShareReference(share.Name);
                share2.FetchAttributesAsync().Wait();
                Assert.AreEqual(0, share2.Metadata.Count);

                share.Metadata.Add("key1", "value1");
                share.SetMetadataAsync().Wait();

                share2.FetchAttributesAsync().Wait();
                Assert.AreEqual(1, share2.Metadata.Count);
                Assert.AreEqual("value1", share2.Metadata["key1"]);

                CloudFileShare share3 =
                    share.ServiceClient.ListSharesSegmentedAsync(
                        share.Name, ShareListingDetails.Metadata, null, null, null, null).Result.Results.First();
                Assert.AreEqual(1, share3.Metadata.Count);
                Assert.AreEqual("value1", share3.Metadata["key1"]);

                share.Metadata.Clear();
                share.SetMetadataAsync().Wait();

                share2.FetchAttributesAsync().Wait();
                Assert.AreEqual(0, share2.Metadata.Count);
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
 public Task DeleteShareAsync(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return share.DeleteAsync(accessCondition, options, operationContext, cancellationToken);
 }
 public Task DeleteShareAsync(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return TaskEx.FromResult(true);
 }
Exemplo n.º 37
0
        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);
                }
            }
        }
        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.AsInputStream(), 512, null);
                }

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    await file.WriteRangeAsync(memoryStream.AsInputStream(), 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().AsTask().Wait();
            }
        }
Exemplo n.º 39
0
 public Task<FileSharePermissions> GetSharePermissionsAsync(CloudFileShare share, AccessCondition accessCondition,
     FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return share.GetPermissionsAsync(accessCondition, options, operationContext, cancellationToken);
 }
Exemplo n.º 40
0
        public async Task FileWriteStreamFlushTestAsync()
        {
            byte[] buffer = GetRandomBuffer(512);

            CloudFileShare share = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                file.StreamWriteSizeInBytes = 1024;
                using (MemoryStream wholeFile = new MemoryStream())
                {
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true
                    };
                    OperationContext opContext = new OperationContext();
                    using (var fileStream = await file.OpenWriteAsync(4 * 512, null, options, opContext))
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            await fileStream.WriteAsync(buffer, 0, buffer.Length);

                            await wholeFile.WriteAsync(buffer, 0, buffer.Length);
                        }

#if NETCORE
                        // todo: Make some other better logic for this test to be reliable.
                        System.Threading.Thread.Sleep(500);
#endif

                        Assert.AreEqual(2, opContext.RequestResults.Count);

                        await fileStream.FlushAsync();

                        Assert.AreEqual(3, opContext.RequestResults.Count);

                        await fileStream.FlushAsync();

                        Assert.AreEqual(3, opContext.RequestResults.Count);

                        await fileStream.WriteAsync(buffer, 0, buffer.Length);

                        await wholeFile.WriteAsync(buffer, 0, buffer.Length);

                        Assert.AreEqual(3, opContext.RequestResults.Count);

                        await fileStream.CommitAsync();

                        Assert.AreEqual(5, opContext.RequestResults.Count);
                    }

                    Assert.AreEqual(5, opContext.RequestResults.Count);

                    using (MemoryOutputStream downloadedFile = new MemoryOutputStream())
                    {
                        await file.DownloadToStreamAsync(downloadedFile);

                        TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile.UnderlyingStream);
                    }
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
Exemplo n.º 41
0
        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));
        }
Exemplo n.º 42
0
        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 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);
                }
            }
        }
Exemplo n.º 44
0
 public void SetShareProperties(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
 {
     share.SetProperties(accessCondition, options, operationContext);
 }
Exemplo n.º 45
0
        public async Task FileWriteStreamBasicTestAsync()
        {
            byte[] buffer = GetRandomBuffer(6 * 512);

#if NETCORE
            MD5 hasher = MD5.Create();
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
#endif
            CloudFileShare share = GetRandomShareReference();
            share.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;

            try
            {
                await share.CreateAsync();

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

                using (MemoryStream wholeFile = new MemoryStream())
                {
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true,
                    };
                    using (var writeStream = await file.OpenWriteAsync(buffer.Length * 3, null, options, null))
                    {
                        Stream fileStream = writeStream;

                        for (int i = 0; i < 3; i++)
                        {
                            await fileStream.WriteAsync(buffer, 0, buffer.Length);

                            await wholeFile.WriteAsync(buffer, 0, buffer.Length);

                            Assert.AreEqual(wholeFile.Position, fileStream.Position);
#if !NETCORE
                            hasher.Append(buffer.AsBuffer());
#endif
                        }

                        await fileStream.FlushAsync();
                    }

#if NETCORE
                    string md5 = Convert.ToBase64String(hasher.ComputeHash(wholeFile.ToArray()));
#else
                    string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif
                    await file.FetchAttributesAsync();

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

                    using (MemoryOutputStream downloadedFile = new MemoryOutputStream())
                    {
                        await file.DownloadToStreamAsync(downloadedFile);

                        TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile.UnderlyingStream);
                    }

                    await TestHelper.ExpectedExceptionAsync <ArgumentException>(
                        async() => await file.OpenWriteAsync(null, null, options, null),
                        "OpenWrite with StoreFileContentMD5 on an existing file should fail");

                    using (var writeStream = await file.OpenWriteAsync(null))
                    {
                        Stream fileStream = writeStream;
                        fileStream.Seek(buffer.Length / 2, SeekOrigin.Begin);
                        wholeFile.Seek(buffer.Length / 2, SeekOrigin.Begin);

                        for (int i = 0; i < 2; i++)
                        {
                            fileStream.Write(buffer, 0, buffer.Length);
                            wholeFile.Write(buffer, 0, buffer.Length);
                            Assert.AreEqual(wholeFile.Position, fileStream.Position);
                        }

                        await fileStream.FlushAsync();
                    }

                    await file.FetchAttributesAsync();

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

                    using (MemoryOutputStream downloadedFile = new MemoryOutputStream())
                    {
                        options.DisableContentMD5Validation = true;
                        await file.DownloadToStreamAsync(downloadedFile, null, options, null);

                        TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile.UnderlyingStream);
                    }
                }
            }
            finally
            {
                share.DeleteAsync().Wait();
            }
        }
        public async Task CloudFileListSharesWithSnapshotAsync()
        {
            CloudFileShare share = GetRandomShareReference();
            await share.CreateAsync();

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

            CloudFileShare snapshot = await share.SnapshotAsync();

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

            CloudFileClient       client       = GenerateCloudFileClient();
            List <CloudFileShare> listedShares = new List <CloudFileShare>();
            FileContinuationToken token        = null;

            do
            {
                ShareResultSegment resultSegment = await client.ListSharesSegmentedAsync(share.Name, ShareListingDetails.All, null, token, null, null);

                token = resultSegment.ContinuationToken;

                foreach (CloudFileShare listResultShare in resultSegment.Results)
                {
                    listedShares.Add(listResultShare);
                }
            }while (token != null);

            int  count         = 0;
            bool originalFound = false;
            bool snapshotFound = false;

            foreach (CloudFileShare listShareItem in listedShares)
            {
                if (listShareItem.Name.Equals(share.Name) && !listShareItem.IsSnapshot && !originalFound)
                {
                    count++;
                    originalFound = true;
                    Assert.AreEqual(2, listShareItem.Metadata.Count);
                    Assert.AreEqual("value2", listShareItem.Metadata["key2"]);
                    Assert.AreEqual("value1", listShareItem.Metadata["key1"]);
                    Assert.AreEqual(share.StorageUri, listShareItem.StorageUri);
                }
                else if (listShareItem.Name.Equals(share.Name) &&
                         listShareItem.IsSnapshot && !snapshotFound)
                {
                    count++;
                    snapshotFound = true;
                    Assert.AreEqual(1, listShareItem.Metadata.Count);
                    Assert.AreEqual("value1", listShareItem.Metadata["key1"]);
                    Assert.AreEqual(snapshot.StorageUri, listShareItem.StorageUri);
                }
            }

            Assert.AreEqual(2, count);

            await snapshot.DeleteAsync();

            await share.DeleteAsync();
        }
Exemplo n.º 47
0
 public FileSharePermissions GetSharePermissions(CloudFileShare share, AccessCondition accessCondition = null,
     FileRequestOptions options = null, OperationContext operationContext = null)
 {
     return share.GetPermissions(accessCondition, options, operationContext);
 }
Exemplo n.º 48
0
        public async Task CloudFileWriteRangeAsync()
        {
            byte[] buffer = GetRandomBuffer(4 * 1024 * 1024);

            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, null);

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

                        int offset = buffer.Length - 1024;
                        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 void TestInitialize()
 {
     this.testShare = GetRandomShareReference();
     this.testShare.CreateIfNotExistsAsync().AsTask().Wait();
 }
Exemplo n.º 50
0
        public void CloudFileClientMaximumExecutionTimeoutShouldNotBeHonoredForStreams()
        {
            CloudFileClient fileClient = GenerateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference(Guid.NewGuid().ToString("N"));

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

            try
            {
                share.Create();

                fileClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(30);
                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file");
                file.StreamWriteSizeInBytes       = 1024 * 1024;
                file.StreamMinimumReadSizeInBytes = 1024 * 1024;

                using (CloudFileStream bos = file.OpenWrite(8 * 1024 * 1024))
                {
                    DateTime start = DateTime.Now;

                    for (int i = 0; i < 7; i++)
                    {
                        bos.Write(buffer, 0, buffer.Length);
                    }

                    // Sleep to ensure we are over the Max execution time when we do the last write
                    int msRemaining = (int)(fileClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;

                    if (msRemaining > 0)
                    {
                        Thread.Sleep(msRemaining);
                    }

                    bos.Write(buffer, 0, buffer.Length);
                }

                using (Stream bis = file.OpenRead())
                {
                    DateTime start = DateTime.Now;
                    int      total = 0;
                    while (total < 7 * 1024 * 1024)
                    {
                        total += bis.Read(buffer, 0, buffer.Length);
                    }

                    // Sleep to ensure we are over the Max execution time when we do the last read
                    int msRemaining = (int)(fileClient.DefaultRequestOptions.MaximumExecutionTime.Value - (DateTime.Now - start)).TotalMilliseconds;

                    if (msRemaining > 0)
                    {
                        Thread.Sleep(msRemaining);
                    }

                    while (true)
                    {
                        int count = bis.Read(buffer, 0, buffer.Length);
                        total += count;
                        if (count == 0)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                fileClient.DefaultRequestOptions.MaximumExecutionTime = null;
                share.DeleteIfExists();
            }
        }
        public async Task CloudFileWriteRangeAsync()
        {
            byte[]            buffer = GetRandomBuffer(4 * 1024 * 1024);
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();

            hasher.Append(buffer.AsBuffer());
            string contentMD5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());

            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.AsInputStream(), 0, null),
                        "Zero-length WriteRange should fail");

                    memoryStream.SetLength(4 * 1024 * 1024 + 1);
                    await TestHelper.ExpectedExceptionAsync <ArgumentOutOfRangeException>(
                        async() => await file.WriteRangeAsync(memoryStream.AsInputStream(), 0, null),
                        ">4MB 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.AsInputStream(), 512, null, null, null, opContext),
                            opContext,
                            "Writing out-of-range ranges should fail",
                            HttpStatusCode.RequestedRangeNotSatisfiable,
                            "InvalidFileRange");

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await file.WriteRangeAsync(memoryStream.AsInputStream(), 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.AsInputStream(), 0, contentMD5, null, null, opContext),
                            opContext,
                            "Invalid MD5 should fail with mismatch",
                            HttpStatusCode.BadRequest,
                            "Md5Mismatch");

                        memoryStream.Seek(offset, SeekOrigin.Begin);
                        await file.WriteRangeAsync(memoryStream.AsInputStream(), 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.AsInputStream(), 1024, null);

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

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

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

                        Assert.IsTrue(fileData.ToArray().SequenceEqual(resultingData.ToArray()));
                    }
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 52
0
 public void FetchShareAttributes(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
 {
     share.FetchAttributes(accessCondition, options, operationContext);
 }
 public Task CreateShareAsync(CloudFileShare share, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return TaskEx.FromResult(share);
 }
Exemplo n.º 54
0
 public void SetSharePermissions(CloudFileShare share, FileSharePermissions permissions,
     AccessCondition accessCondition = null,
     FileRequestOptions options = null, OperationContext operationContext = null)
 {
     share.SetPermissions(permissions, accessCondition, options, operationContext);
 }
 public void SetShareProperties(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 56
0
        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 Task CreateShareAsync(CloudFileShare share, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
 {
     return share.CreateAsync(options, operationContext, cancellationToken);
 }
Exemplo n.º 58
0
        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";
#if !ASPNET_K
                file.Properties.ContentEncoding = "gzip";
#endif
                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);
#if !ASPNET_K
                Assert.AreEqual("gzip", file2.Properties.ContentEncoding);
#endif
                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);

                CloudFile file4 = (CloudFile)results.First();
                Assert.AreEqual(file2.Properties.Length, file4.Properties.Length);
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }
 public Task FetchShareAttributesAsync(CloudFileShare share, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken token)
 {
     return share.FetchAttributesAsync(accessCondition, options, operationContext, token);
 }
Exemplo n.º 60
0
        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);
        }