private static async Task ListSharesSample(CloudFileClient cloudFileClient)
        {
            Console.WriteLine();
            // Keep a list of the file shares so you can compare this list 
            //   against the list of shares that we retrieve .
            List<string> fileShareNames = new List<string>();

            try
            {
                // Create 3 file shares.

                // Create the share name -- use a guid in the name so it's unique.
                // This will also be used as the container name for blob storage when copying the file to blob storage.
                string baseShareName = "demotest-" + System.Guid.NewGuid().ToString();


                for (int i = 0; i < 3; i++)
                {
                    // Set the name of the share, then add it to the generic list.
                    string shareName = baseShareName + "-0" + i;
                    fileShareNames.Add(shareName);

                    // Create the share with this name.
                    Console.WriteLine("Creating share with name {0}", shareName);
                    CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(shareName);
                    try
                    {
                        await cloudFileShare.CreateIfNotExistsAsync();
                        Console.WriteLine("    Share created successfully.");
                    }
                    catch (StorageException exStorage)
                    {
                        Common.WriteException(exStorage);
                        Console.WriteLine(
                            "Please make sure your storage account has storage file endpoint enabled and specified correctly in the app.config - then restart the sample.");
                        Console.WriteLine("Press any key to exit");
                        Console.ReadLine();
                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("    Exception thrown creating share.");
                        Common.WriteException(ex);
                        throw;
                    }
                }

                Console.WriteLine(string.Empty);
                Console.WriteLine("List of shares in the storage account:");

                // List the file shares for this storage account 
                IEnumerable<CloudFileShare> cloudShareList = cloudFileClient.ListShares();
                try
                {
                    foreach (CloudFileShare cloudShare in cloudShareList)
                    {
                        Console.WriteLine("Cloud Share name = {0}", cloudShare.Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("    Exception thrown listing shares.");
                    Common.WriteException(ex);
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown. Message = {0}{1}    Strack Trace = {2}", ex.Message,
                    Environment.NewLine, ex.StackTrace);
            }
            finally
            {
                // If it created the file shares, remove them (cleanup).
                if (fileShareNames != null && cloudFileClient != null)
                {
                    // Now clean up after yourself, using the list of shares that you created in case there were other shares in the account.
                    foreach (string fileShareName in fileShareNames)
                    {
                        CloudFileShare cloudFileShare = cloudFileClient.GetShareReference(fileShareName);
                        cloudFileShare.DeleteIfExists();
                    }
                }
            }
            Console.WriteLine();
        }
 public async Task CloudFileClientWithUppercaseAccountNameAsync()
 {
     StorageCredentials credentials = new StorageCredentials(TestBase.StorageCredentials.AccountName.ToUpper(), Convert.ToBase64String(TestBase.StorageCredentials.ExportKey()));
     Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.FileServiceEndpoint);
     CloudFileClient fileClient = new CloudFileClient(baseAddressUri, TestBase.StorageCredentials);
     CloudFileShare share = fileClient.GetShareReference("share");
     await share.ExistsAsync();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare" /> class.
 /// </summary>
 /// <param name="properties">The properties.</param>
 /// <param name="metadata">The metadata.</param>
 /// <param name="shareName">The share name.</param>
 /// <param name="serviceClient">The client to be used.</param>
 internal CloudFileShare(FileShareProperties properties, IDictionary<string, string> metadata, string shareName, CloudFileClient serviceClient)
 {
     this.StorageUri = NavigationHelper.AppendPathToUri(serviceClient.StorageUri, shareName);
     this.ServiceClient = serviceClient;
     this.Name = shareName;
     this.Metadata = metadata;
     this.Properties = properties;
 }
 public void CloudFileClientWithUppercaseAccountName()
 {
     StorageCredentials credentials = new StorageCredentials(TestBase.StorageCredentials.AccountName.ToUpper(), TestBase.StorageCredentials.ExportKey());
     Uri baseAddressUri = new Uri(TestBase.TargetTenantConfig.FileServiceEndpoint);
     CloudFileClient fileClient = new CloudFileClient(baseAddressUri, TestBase.StorageCredentials);
     CloudFileShare share = fileClient.GetShareReference("share");
     share.Exists();
 }
Exemplo n.º 5
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.º 6
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.º 8
0
        public void CloudFileClientListSharesSegmented()
        {
            AssertSecondaryEndpoint();

            string          name       = GetRandomShareName();
            List <string>   shareNames = new List <string>();
            CloudFileClient fileClient = GenerateCloudFileClient();

            for (int i = 0; i < 3; i++)
            {
                string shareName = name + i.ToString();
                shareNames.Add(shareName);
                fileClient.GetShareReference(shareName).Create();
            }

            List <string>         listedShareNames = new List <string>();
            FileContinuationToken token            = null;

            do
            {
                ShareResultSegment resultSegment = fileClient.ListSharesSegmented(token);
                token = resultSegment.ContinuationToken;

                foreach (CloudFileShare share in resultSegment.Results)
                {
                    Assert.IsTrue(fileClient.GetShareReference(share.Name).StorageUri.Equals(share.StorageUri));
                    listedShareNames.Add(share.Name);
                }
            }while (token != null);

            foreach (string shareName in listedShareNames)
            {
                if (shareNames.Remove(shareName))
                {
                    fileClient.GetShareReference(shareName).Delete();
                }
            }

            Assert.AreEqual(0, shareNames.Count);
        }
Exemplo n.º 9
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().Wait();
            }
        }
Exemplo n.º 10
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.AsInputStream());

                        Assert.Fail();
                    }
                    catch (AggregateException ex)
                    {
                        Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.InnerException.Message).ExceptionInfo.Message);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                }
            }
            finally
            {
                fileClient.DefaultRequestOptions.MaximumExecutionTime = null;
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 11
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();
            }
        }
        public async Task CloudFileClientListSharesSegmentedWithPrefixAsync()
        {
            string          name       = GetRandomShareName();
            List <string>   shareNames = new List <string>();
            CloudFileClient fileClient = GenerateCloudFileClient();

            for (int i = 0; i < 3; i++)
            {
                string shareName = name + i.ToString();
                shareNames.Add(shareName);
                await fileClient.GetShareReference(shareName).CreateAsync();
            }

            List <string>         listedShareNames = new List <string>();
            FileContinuationToken token            = null;

            do
            {
                ShareResultSegment resultSegment = await fileClient.ListSharesSegmentedAsync(name, ShareListingDetails.None, 1, token, null, null);

                token = resultSegment.ContinuationToken;

                int count = 0;
                foreach (CloudFileShare share in resultSegment.Results)
                {
                    count++;
                    listedShareNames.Add(share.Name);
                }
                Assert.IsTrue(count <= 1);
            }while (token != null);

            Assert.AreEqual(shareNames.Count, listedShareNames.Count);
            foreach (string shareName in listedShareNames)
            {
                Assert.IsTrue(shareNames.Remove(shareName));
                await fileClient.GetShareReference(shareName).DeleteAsync();
            }
        }
Exemplo n.º 13
0
        public void CloudFileClientListSharesSegmentedTask()
        {
            string          name       = GetRandomShareName();
            List <string>   shareNames = new List <string>();
            CloudFileClient fileClient = GenerateCloudFileClient();

            for (int i = 0; i < 3; i++)
            {
                string shareName = name + i.ToString();
                shareNames.Add(shareName);
                fileClient.GetShareReference(shareName).CreateAsync().Wait();
            }

            List <string>         listedShareNames = new List <string>();
            FileContinuationToken token            = null;

            do
            {
                ShareResultSegment resultSegment = fileClient.ListSharesSegmentedAsync(token).Result;
                token = resultSegment.ContinuationToken;

                foreach (CloudFileShare share in resultSegment.Results)
                {
                    listedShareNames.Add(share.Name);
                }
            }while (token != null);

            foreach (string shareName in listedShareNames)
            {
                if (shareNames.Remove(shareName))
                {
                    fileClient.GetShareReference(shareName).DeleteAsync().Wait();
                }
            }

            Assert.AreEqual(0, shareNames.Count);
        }
Exemplo n.º 14
0
        internal static FileRequestOptions ApplyDefaults(FileRequestOptions options, CloudFileClient serviceClient, bool applyExpiry = true)
        {
            FileRequestOptions modifiedOptions = new FileRequestOptions(options);

            modifiedOptions.RetryPolicy  = modifiedOptions.RetryPolicy ?? serviceClient.DefaultRequestOptions.RetryPolicy;
            modifiedOptions.LocationMode = (modifiedOptions.LocationMode
                                            ?? serviceClient.DefaultRequestOptions.LocationMode)
                                           ?? RetryPolicies.LocationMode.PrimaryOnly;
            modifiedOptions.ServerTimeout                = modifiedOptions.ServerTimeout ?? serviceClient.DefaultRequestOptions.ServerTimeout;
            modifiedOptions.MaximumExecutionTime         = modifiedOptions.MaximumExecutionTime ?? serviceClient.DefaultRequestOptions.MaximumExecutionTime;
            modifiedOptions.ParallelOperationThreadCount = (modifiedOptions.ParallelOperationThreadCount
                                                            ?? serviceClient.DefaultRequestOptions.ParallelOperationThreadCount)
                                                           ?? 1;

            if (applyExpiry && !modifiedOptions.OperationExpiryTime.HasValue && modifiedOptions.MaximumExecutionTime.HasValue)
            {
                modifiedOptions.OperationExpiryTime = DateTime.Now + modifiedOptions.MaximumExecutionTime.Value;
            }

#if WINDOWS_PHONE
            modifiedOptions.DisableContentMD5Validation = true;
            modifiedOptions.StoreFileContentMD5         = false;
            modifiedOptions.UseTransactionalMD5         = false;
#else
            modifiedOptions.DisableContentMD5Validation = (modifiedOptions.DisableContentMD5Validation
                                                           ?? serviceClient.DefaultRequestOptions.DisableContentMD5Validation)
                                                          ?? false;
            modifiedOptions.StoreFileContentMD5 = (modifiedOptions.StoreFileContentMD5
                                                   ?? serviceClient.DefaultRequestOptions.StoreFileContentMD5)
                                                  ?? false;
            modifiedOptions.UseTransactionalMD5 = (modifiedOptions.UseTransactionalMD5
                                                   ?? serviceClient.DefaultRequestOptions.UseTransactionalMD5)
                                                  ?? false;
#endif

            return(modifiedOptions);
        }
Exemplo n.º 15
0
        public void CloudFileClientListSharesWithPrefixSegmented2()
        {
            string          name       = GetRandomShareName();
            List <string>   shareNames = new List <string>();
            CloudFileClient fileClient = GenerateCloudFileClient();

            for (int i = 0; i < 3; i++)
            {
                string shareName = name + i.ToString();
                shareNames.Add(shareName);
                fileClient.GetShareReference(shareName).Create();
            }

            List <string>         listedShareNames = new List <string>();
            FileContinuationToken token            = null;

            do
            {
                ShareResultSegment resultSegment = fileClient.ListSharesSegmented(name, token);
                token = resultSegment.ContinuationToken;

                int count = 0;
                foreach (CloudFileShare share in resultSegment.Results)
                {
                    count++;
                    listedShareNames.Add(share.Name);
                }
            }while (token != null);

            Assert.AreEqual(shareNames.Count, listedShareNames.Count);
            foreach (string shareName in listedShareNames)
            {
                Assert.IsTrue(shareNames.Remove(shareName));
                fileClient.GetShareReference(shareName).Delete();
            }
            Assert.AreEqual(0, shareNames.Count);
        }
Exemplo n.º 16
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();
            }
        }
Exemplo n.º 17
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.º 18
0
        public void CloudFileTestValidCorsRules()
        {
            CorsRule ruleMinRequired = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods = CorsHttpMethods.Get
            };

            CorsRule ruleBasic = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com", "www.bc.com"
                },
                AllowedMethods  = CorsHttpMethods.Get | CorsHttpMethods.Put,
                MaxAgeInSeconds = 500,
                ExposedHeaders  =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-source*",
                    "x-ms-meta-abc",
                    "x-ms-meta-bcd"
                },
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-target*",
                    "x-ms-meta-xyz",
                    "x-ms-meta-foo"
                }
            };

            CorsRule ruleAllMethods = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods =
                    CorsHttpMethods.Put | CorsHttpMethods.Trace
                    | CorsHttpMethods.Connect | CorsHttpMethods.Delete
                    | CorsHttpMethods.Get | CorsHttpMethods.Head
                    | CorsHttpMethods.Options | CorsHttpMethods.Post
                    | CorsHttpMethods.Merge
            };

            CorsRule ruleSingleExposedHeader = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                ExposedHeaders = new List <string>()
                {
                    "x-ms-meta-bcd"
                },
            };

            CorsRule ruleSingleExposedPrefixHeader = new CorsRule()
            {
                AllowedOrigins =
                    new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                ExposedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*"
                },
            };

            CorsRule ruleSingleAllowedHeader = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders = new List <string>()
                {
                    "x-ms-meta-xyz",
                },
            };

            CorsRule ruleSingleAllowedPrefixHeader = new CorsRule()
            {
                AllowedOrigins =
                    new List <string>()
                {
                    "www.ab.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-target*"
                },
            };

            CorsRule ruleAllowAll = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "*"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders = new List <string>()
                {
                    "*"
                },
                ExposedHeaders = new List <string>()
                {
                    "*"
                }
            };

            CloudFileClient client = GenerateCloudFileClient();

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleBasic
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleMinRequired
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleAllMethods
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleSingleExposedHeader
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleSingleExposedPrefixHeader
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleSingleAllowedHeader
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleSingleAllowedPrefixHeader
            });

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleAllowAll
            });

            // Empty rule set should delete all rules
            this.TestCorsRules(client, new List <CorsRule>()
            {
            });

            // Test duplicate rules
            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleBasic, ruleBasic
            });

            // Test max number of  rules (five)
            this.TestCorsRules(
                client,
                new List <CorsRule>()
            {
                ruleBasic,
                ruleMinRequired,
                ruleAllMethods,
                ruleSingleExposedHeader,
                ruleSingleExposedPrefixHeader
            });


            // Test max number of rules + 1 (six)
            TestHelper.ExpectedException(
                () =>
                this.TestCorsRules(
                    client,
                    new List <CorsRule>()
            {
                ruleBasic,
                ruleMinRequired,
                ruleAllMethods,
                ruleSingleExposedHeader,
                ruleSingleExposedPrefixHeader,
                ruleSingleAllowedHeader
            }),
                "Services are limited to a maximum of five CORS rules.",
                HttpStatusCode.BadRequest,
                "InvalidXmlDocument");
        }
 internal static FileRequestOptions ApplyDefaults(FileRequestOptions options, CloudFileClient serviceClient, bool applyExpiry = true)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 20
0
        internal static FileRequestOptions ApplyDefaults(FileRequestOptions options, CloudFileClient serviceClient, bool applyExpiry = true)
        {
            FileRequestOptions modifiedOptions = new FileRequestOptions(options);

            modifiedOptions.RetryPolicy =
                modifiedOptions.RetryPolicy
                ?? serviceClient.DefaultRequestOptions.RetryPolicy
                ?? BaseDefaultRequestOptions.RetryPolicy;

            modifiedOptions.LocationMode =
                modifiedOptions.LocationMode
                ?? serviceClient.DefaultRequestOptions.LocationMode
                ?? BaseDefaultRequestOptions.LocationMode;

#if !(WINDOWS_RT || ASPNET_K || PORTABLE)
            modifiedOptions.RequireEncryption =
                modifiedOptions.RequireEncryption
                ?? serviceClient.DefaultRequestOptions.RequireEncryption
                ?? BaseDefaultRequestOptions.RequireEncryption;
#endif

            modifiedOptions.ServerTimeout =
                modifiedOptions.ServerTimeout
                ?? serviceClient.DefaultRequestOptions.ServerTimeout
                ?? BaseDefaultRequestOptions.ServerTimeout;

            modifiedOptions.MaximumExecutionTime =
                modifiedOptions.MaximumExecutionTime
                ?? serviceClient.DefaultRequestOptions.MaximumExecutionTime
                ?? BaseDefaultRequestOptions.MaximumExecutionTime;

            modifiedOptions.ParallelOperationThreadCount =
                modifiedOptions.ParallelOperationThreadCount
                ?? serviceClient.DefaultRequestOptions.ParallelOperationThreadCount
                ?? BaseDefaultRequestOptions.ParallelOperationThreadCount;

            if (applyExpiry && !modifiedOptions.OperationExpiryTime.HasValue && modifiedOptions.MaximumExecutionTime.HasValue)
            {
                modifiedOptions.OperationExpiryTime = DateTime.Now + modifiedOptions.MaximumExecutionTime.Value;
            }

#if WINDOWS_PHONE && WINDOWS_DESKTOP
            modifiedOptions.DisableContentMD5Validation = BaseDefaultRequestOptions.DisableContentMD5Validation;
            modifiedOptions.StoreFileContentMD5         = BaseDefaultRequestOptions.StoreFileContentMD5;
            modifiedOptions.UseTransactionalMD5         = BaseDefaultRequestOptions.UseTransactionalMD5;
#else
            modifiedOptions.DisableContentMD5Validation =
                modifiedOptions.DisableContentMD5Validation
                ?? serviceClient.DefaultRequestOptions.DisableContentMD5Validation
                ?? BaseDefaultRequestOptions.DisableContentMD5Validation;

            modifiedOptions.StoreFileContentMD5 =
                modifiedOptions.StoreFileContentMD5
                ?? serviceClient.DefaultRequestOptions.StoreFileContentMD5
                ?? BaseDefaultRequestOptions.StoreFileContentMD5;

            modifiedOptions.UseTransactionalMD5 =
                modifiedOptions.UseTransactionalMD5
                ?? serviceClient.DefaultRequestOptions.UseTransactionalMD5
                ?? BaseDefaultRequestOptions.UseTransactionalMD5;
#endif

            return(modifiedOptions);
        }
Exemplo n.º 21
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.º 22
0
 private static CloudFileClient GetCloudFileClient()
 {
     if (Util.fileClient == null)
     {
         Util.fileClient = GetStorageAccount().CreateCloudFileClient();
     }
     
     return Util.fileClient;
 }
Exemplo n.º 23
0
        public void CloudFileDirectoryListFilesAndDirectoriesAPM()
        {
            CloudFileClient client = GenerateCloudFileClient();
            string          name   = GetRandomShareName();
            CloudFileShare  share  = client.GetShareReference(name);

            try
            {
                share.Create();
                if (CloudFileDirectorySetup(share))
                {
                    CloudFileDirectory topDir1 = share.GetRootDirectoryReference().GetDirectoryReference("TopDir1");
                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        FileContinuationToken token       = null;
                        List <IListFileItem>  simpleList1 = new List <IListFileItem>();
                        do
                        {
                            IAsyncResult result = topDir1.BeginListFilesAndDirectoriesSegmented(
                                null,
                                null,
                                null,
                                null,
                                ar => waitHandle.Set(),
                                null);
                            waitHandle.WaitOne();
                            FileResultSegment segment = topDir1.EndListFilesAndDirectoriesSegmented(result);
                            simpleList1.AddRange(segment.Results);
                            token = segment.ContinuationToken;
                        }while (token != null);

                        ////Check if for 3 because if there were more than 3, the previous assert would have failed.
                        ////So the only thing we need to make sure is that it is not less than 3.
                        Assert.IsTrue(simpleList1.Count == 3);

                        IListFileItem item11 = simpleList1.ElementAt(0);
                        Assert.IsTrue(item11.Uri.Equals(share.Uri + "/TopDir1/File1"));
                        Assert.AreEqual("File1", ((CloudFile)item11).Name);

                        IListFileItem item12 = simpleList1.ElementAt(1);
                        Assert.IsTrue(item12.Uri.Equals(share.Uri + "/TopDir1/MidDir1"));
                        Assert.AreEqual("MidDir1", ((CloudFileDirectory)item12).Name);

                        IListFileItem item13 = simpleList1.ElementAt(2);
                        Assert.IsTrue(item13.Uri.Equals(share.Uri + "/TopDir1/MidDir2"));
                        Assert.AreEqual("MidDir2", ((CloudFileDirectory)item13).Name);
                        CloudFileDirectory midDir2 = (CloudFileDirectory)item13;

                        List <IListFileItem> simpleList2 = new List <IListFileItem>();
                        do
                        {
                            IAsyncResult result = midDir2.BeginListFilesAndDirectoriesSegmented(
                                token,
                                ar => waitHandle.Set(),
                                null);
                            waitHandle.WaitOne();
                            FileResultSegment segment = midDir2.EndListFilesAndDirectoriesSegmented(result);
                            simpleList2.AddRange(segment.Results);
                            token = segment.ContinuationToken;
                        }while (token != null);
                        Assert.IsTrue(simpleList2.Count == 2);

                        IListFileItem item21 = simpleList2.ElementAt(0);
                        Assert.IsTrue(item21.Uri.Equals(share.Uri + "/TopDir1/MidDir2/EndDir1"));
                        Assert.AreEqual("EndDir1", ((CloudFileDirectory)item21).Name);

                        IListFileItem item22 = simpleList2.ElementAt(1);
                        Assert.IsTrue(item22.Uri.Equals(share.Uri + "/TopDir1/MidDir2/EndDir2"));
                        Assert.AreEqual("EndDir2", ((CloudFileDirectory)item22).Name);
                    }
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        /// <summary>
        /// Manage file properties
        /// </summary>
        /// <param name="cloudFileClient"></param>
        /// <returns></returns>
        private static async Task FilePropertiesSample(CloudFileClient cloudFileClient)
        {
            Console.WriteLine();
            // Create the share name -- use a guid in the name so it's unique.
            string shareName = "demotest-" + Guid.NewGuid();
            CloudFileShare share = cloudFileClient.GetShareReference(shareName);
            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await share.CreateIfNotExistsAsync();

                // Create directory
                Console.WriteLine("Create directory");
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                await rootDirectory.CreateIfNotExistsAsync();

                CloudFile file = rootDirectory.GetFileReference("demofile");

                // Set file properties
                file.Properties.ContentType = "plain/text";
                file.Properties.ContentEncoding = "UTF-8";
                file.Properties.ContentLanguage = "en";

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);
                
                // Fetch file attributes
                // in this case this call is not need but is included for demo purposes
                await file.FetchAttributesAsync();
                Console.WriteLine("Get file properties:");
                Console.WriteLine("    ETag: {0}", file.Properties.ETag);
                Console.WriteLine("    Content type: {0}", file.Properties.ContentType);
                Console.WriteLine("    Cache control: {0}", file.Properties.CacheControl);
                Console.WriteLine("    Content encoding: {0}", file.Properties.ContentEncoding);
                Console.WriteLine("    Content language: {0}", file.Properties.ContentLanguage);
                Console.WriteLine("    Content disposition: {0}", file.Properties.ContentDisposition);
                Console.WriteLine("    Content MD5: {0}", file.Properties.ContentMD5);
                Console.WriteLine("    Length: {0}", file.Properties.Length);
            }
            catch (StorageException exStorage)
            {
                Common.WriteException(exStorage);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                share.DeleteIfExists();
            }
            Console.WriteLine();
        }
Exemplo n.º 25
0
        public async Task CloudFileClientMaximumExecutionTimeoutShouldNotBeHonoredForStreamsAsync()
        {
            CloudFileClient    fileClient    = GenerateCloudFileClient();
            CloudFileShare     share         = fileClient.GetShareReference(Guid.NewGuid().ToString("N"));
            CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();

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

            try
            {
                await share.CreateAsync();

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

                using (ICloudFileStream fileStream = await file.OpenWriteAsync(8 * 1024 * 1024))
                {
                    Stream fos = fileStream.AsStreamForWrite();

                    DateTime start = DateTime.Now;
                    for (int i = 0; i < 7; i++)
                    {
                        await fos.WriteAsync(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)
                    {
                        await Task.Delay(msRemaining);
                    }

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

                    await fileStream.CommitAsync();
                }

                using (IRandomAccessStreamWithContentType fileStream = await file.OpenReadAsync())
                {
                    Stream fis = fileStream.AsStreamForRead();

                    DateTime start = DateTime.Now;
                    int      total = 0;
                    while (total < 7 * 1024 * 1024)
                    {
                        total += await fis.ReadAsync(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)
                    {
                        await Task.Delay(msRemaining);
                    }

                    while (true)
                    {
                        int count = await fis.ReadAsync(buffer, 0, buffer.Length);

                        total += count;
                        if (count == 0)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                fileClient.DefaultRequestOptions.MaximumExecutionTime = null;
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemplo n.º 26
0
        // TODO: extract the common pattern(Upload and Download)
        private static void UploadFiles(Dictionary<string, DataSyncFileInfo> localOnly, CloudFileClient fileClient)
        {
            List<Task> waitTasks = new List<Task>();
            foreach (var file in localOnly)
            {
                var path = file.Key.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (path.Length < 2)
                {
                    throw new Exception("share is needed, so you should create a flod in local.");
                }
                string shareString = path[0];
                fileClient.GetShareReference(shareString).CreateIfNotExists();
                string dirString = path[0] + "/";
                for (int i = 1; i < path.Length - 1; i++)
                {
                    dirString += path[i] + "/";
                    CloudFileDirectory fileDir = new CloudFileDirectory(
                    new Uri(fileClient.BaseUri.AbsoluteUri + dirString), fileClient.Credentials);
                    fileDir.CreateIfNotExists();
                }

                var uploadTask = Task.Run(() =>
                {
                    Console.WriteLine($"upload {file.Key} ...");
                    CloudFile cloudFile = new CloudFile(new Uri(fileClient.BaseUri.AbsoluteUri + file.Key.Substring(1)), fileClient.Credentials);
                    cloudFile.UploadFromFile(file.Value.LocalFile.FullName);
                    Console.WriteLine($"{file.Key} is uploaded!");
                });

                waitTasks.Add(uploadTask);
                // TODO: config the number of running task
                while (waitTasks.Count(task =>
                task.Status == TaskStatus.Running || task.Status == TaskStatus.WaitingToRun) >= 8)
                {
                    Task.WaitAny(waitTasks.ToArray());
                }
            }

            Task.WaitAll(waitTasks.ToArray());
        }
Exemplo n.º 27
0
 private static void ListCloudFiles(CloudFileClient fileClient)
 {
     var shares = fileClient.ListShares();
     foreach (var share in shares)
     {
         var rootDir = share.GetRootDirectoryReference();
         ListCloudFilesByDir(rootDir);
     }
 }
Exemplo n.º 28
0
        private static void HandleLocalFiles(CloudFileClient fileClient)
        {
            if (localOnly.Count == 0)
            {
                Console.WriteLine("No file is only in the localhost.");
                return;
            }

            Console.WriteLine($"There are {localOnly.Count} files in the localhost, do you want to upload them? Y/N [N]");
            string upload = Console.ReadLine();
            bool isUpload = false;
            if (upload == "Y")
            {
                isUpload = true;
            }

            if (isUpload)
            {
                UploadFiles(localOnly, fileClient);
            }
            else
            {
                Console.WriteLine($"There are {localOnly.Count} files in the localhost, do you want to delete them? Y/N [N]");
                string delete = Console.ReadLine();
                bool isDelete = false;
                if (delete == "Y")
                {
                    isDelete = true;
                }

                if (isDelete)
                {
                    DeleteLocalFiles(localOnly);
                }
            }
        }
Exemplo n.º 29
0
        private static void HandleConflictFiles(CloudFileClient fileClient)
        {
            if (conflictFiles.Count == 0)
            {
                Console.WriteLine("No file is conflicted.");
                return;
            }

            Console.WriteLine($"There are {conflictFiles.Count} files are conflicted, do you want?");
            Console.WriteLine("1. upload");
            Console.WriteLine("2. download");
            int option = int.Parse(Console.ReadLine());
            switch (option)
            {
                case 1:
                    UploadFiles(conflictFiles, fileClient);
                    break;
                case 2:
                    DownloadFiles(conflictFiles);
                    break;
                default:
                    break;
            }
        }
Exemplo n.º 30
0
 public static void MyClassInitialize(TestContext testContext)
 {
     client          = GenerateCloudFileClient();
     startProperties = client.GetServiceProperties();
 }
Exemplo n.º 31
0
        public void CloudFileTestCorsMaxHeaders()
        {
            CorsRule ruleManyHeaders = new CorsRule()
            {
                AllowedOrigins = new List <string>()
                {
                    "www.xyz.com"
                },
                AllowedMethods = CorsHttpMethods.Get,
                AllowedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-target*",
                    "x-ms-meta-other*"
                },
                ExposedHeaders =
                    new List <string>()
                {
                    "x-ms-meta-data*",
                    "x-ms-meta-source*"
                }
            };

            // Add maximum number of non-prefixed headers
            for (int i = 0; i < 64; i++)
            {
                ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-" + i);
                ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-" + i);
            }

            CloudFileClient client = GenerateCloudFileClient();

            this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleManyHeaders
            });

            // Test with too many Exposed Headers (65)
            ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-toomany");

            TestHelper.ExpectedException(
                () => this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                "A maximum of 64 literal exposed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.ExposedHeaders.Remove("x-ms-meta-toomany");

            // Test with too many Allowed Headers (65)
            ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-toomany");

            TestHelper.ExpectedException(
                () => this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                "A maximum of 64 literal allowed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.AllowedHeaders.Remove("x-ms-meta-toomany");

            // Test with too many Exposed Prefixed Headers (three)
            ruleManyHeaders.ExposedHeaders.Add("x-ms-meta-toomany*");

            TestHelper.ExpectedException(
                () => this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                "A maximum of two prefixed exposed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.ExposedHeaders.Remove("x-ms-meta-toomany*");

            // Test with too many Allowed Prefixed Headers (three)
            ruleManyHeaders.AllowedHeaders.Add("x-ms-meta-toomany*");

            TestHelper.ExpectedException(
                () => this.TestCorsRules(client, new List <CorsRule>()
            {
                ruleManyHeaders
            }),
                "A maximum of two prefixed allowed headers are allowed.",
                HttpStatusCode.BadRequest,
                "InvalidXmlNodeValue");

            ruleManyHeaders.AllowedHeaders.Remove("x-ms-meta-toomany*");
        }
 public static void MyClassInitialize(TestContext testContext)
 {
     client = GenerateCloudFileClient();
     startProperties = client.GetServiceProperties();
 }
        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();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare" /> class.
 /// </summary>
 /// <param name="shareName">The share name.</param>
 /// <param name="serviceClient">A client object that specifies the endpoint for the File service.</param>
 internal CloudFileShare(string shareName, CloudFileClient serviceClient)
     : this(new FileShareProperties(), new Dictionary<string, string>(), shareName, serviceClient)
 {
 }
Exemplo n.º 35
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();
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CloudFile"/> class.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <param name="serviceClient">The service client.</param>
        internal CloudFile(CloudFileAttributes attributes, CloudFileClient serviceClient)
        {
            this.attributes = attributes;
            this.ServiceClient = serviceClient;

            this.ParseQueryAndVerify(this.StorageUri, this.ServiceClient.Credentials);
        }
        /// <summary>
        /// Get directory properties
        /// </summary>
        /// <param name="cloudFileClient"></param>
        /// <returns></returns>
        private static async Task DirectoryPropertiesSample(CloudFileClient cloudFileClient)
        {
            Console.WriteLine();
            // Create the share name -- use a guid in the name so it's unique.
            string shareName = "demotest-" + Guid.NewGuid();
            CloudFileShare share = cloudFileClient.GetShareReference(shareName);
            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await share.CreateIfNotExistsAsync();

                // Create directory
                Console.WriteLine("Create directory");
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                await rootDirectory.CreateIfNotExistsAsync();
                
                // Fetch directory attributes
                // in this case this call is not need but is included for demo purposes
                await rootDirectory.FetchAttributesAsync();
                Console.WriteLine("Get directory properties:");
                Console.WriteLine("    ETag: {0}", rootDirectory.Properties.ETag);
                Console.WriteLine("    Last modified: {0}", rootDirectory.Properties.LastModified);
            }
            catch (StorageException exStorage)
            {
                Common.WriteException(exStorage);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                share.DeleteIfExists();
            }
            Console.WriteLine();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare" /> class.
 /// </summary>
 /// <param name="shareName">The share name.</param>
 /// <param name="snapshotTime">A <see cref="DateTimeOffset"/> specifying the snapshot timestamp, if the share is a snapshot.</param>
 /// <param name="serviceClient">A client object that specifies the endpoint for the File service.</param>
 internal CloudFileShare(string shareName, DateTimeOffset?snapshotTime, CloudFileClient serviceClient)
     : this(new FileShareProperties(), new Dictionary <string, string>(), shareName, snapshotTime, serviceClient)
 {
 }
Exemplo n.º 39
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();
        }
 internal CloudFile(CloudFileAttributes attributes, CloudFileClient serviceClient)
 {
     throw new System.NotImplementedException();
 }
        private void TestCorsRules(CloudFileClient client, IList<CorsRule> corsProps)
        {
            props.Cors.CorsRules.Clear();

            foreach (CorsRule rule in corsProps)
            {
                props.Cors.CorsRules.Add(rule);
            }

            client.SetServiceProperties(props);
            TestHelper.AssertFileServicePropertiesAreEqual(props, client.GetServiceProperties());
        }
 internal CloudFileShare(string shareName, DateTimeOffset?snapshotTime, CloudFileClient serviceClient)
     : this(new FileShareProperties(), (IDictionary <string, string>) new Dictionary <string, string>(), shareName, snapshotTime, serviceClient)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// Query the Cross-Origin Resource Sharing (CORS) rules for the File service
        /// </summary>
        /// <param name="fileClient"></param>
        private static async Task CorsSample(CloudFileClient fileClient)
        {
            Console.WriteLine();

            // Get service properties
            Console.WriteLine("Get service properties");
            FileServiceProperties originalProperties = await fileClient.GetServicePropertiesAsync();
            try
            {
                // Add CORS rule
                Console.WriteLine("Add CORS rule");

                CorsRule corsRule = new CorsRule
                {
                    AllowedHeaders = new List<string> { "*" },
                    AllowedMethods = CorsHttpMethods.Get,
                    AllowedOrigins = new List<string> { "*" },
                    ExposedHeaders = new List<string> { "*" },
                    MaxAgeInSeconds = 3600
                };

                FileServiceProperties serviceProperties = await fileClient.GetServicePropertiesAsync();
                serviceProperties.Cors.CorsRules.Add(corsRule);
                await fileClient.SetServicePropertiesAsync(serviceProperties);
            }
            finally
            {
                // Revert back to original service properties
                Console.WriteLine("Revert back to original service properties");
                await fileClient.SetServicePropertiesAsync(originalProperties);
            }
            Console.WriteLine();
        }
 internal CloudFileShare(FileShareProperties properties, IDictionary <string, string> metadata, string shareName, DateTimeOffset?snapshotTime, CloudFileClient serviceClient)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare" /> class.
 /// </summary>
 /// <param name="shareName">The share name.</param>
 /// <param name="serviceClient">A client object that specifies the endpoint for the File service.</param>
 internal CloudFileShare(string shareName, CloudFileClient serviceClient)
     : this(new FileShareProperties(), new Dictionary <string, string>(), shareName, serviceClient)
 {
 }
Exemplo n.º 46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFileShare" /> class.
 /// </summary>
 /// <param name="properties">The properties.</param>
 /// <param name="metadata">The metadata.</param>
 /// <param name="shareName">The share name.</param>
 /// <param name="serviceClient">The client to be used.</param>
 internal CloudFileShare(FileShareProperties properties, IDictionary <string, string> metadata, string shareName, CloudFileClient serviceClient)
 {
     this.StorageUri    = NavigationHelper.AppendPathToUri(serviceClient.StorageUri, shareName);
     this.ServiceClient = serviceClient;
     this.Name          = shareName;
     this.Metadata      = metadata;
     this.Properties    = properties;
 }
Exemplo n.º 47
0
        public void FileWriteStreamBasicTestAPM()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024 * 1024);

            MD5             hasher     = MD5.Create();
            CloudFileClient fileClient = GenerateCloudFileClient();

            fileClient.DefaultRequestOptions.ParallelOperationThreadCount = 4;
            string         name  = GetRandomShareName();
            CloudFileShare share = fileClient.GetShareReference(name);

            try
            {
                share.Create();

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

                using (MemoryStream wholeFile = new MemoryStream())
                {
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true,
                    };

                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        IAsyncResult result = file.BeginOpenWrite(fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value * 2 * buffer.Length, null, options, null,
                                                                  ar => waitHandle.Set(),
                                                                  null);
                        waitHandle.WaitOne();
                        using (CloudFileStream fileStream = file.EndOpenWrite(result))
                        {
                            IAsyncResult[] results = new IAsyncResult[fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value * 2];
                            for (int i = 0; i < results.Length; i++)
                            {
                                results[i] = fileStream.BeginWrite(buffer, 0, buffer.Length, null, null);
                                wholeFile.Write(buffer, 0, buffer.Length);
                                Assert.AreEqual(wholeFile.Position, fileStream.Position);
                            }

                            for (int i = 0; i < fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value; i++)
                            {
                                Assert.IsTrue(results[i].IsCompleted);
                            }

                            for (int i = fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value; i < results.Length; i++)
                            {
                                Assert.IsFalse(results[i].IsCompleted);
                            }

                            for (int i = 0; i < results.Length; i++)
                            {
                                fileStream.EndWrite(results[i]);
                            }

                            result = fileStream.BeginCommit(
                                ar => waitHandle.Set(),
                                null);
                            waitHandle.WaitOne();
                            fileStream.EndCommit(result);
                        }
                    }

                    wholeFile.Seek(0, SeekOrigin.Begin);
                    string md5 = Convert.ToBase64String(hasher.ComputeHash(wholeFile));
                    file.FetchAttributes();
                    Assert.AreEqual(md5, file.Properties.ContentMD5);

                    using (MemoryStream downloadedFile = new MemoryStream())
                    {
                        file.DownloadToStream(downloadedFile);
                        TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile);
                    }

                    fileClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;

                    TestHelper.ExpectedException <ArgumentException>(
                        () => file.BeginOpenWrite(null, null, options, null, null, null),
                        "BeginOpenWrite with StoreFileContentMD5 on an existing file should fail");

                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        IAsyncResult result = file.BeginOpenWrite(null,
                                                                  ar => waitHandle.Set(),
                                                                  null);
                        waitHandle.WaitOne();
                        using (Stream fileStream = file.EndOpenWrite(result))
                        {
                            fileStream.Seek(buffer.Length / 2, SeekOrigin.Begin);
                            wholeFile.Seek(buffer.Length / 2, SeekOrigin.Begin);

                            IAsyncResult[] results = new IAsyncResult[fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value * 2];
                            for (int i = 0; i < results.Length; i++)
                            {
                                results[i] = fileStream.BeginWrite(buffer, 0, buffer.Length, null, null);
                                wholeFile.Write(buffer, 0, buffer.Length);
                                Assert.AreEqual(wholeFile.Position, fileStream.Position);
                            }

                            for (int i = 0; i < fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value; i++)
                            {
                                Assert.IsTrue(results[i].IsCompleted);
                            }

                            for (int i = fileClient.DefaultRequestOptions.ParallelOperationThreadCount.Value; i < results.Length; i++)
                            {
                                Assert.IsFalse(results[i].IsCompleted);
                            }

                            for (int i = 0; i < results.Length; i++)
                            {
                                fileStream.EndWrite(results[i]);
                            }

                            wholeFile.Seek(0, SeekOrigin.End);
                        }

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

                        using (MemoryStream downloadedFile = new MemoryStream())
                        {
                            options.DisableContentMD5Validation = true;
                            file.DownloadToStream(downloadedFile, null, options);
                            TestHelper.AssertStreamsAreEqual(wholeFile, downloadedFile);
                        }
                    }
                }
            }
            finally
            {
                share.DeleteIfExists();
            }
        }
        /// <summary>
        /// Manage file metadata
        /// </summary>
        /// <param name="cloudFileClient"></param>
        /// <returns></returns>
        private static async Task FileMetadataSample(CloudFileClient cloudFileClient)
        {
            Console.WriteLine();
            // Create the share name -- use a guid in the name so it's unique.
            string shareName = "demotest-" + Guid.NewGuid();
            CloudFileShare share = cloudFileClient.GetShareReference(shareName);
            try
            {
                // Create share
                Console.WriteLine("Create Share");
                await share.CreateIfNotExistsAsync();

                // Create directory
                Console.WriteLine("Create directory");
                CloudFileDirectory rootDirectory = share.GetRootDirectoryReference();
                await rootDirectory.CreateIfNotExistsAsync();

                CloudFile file = rootDirectory.GetFileReference("demofile");

                // Set file metadata
                Console.WriteLine("Set file metadata");
                file.Metadata.Add("key1", "value1");
                file.Metadata.Add("key2", "value2");

                // Create file
                Console.WriteLine("Create file");
                await file.CreateAsync(1000);

                // Fetch file attributes
                // in this case this call is not need but is included for demo purposes
                await file.FetchAttributesAsync();
                Console.WriteLine("Get file metadata:");
                foreach (var keyValue in file.Metadata)
                {
                    Console.WriteLine("    {0}: {1}", keyValue.Key, keyValue.Value);
                }
                Console.WriteLine();
            }
            catch (StorageException exStorage)
            {
                Common.WriteException(exStorage);
                Console.WriteLine(
                    "Please make sure your storage account is specified correctly in the app.config - then restart the sample.");
                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("    Exception thrown creating share.");
                Common.WriteException(ex);
                throw;
            }
            finally
            {
                // Delete share
                Console.WriteLine("Delete share");
                share.DeleteIfExists();
            }
        }