public async Task BlobServiceCors() { BlobServiceData properties1 = _blobService.Data; BlobServiceData properties2 = new BlobServiceData(); properties2.DeleteRetentionPolicy = new DeleteRetentionPolicy(); properties2.DeleteRetentionPolicy.Enabled = true; properties2.DeleteRetentionPolicy.Days = 300; properties2.DefaultServiceVersion = "2017-04-17"; properties2.Cors = new CorsRules(); properties2.Cors.CorsRulesValue.Add(new CorsRule(new string[] { "http://www.contoso.com", "http://www.fabrikam.com" }, new CorsRuleAllowedMethodsItem[] { CorsRuleAllowedMethodsItem.GET, CorsRuleAllowedMethodsItem.PUT }, 100, new string[] { "x-ms-meta-*" }, new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*" } )); properties2.Cors.CorsRulesValue.Add(new CorsRule(new string[] { "*" }, new CorsRuleAllowedMethodsItem[] { CorsRuleAllowedMethodsItem.GET }, 2, new string[] { "*" }, new string[] { "*" } )); properties2.Cors.CorsRulesValue.Add(new CorsRule(new string[] { "http://www.abc23.com", "https://www.fabrikam.com/*" }, new CorsRuleAllowedMethodsItem[] { CorsRuleAllowedMethodsItem.GET, CorsRuleAllowedMethodsItem.PUT, CorsRuleAllowedMethodsItem.Post }, 2000, new string[] { "x-ms-meta-12345675754564*" }, new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*" } )); _blobService = (await _blobService.CreateOrUpdateAsync(properties2)).Value; BlobServiceData properties3 = _blobService.Data; Assert.IsTrue(properties3.DeleteRetentionPolicy.Enabled); Assert.AreEqual(300, properties3.DeleteRetentionPolicy.Days); Assert.AreEqual("2017-04-17", properties3.DefaultServiceVersion); //validate CORS rules Assert.AreEqual(properties2.Cors.CorsRulesValue.Count, properties3.Cors.CorsRulesValue.Count); for (int i = 0; i < properties2.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = properties2.Cors.CorsRulesValue[i]; CorsRule getRule = properties3.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } _blobService = await _blobService.GetAsync(); BlobServiceData properties4 = _blobService.Data; Assert.IsTrue(properties4.DeleteRetentionPolicy.Enabled); Assert.AreEqual(300, properties4.DeleteRetentionPolicy.Days); Assert.AreEqual("2017-04-17", properties4.DefaultServiceVersion); //validate CORS rules Assert.AreEqual(properties2.Cors.CorsRulesValue.Count, properties4.Cors.CorsRulesValue.Count); for (int i = 0; i < properties2.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = properties2.Cors.CorsRulesValue[i]; CorsRule getRule = properties4.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } }
public void CloudTableTestValidCorsRules() { 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>() { "*" } }; CloudTableClient client = GenerateCloudTableClient(); 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"); }
private static CorsRule Clone(CorsRule rule) { throw new NotImplementedException(); }
public string EnableStorageCORS(Account account) { try { var storageAccount = StorageUtils.CreateCloudStorageAccount(account); var blobClient = storageAccount.CreateCloudBlobClient(); CorsHttpMethods allowedMethods = CorsHttpMethods.None; allowedMethods = allowedMethods | CorsHttpMethods.Get; allowedMethods = allowedMethods | CorsHttpMethods.Put; allowedMethods = allowedMethods | CorsHttpMethods.Post; allowedMethods = allowedMethods | CorsHttpMethods.Delete; allowedMethods = allowedMethods | CorsHttpMethods.Options; var delimiter = new[] { "," }; CorsRule corsRule = new CorsRule(); const string allowedOrigins = "*"; const string allowedHeaders = "*"; const string exposedHeaders = ""; string[] allAllowedOrigin = allowedOrigins.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); string[] allExpHeaders = exposedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); string[] allAllowHeaders = allowedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); List <string> corsAllowedOrigin = new List <string>(); foreach (var item in allAllowedOrigin) { if (!string.IsNullOrWhiteSpace(item)) { corsAllowedOrigin.Add(item.Trim()); } } List <string> corsExposedHeaders = new List <string>(); foreach (var item in allExpHeaders) { if (!string.IsNullOrWhiteSpace(item)) { corsExposedHeaders.Add(item.Trim()); } } List <string> corsAllowHeaders = new List <string>(); foreach (var item in allAllowHeaders) { if (!string.IsNullOrWhiteSpace(item)) { corsAllowHeaders.Add(item.Trim()); } } corsRule.MaxAgeInSeconds = 200; corsRule.AllowedMethods = allowedMethods; corsRule.AllowedHeaders = corsAllowHeaders; corsRule.AllowedOrigins = corsAllowedOrigin; corsRule.ExposedHeaders = corsExposedHeaders; ServiceProperties properties = blobClient.GetServiceProperties(); properties.Cors.CorsRules.Clear(); properties.Cors.CorsRules.Add(corsRule); blobClient.SetServiceProperties(properties); } catch (Exception ex) { logger.Error(ex); return("Failed due to Incorrect Account Name or Key."); } return("Enabling CORS Succeed"); }
public async Task FileServiceCorsTest() { // Create resource group var rgName = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account StorageAccount account = await CreateStorageAccountAsync(rgName, accountName); VerifyAccountProperties(account, true); // implement case Response <FileServiceProperties> properties1 = await FileServicesClient.GetServicePropertiesAsync(rgName, accountName); Assert.AreEqual(0, properties1.Value.Cors.CorsRulesValue.Count()); properties1.Value.Cors = new CorsRules { CorsRulesValue = { new CorsRule(allowedOrigins: new string[] { "http://www.contoso.com", "http://www.fabrikam.com" }, allowedMethods: new CorsRuleAllowedMethodsItem[] { "GET", "HEAD", "POST", "OPTIONS", "MERGE", "PUT"}, maxAgeInSeconds: 100, exposedHeaders: new string[] { "x-ms-meta-*" }, allowedHeaders: new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*"}), new CorsRule(allowedOrigins: new string[] { "*" }, allowedMethods: new CorsRuleAllowedMethodsItem[] { "GET" }, maxAgeInSeconds: 2, exposedHeaders: new string[] { "*" }, allowedHeaders: new string[] { "*" }), new CorsRule(allowedOrigins: new string[] { "http://www.abc23.com", "https://www.fabrikam.com/*" }, allowedMethods: new CorsRuleAllowedMethodsItem[] { "GET", "PUT", "CONNECT" }, maxAgeInSeconds: 2000, exposedHeaders: new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x -ms-meta-target*"}, allowedHeaders: new string[] { "x-ms-meta-12345675754564*" }) } }; Response <FileServiceProperties> properties3 = await FileServicesClient.SetServicePropertiesAsync(rgName, accountName, properties1.Value); //Validate CORS Rules Assert.AreEqual(properties1.Value.Cors.CorsRulesValue.Count, properties3.Value.Cors.CorsRulesValue.Count); for (int i = 0; i < properties1.Value.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = properties1.Value.Cors.CorsRulesValue[i]; CorsRule getRule = properties3.Value.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } Response <FileServiceProperties> properties4 = await FileServicesClient.GetServicePropertiesAsync(rgName, accountName); //Validate CORS Rules Assert.AreEqual(properties1.Value.Cors.CorsRulesValue.Count, properties4.Value.Cors.CorsRulesValue.Count); for (int i = 0; i < properties1.Value.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = properties1.Value.Cors.CorsRulesValue[i]; CorsRule getRule = properties4.Value.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } }
internal static void AssertServicePropertiesAreEqual(ServiceProperties propsA, ServiceProperties propsB) { if (propsA.Logging != null && propsB.Logging != null) { Assert.AreEqual(propsA.Logging.LoggingOperations, propsB.Logging.LoggingOperations); Assert.AreEqual(propsA.Logging.RetentionDays, propsB.Logging.RetentionDays); Assert.AreEqual(propsA.Logging.Version, propsB.Logging.Version); } else { Assert.IsNull(propsA.Logging); Assert.IsNull(propsA.Logging); } if (propsA.HourMetrics != null && propsB.Logging != null) { Assert.AreEqual(propsA.HourMetrics.MetricsLevel, propsB.HourMetrics.MetricsLevel); Assert.AreEqual(propsA.HourMetrics.RetentionDays, propsB.HourMetrics.RetentionDays); Assert.AreEqual(propsA.HourMetrics.Version, propsB.HourMetrics.Version); } else { Assert.IsNull(propsA.HourMetrics); Assert.IsNull(propsB.HourMetrics); } if (propsA.MinuteMetrics != null && propsB.MinuteMetrics != null) { Assert.AreEqual(propsA.MinuteMetrics.MetricsLevel, propsB.MinuteMetrics.MetricsLevel); Assert.AreEqual(propsA.MinuteMetrics.RetentionDays, propsB.MinuteMetrics.RetentionDays); Assert.AreEqual(propsA.MinuteMetrics.Version, propsB.MinuteMetrics.Version); } else { Assert.IsNull(propsA.MinuteMetrics); Assert.IsNull(propsB.MinuteMetrics); } if (propsA.DefaultServiceVersion != null && propsB.DefaultServiceVersion != null) { Assert.AreEqual(propsA.DefaultServiceVersion, propsB.DefaultServiceVersion); } else { Assert.IsNull(propsA.DefaultServiceVersion); Assert.IsNull(propsB.DefaultServiceVersion); } if (propsA.Cors != null && propsB.Cors != null) { Assert.AreEqual(propsA.Cors.CorsRules.Count, propsB.Cors.CorsRules.Count); // Check that rules are equal and in the same order. for (int i = 0; i < propsA.Cors.CorsRules.Count; i++) { CorsRule ruleA = propsA.Cors.CorsRules.ElementAt(i); CorsRule ruleB = propsB.Cors.CorsRules.ElementAt(i); Assert.IsTrue( ruleA.AllowedOrigins.Count == ruleB.AllowedOrigins.Count && !ruleA.AllowedOrigins.Except(ruleB.AllowedOrigins).Any()); Assert.IsTrue( ruleA.ExposedHeaders.Count == ruleB.ExposedHeaders.Count && !ruleA.ExposedHeaders.Except(ruleB.ExposedHeaders).Any()); Assert.IsTrue( ruleA.AllowedHeaders.Count == ruleB.AllowedHeaders.Count && !ruleA.AllowedHeaders.Except(ruleB.AllowedHeaders).Any()); Assert.IsTrue(ruleA.AllowedMethods == ruleB.AllowedMethods); Assert.IsTrue(ruleA.MaxAgeInSeconds == ruleB.MaxAgeInSeconds); } } else { Assert.IsNull(propsA.Cors); Assert.IsNull(propsB.Cors); } }
public void TableServiceCorsTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType().FullName)) { var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(context, handler); var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler); // Create resource group var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient); // Create storage account string accountName = TestUtilities.GenerateName("sto"); var parameters = new StorageAccountCreateParameters { Location = "eastus2euap", Kind = Kind.StorageV2, Sku = new Sku { Name = SkuName.StandardLRS }, LargeFileSharesState = LargeFileSharesState.Enabled }; var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters); // implement case try { TableServiceProperties properties1 = storageMgmtClient.TableServices.GetServiceProperties(rgName, accountName); Assert.Equal(0, properties1.Cors.CorsRulesProperty.Count); CorsRules cors = new CorsRules(); cors.CorsRulesProperty = new List <CorsRule>(); cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*" }, AllowedMethods = new string[] { "GET", "HEAD", "POST", "OPTIONS", "MERGE", "PUT" }, AllowedOrigins = new string[] { "http://www.contoso.com", "http://www.fabrikam.com" }, ExposedHeaders = new string[] { "x-ms-meta-*" }, MaxAgeInSeconds = 100 }); cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "*" }, AllowedMethods = new string[] { "GET" }, AllowedOrigins = new string[] { "*" }, ExposedHeaders = new string[] { "*" }, MaxAgeInSeconds = 2 }); cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "x-ms-meta-12345675754564*" }, AllowedMethods = new string[] { "GET", "PUT", "CONNECT" }, AllowedOrigins = new string[] { "http://www.abc23.com", "https://www.fabrikam.com/*" }, ExposedHeaders = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x -ms-meta-target*" }, MaxAgeInSeconds = 2000 }); TableServiceProperties properties3 = storageMgmtClient.TableServices.SetServiceProperties(rgName, accountName, cors); //Validate CORS Rules if (HttpMockServer.Mode == HttpRecorderMode.Record) { // Need wait for cors rules setting take effect when record case System.Threading.Thread.Sleep(30000); } Assert.Equal(cors.CorsRulesProperty.Count, properties3.Cors.CorsRulesProperty.Count); for (int i = 0; i < cors.CorsRulesProperty.Count; i++) { CorsRule putRule = cors.CorsRulesProperty[i]; CorsRule getRule = properties3.Cors.CorsRulesProperty[i]; Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods); Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } TableServiceProperties properties4 = storageMgmtClient.TableServices.GetServiceProperties(rgName, accountName); //Validate CORS Rules Assert.Equal(cors.CorsRulesProperty.Count, properties4.Cors.CorsRulesProperty.Count); for (int i = 0; i < cors.CorsRulesProperty.Count; i++) { CorsRule putRule = cors.CorsRulesProperty[i]; CorsRule getRule = properties4.Cors.CorsRulesProperty[i]; Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods); Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } } finally { // clean up storageMgmtClient.StorageAccounts.Delete(rgName, accountName); resourcesClient.ResourceGroups.Delete(rgName); } } }
// Constructor - create from an Azure CorsRule object. public CORSRule(CorsRule rule) { // Retrieve allowed origins. if (rule.AllowedOrigins != null) { String origins = String.Empty; foreach (String origin in rule.AllowedOrigins) { if (origins.Length > 0) { origins = origins + ","; } origins = origins + origin; } this.AllowedOrigins = origins; } // Retrieve allowed headers. if (rule.AllowedHeaders != null) { String headers = String.Empty; foreach (String header in rule.AllowedHeaders) { if (headers.Length > 0) { headers = headers + ","; } headers = headers + header; } this.AllowedHeaders = headers; } // Retrieve exposed headers. if (rule.ExposedHeaders != null) { String headers = String.Empty; foreach (String header in rule.ExposedHeaders) { if (headers.Length > 0) { headers = headers + ","; } headers = headers + header; } this.ExposedHeaders = headers; } // Retrieve allowed methods. String methods = String.Empty; if ((rule.AllowedMethods & CorsHttpMethods.Connect) == CorsHttpMethods.Connect) { methods = methods + "CONNECT,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Delete) == CorsHttpMethods.Delete) { methods = methods + "DELETE,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Get) == CorsHttpMethods.Get) { methods = methods + "GET,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Head) == CorsHttpMethods.Head) { methods = methods + "HEAD,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Merge) == CorsHttpMethods.Merge) { methods = methods + "MERGE,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.None) == CorsHttpMethods.None) { methods = methods + "NONE,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Options) == CorsHttpMethods.Options) { methods = methods + "OPTIONS,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Post) == CorsHttpMethods.Post) { methods = methods + "POST,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Put) == CorsHttpMethods.Put) { methods = methods + "PUT,"; } ; if ((rule.AllowedMethods & CorsHttpMethods.Trace) == CorsHttpMethods.Trace) { methods = methods + "TRACE,"; } ; if (methods.Length > 0 && methods.EndsWith(",")) { methods = methods.Substring(0, methods.Length - 1); } this.AllowedMethods = methods; this.MaxAgeInSeconds = rule.MaxAgeInSeconds.ToString(); }
public async Task BlobServiceCors() { BlobServiceData blobServiceData = new BlobServiceData() { DeleteRetentionPolicy = new DeleteRetentionPolicy() { Enabled = true, Days = 300, }, DefaultServiceVersion = "2017-04-17", Cors = new CorsRules() { CorsRulesValue = { new CorsRule(new[] { "http://www.contoso.com", "http://www.fabrikam.com" }, new[] { CorsRuleAllowedMethodsItem.GET, CorsRuleAllowedMethodsItem.PUT }, 100, new[] { "x-ms-meta-*" }, new[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*"}), new CorsRule(new[] { "*" }, new[] { CorsRuleAllowedMethodsItem.GET }, 2, new[] { "*" }, new[] { "*" }), new CorsRule(new[] { "http://www.abc23.com", "https://www.fabrikam.com/*" }, new[] { CorsRuleAllowedMethodsItem.GET, CorsRuleAllowedMethodsItem.PUT, CorsRuleAllowedMethodsItem.Post}, 2000, new[] { "x-ms-meta-12345675754564*" }, new[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*"}) } } }; _blobService = (await _blobService.CreateOrUpdateAsync(WaitUntil.Completed, blobServiceData)).Value; Assert.AreEqual(blobServiceData.DeleteRetentionPolicy.Enabled, _blobService.Data.DeleteRetentionPolicy.Enabled); Assert.AreEqual(blobServiceData.DeleteRetentionPolicy.Days, _blobService.Data.DeleteRetentionPolicy.Days); Assert.AreEqual(blobServiceData.DefaultServiceVersion, _blobService.Data.DefaultServiceVersion); //validate CORS rules Assert.AreEqual(blobServiceData.Cors.CorsRulesValue.Count, _blobService.Data.Cors.CorsRulesValue.Count); for (int i = 0; i < blobServiceData.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = blobServiceData.Cors.CorsRulesValue[i]; CorsRule getRule = _blobService.Data.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } _blobService = await _blobService.GetAsync(); Assert.AreEqual(blobServiceData.DeleteRetentionPolicy.Enabled, _blobService.Data.DeleteRetentionPolicy.Enabled); Assert.AreEqual(blobServiceData.DeleteRetentionPolicy.Days, _blobService.Data.DeleteRetentionPolicy.Days); Assert.AreEqual(blobServiceData.DefaultServiceVersion, _blobService.Data.DefaultServiceVersion); //validate CORS rules Assert.AreEqual(blobServiceData.Cors.CorsRulesValue.Count, _blobService.Data.Cors.CorsRulesValue.Count); for (int i = 0; i < blobServiceData.Cors.CorsRulesValue.Count; i++) { CorsRule putRule = blobServiceData.Cors.CorsRulesValue[i]; CorsRule getRule = _blobService.Data.Cors.CorsRulesValue[i]; Assert.AreEqual(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.AreEqual(putRule.AllowedMethods, getRule.AllowedMethods); Assert.AreEqual(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.AreEqual(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.AreEqual(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } }
public override void ExecuteCmdlet() { if (ServiceType != StorageServiceType.Table) { ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.Clean(); serviceProperties.Cors = new CorsProperties(); foreach (var corsRuleObject in this.CorsRules) { CorsRule corsRule = new CorsRule(); corsRule.AllowedHeaders = corsRuleObject.AllowedHeaders; corsRule.AllowedOrigins = corsRuleObject.AllowedOrigins; corsRule.ExposedHeaders = corsRuleObject.ExposedHeaders; corsRule.MaxAgeInSeconds = corsRuleObject.MaxAgeInSeconds; this.SetAllowedMethods(corsRule, corsRuleObject.AllowedMethods); serviceProperties.Cors.CorsRules.Add(corsRule); } try { Channel.SetStorageServiceProperties(ServiceType, serviceProperties, GetRequestOptions(ServiceType), OperationContext); } catch (StorageException se) { if ((null != se.RequestInformation) && ((int)HttpStatusCode.BadRequest == se.RequestInformation.HttpStatusCode) && (null != se.RequestInformation.ExtendedErrorInformation) && (string.Equals(InvalidXMLNodeValueError, se.RequestInformation.ErrorCode, StringComparison.OrdinalIgnoreCase) || string.Equals(InvalidXMLDocError, se.RequestInformation.ErrorCode, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(Resources.CORSRuleError); } else { throw; } } } else //Table use old XSCL { XTable.ServiceProperties serviceProperties = new XTable.ServiceProperties(); serviceProperties.Clean(); serviceProperties.Cors = new XTable.CorsProperties(); foreach (var corsRuleObject in this.CorsRules) { XTable.CorsRule corsRule = new XTable.CorsRule(); corsRule.AllowedHeaders = corsRuleObject.AllowedHeaders; corsRule.AllowedOrigins = corsRuleObject.AllowedOrigins; corsRule.ExposedHeaders = corsRuleObject.ExposedHeaders; corsRule.MaxAgeInSeconds = corsRuleObject.MaxAgeInSeconds; this.SetAllowedMethods(corsRule, corsRuleObject.AllowedMethods); serviceProperties.Cors.CorsRules.Add(corsRule); } try { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); tableChannel.SetStorageTableServiceProperties(serviceProperties, GetTableRequestOptions(), TableOperationContext); } catch (XTable.StorageException se) { if ((null != se.RequestInformation) && ((int)HttpStatusCode.BadRequest == se.RequestInformation.HttpStatusCode) && (null != se.RequestInformation.ExtendedErrorInformation) && (string.Equals(InvalidXMLNodeValueError, se.RequestInformation.ErrorCode, StringComparison.OrdinalIgnoreCase) || string.Equals(InvalidXMLDocError, se.RequestInformation.ErrorCode, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(Resources.CORSRuleError); } else { throw; } } } if (PassThru) { WriteObject(this.CorsRules); } }
public async Task EnableCORSAsync() { CorsHttpMethods allowedMethods = CorsHttpMethods.None; allowedMethods |= CorsHttpMethods.Get; allowedMethods |= CorsHttpMethods.Put; allowedMethods |= CorsHttpMethods.Post; allowedMethods |= CorsHttpMethods.Delete; allowedMethods |= CorsHttpMethods.Options; var delimiter = new[] { "," }; var corsRule = new CorsRule(); const string AllowedOrigins = "*"; const string AllowedHeaders = "*"; const string ExposedHeaders = ""; var allAllowedOrigin = AllowedOrigins.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); var allExpHeaders = ExposedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); var allAllowHeaders = AllowedHeaders.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); var corsAllowedOrigin = new List <string>(); foreach (var item in allAllowedOrigin) { if (!string.IsNullOrWhiteSpace(item)) { corsAllowedOrigin.Add(item.Trim()); } } var corsExposedHeaders = new List <string>(); foreach (var item in allExpHeaders) { if (!string.IsNullOrWhiteSpace(item)) { corsExposedHeaders.Add(item.Trim()); } } var corsAllowHeaders = new List <string>(); foreach (var item in allAllowHeaders) { if (!string.IsNullOrWhiteSpace(item)) { corsAllowHeaders.Add(item.Trim()); } } corsRule.MaxAgeInSeconds = 200; corsRule.AllowedMethods = allowedMethods; corsRule.AllowedHeaders = corsAllowHeaders; corsRule.AllowedOrigins = corsAllowedOrigin; corsRule.ExposedHeaders = corsExposedHeaders; var serviceProperties = await this.blobClient.GetServicePropertiesAsync(); serviceProperties.Cors.CorsRules.Clear(); serviceProperties.Cors.CorsRules.Add(corsRule); await this.blobClient.SetServicePropertiesAsync(serviceProperties); }
public void GetServiceProperties_AllService_AllProperties() { //prepare the service properties to set and get PSCorsRule[] corsRules = CORSRuleUtil.GetRandomValidCORSRules(random.Next(1, 5)); Microsoft.WindowsAzure.Storage.Shared.Protocol.ServiceProperties serviceProperties = new Microsoft.WindowsAzure.Storage.Shared.Protocol.ServiceProperties(); serviceProperties.Clean(); serviceProperties.Cors = new CorsProperties(); foreach (var rule in corsRules) { CorsRule corsRule = new CorsRule() { AllowedHeaders = rule.AllowedHeaders, AllowedOrigins = rule.AllowedOrigins, ExposedHeaders = rule.ExposedHeaders, MaxAgeInSeconds = rule.MaxAgeInSeconds, }; SetAllowedMethods(corsRule, rule.AllowedMethods); serviceProperties.Cors.CorsRules.Add(corsRule); } serviceProperties.HourMetrics = new MetricsProperties("1.0"); serviceProperties.HourMetrics.MetricsLevel = MetricsLevel.ServiceAndApi; serviceProperties.HourMetrics.RetentionDays = 1; serviceProperties.MinuteMetrics = new MetricsProperties("1.0"); serviceProperties.MinuteMetrics.MetricsLevel = MetricsLevel.Service; serviceProperties.MinuteMetrics.RetentionDays = 3; serviceProperties.Logging = new LoggingProperties("1.0"); serviceProperties.Logging.LoggingOperations = LoggingOperations.All; serviceProperties.Logging.RetentionDays = 5; foreach (string servicetype in ValidServiceType) { Constants.ServiceType service = Constants.ServiceType.Blob; Enum.TryParse <Constants.ServiceType>(servicetype, true, out service); if (service == Constants.ServiceType.Blob) //only Blob support default service version { serviceProperties.DefaultServiceVersion = "2017-04-17"; serviceProperties.DeleteRetentionPolicy = new DeleteRetentionPolicy(); serviceProperties.DeleteRetentionPolicy.Enabled = true; serviceProperties.DeleteRetentionPolicy.RetentionDays = 10; } //Set Service Properties with XSCL API ServiceCORSRule.SetSerivceProperties(service, serviceProperties); //Get Service Properties with PowerShell PSSeriviceProperties properties = GetServicePropertiesFromPSH(service); //Validate Cors, metric, logging CORSRuleUtil.ValidateCORSRules(corsRules, properties.Cors); if (service != Constants.ServiceType.File) // File service don't support logging { ExpectEqual(serviceProperties.Logging.Version, properties.Logging.Version, "Logging version"); ExpectEqual(serviceProperties.Logging.LoggingOperations.ToString(), properties.Logging.LoggingOperations.ToString(), "Logging Operations"); ExpectEqual(serviceProperties.Logging.RetentionDays.Value, properties.Logging.RetentionDays.Value, "Logging RetentionDays"); } ExpectEqual(serviceProperties.HourMetrics.Version, properties.HourMetrics.Version, "HourMetrics Version"); ExpectEqual(serviceProperties.HourMetrics.MetricsLevel.ToString(), properties.HourMetrics.MetricsLevel.ToString(), "HourMetrics MetricsLevel"); ExpectEqual(serviceProperties.HourMetrics.RetentionDays.Value, properties.HourMetrics.RetentionDays.Value, "HourMetrics RetentionDays"); ExpectEqual(serviceProperties.MinuteMetrics.Version, properties.MinuteMetrics.Version, "MinuteMetrics Version"); ExpectEqual(serviceProperties.MinuteMetrics.MetricsLevel.ToString(), properties.MinuteMetrics.MetricsLevel.ToString(), "MinuteMetrics MetricsLevel"); ExpectEqual(serviceProperties.MinuteMetrics.RetentionDays.Value, properties.MinuteMetrics.RetentionDays.Value, "MinuteMetrics RetentionDays"); if (service == Constants.ServiceType.Blob) { ExpectEqual(serviceProperties.DefaultServiceVersion, properties.DefaultServiceVersion, "DefaultServiceVersion"); ExpectEqual(serviceProperties.DeleteRetentionPolicy.Enabled.ToString(), properties.DeleteRetentionPolicy.Enabled.ToString(), "DeleteRetentionPolicy Enabled"); ExpectEqual(serviceProperties.DeleteRetentionPolicy.RetentionDays.Value, properties.DeleteRetentionPolicy.RetentionDays.Value, "DeleteRetentionPolicy RetentionDays"); serviceProperties.DeleteRetentionPolicy = null; serviceProperties.DefaultServiceVersion = null; } } }
public async Task RunQueueStorageOperationsAsync() { // string queueName = "queue-" + System.Guid.NewGuid().ToString(); string queueName = "queue"; Console.WriteLine(); CloudStorageAccount storageAccount = Common.CreateStorageAccountFromConnectionString(Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(queueName); try { await queue.CreateIfNotExistsAsync(); } catch { Console.WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample."); Console.ReadLine(); throw; } Console.WriteLine("QUEUE created with NAME : " + queue.Name.ToString() + "\n"); Console.WriteLine("*** MENU ***"); Console.WriteLine("1 : Insert a message into a queue"); Console.WriteLine("2 : See messages in a queue"); Console.WriteLine("3 : De-queue the next message"); Console.WriteLine("4 : Change the contents of a queued message"); Console.WriteLine("5 : Enqueue a limited number of messages"); Console.WriteLine("6 : Get the queue length"); Console.WriteLine("7 : Delete the Queue"); Console.WriteLine("8 : listing and comparing queues "); Console.WriteLine("9 : Get Service Properties of Queue"); Console.WriteLine("10 : adding and restoring CORS rules sample"); Console.WriteLine("11 : QUEUE MetaData"); Console.WriteLine("12 : exit app"); var selectedValue = Console.ReadLine(); Regex regex = new Regex("^[0-9]+$"); if (regex.IsMatch(selectedValue.ToString())) { int selection = Convert.ToInt32(selectedValue); while (selection != 0) { switch (selection) { case 1: //Insert a message into a queue Console.WriteLine("Enter a message"); await queue.AddMessageAsync(new CloudQueueMessage(Console.ReadLine())); break; case 2: //Peek messages in a queue CloudQueueMessage peekedMessage = await queue.PeekMessageAsync(); if (peekedMessage != null) { Console.WriteLine("The peeked message is: {0}", peekedMessage.AsString); } else { Console.WriteLine("No messages exist"); } break; case 3: //De-queue the next message CloudQueueMessage message = await queue.GetMessageAsync(); if (message != null) { Console.WriteLine("Processing & deleting message with content: {0}", message.AsString); await queue.DeleteMessageAsync(message); } else { Console.WriteLine("No messages exist"); } break; case 4: //Change the contents of a queued message CloudQueueMessage message1 = await queue.GetMessageAsync(); if (message1 != null) { Console.WriteLine("Enter content to be updated !"); message1.SetMessageContent(Console.ReadLine().ToString()); await queue.UpdateMessageAsync(message1, TimeSpan.Zero, MessageUpdateFields.Content | MessageUpdateFields.Visibility); CloudQueueMessage peekedMessage1 = await queue.PeekMessageAsync(); if (peekedMessage1 != null) { Console.WriteLine("The modified message is: {0}", peekedMessage1.AsString); } } else { Console.WriteLine("No messages exist"); } break; case 5: //Enqueue a limited number of messages Console.WriteLine("Input the count of the messages : "); var messageCount = Console.ReadLine(); if (regex.IsMatch(messageCount.ToString())) { for (int i = 0; i < Convert.ToInt32(messageCount); i++) { Console.WriteLine("Enter the message no : " + i); var newMsg = Console.ReadLine(); await queue.AddMessageAsync(new CloudQueueMessage(newMsg)); } } else { Console.WriteLine("Please Input a number"); } break; case 6: //Get the queue length queue.FetchAttributes(); int? count = queue.ApproximateMessageCount; if (count != null && count > 0) { Console.WriteLine("Message count = " + count); } else { Console.WriteLine("No messages exist"); } break; case 7: //Delete the Queue await queue.DeleteIfExistsAsync(); Console.WriteLine("Queue deleted !!"); break; case 8: //listing and comparing queues Console.WriteLine("Enter the no of queues u want to create"); var queueCount = Console.ReadLine(); List<string> lstQueueNames = new List<string>(); if (regex.IsMatch(queueCount.ToString())) { for (int i = 0; i < Convert.ToInt32(queueCount); i++) { string qName = queueName + "-ls-" + i; lstQueueNames.Add(qName); CloudQueue cloudQueue = queueClient.GetQueueReference(queueName); try { await cloudQueue.CreateIfNotExistsAsync(); } 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 while creating queue."); Common.WriteException(ex); throw; } } QueueContinuationToken queueContinuationToken = null; List<CloudQueue> lstCloudQueues = new List<CloudQueue>(); do { QueueResultSegment queueResultSegment = await queueClient.ListQueuesSegmentedAsync(queueName, queueContinuationToken); queueContinuationToken = queueResultSegment.ContinuationToken; lstCloudQueues.AddRange(queueResultSegment.Results); } while (queueContinuationToken != null); foreach (string qNames in lstQueueNames) { CloudQueue cloudQueue = queueClient.GetQueueReference(qNames); cloudQueue.DeleteIfExists(); } } else { Console.WriteLine("Enter a numeric value"); } break; case 9: // get the service properties - sample only ServiceProperties orignalServiceProperties = await queueClient.GetServicePropertiesAsync(); Console.WriteLine("Original service properties :"); Console.WriteLine("Logging operations : " + orignalServiceProperties.Logging.LoggingOperations); Console.WriteLine("Logging RetentionDays : " + orignalServiceProperties.Logging.RetentionDays); Console.WriteLine("Logging Version : " + orignalServiceProperties.Logging.Version); Console.WriteLine("HourMetrics MetricsLevel : " + orignalServiceProperties.HourMetrics.MetricsLevel); Console.WriteLine("HourMetrics Retention Days : " + orignalServiceProperties.HourMetrics.RetentionDays); Console.WriteLine("HourMetrics Version : " + orignalServiceProperties.HourMetrics.Version); Console.WriteLine("MinuteMetrics MetricsLevel : " + orignalServiceProperties.MinuteMetrics.MetricsLevel); Console.WriteLine("MinuteMetrics Retention Days : " + orignalServiceProperties.MinuteMetrics.RetentionDays); Console.WriteLine("MinuteMetrics Version : " + orignalServiceProperties.MinuteMetrics.Version); try { Console.WriteLine(); Console.WriteLine("After changing values"); //change the service properties ServiceProperties serviceProperties = await queueClient.GetServicePropertiesAsync(); serviceProperties.Logging.LoggingOperations = LoggingOperations.Read | LoggingOperations.Write; serviceProperties.Logging.RetentionDays = 10; serviceProperties.Logging.Version = Constants.AnalyticsConstants.LoggingVersionV1; serviceProperties.HourMetrics.MetricsLevel = MetricsLevel.Service; serviceProperties.HourMetrics.RetentionDays = 10; serviceProperties.HourMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1; serviceProperties.MinuteMetrics.MetricsLevel = MetricsLevel.Service; serviceProperties.MinuteMetrics.RetentionDays = 10; serviceProperties.MinuteMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1; await queueClient.SetServicePropertiesAsync(serviceProperties); Console.WriteLine("Logging operations : " + serviceProperties.Logging.LoggingOperations); Console.WriteLine("Logging RetentionDays : " + serviceProperties.Logging.RetentionDays); Console.WriteLine("Logging Version : " + serviceProperties.Logging.Version); Console.WriteLine("HourMetrics MetricsLevel : " + serviceProperties.HourMetrics.MetricsLevel); Console.WriteLine("HourMetrics Retention Days : " + serviceProperties.HourMetrics.RetentionDays); Console.WriteLine("HourMetrics Version : " + serviceProperties.HourMetrics.Version); Console.WriteLine("MinuteMetrics MetricsLevel : " + serviceProperties.MinuteMetrics.MetricsLevel); Console.WriteLine("MinuteMetrics Retention Days : " + serviceProperties.MinuteMetrics.RetentionDays); Console.WriteLine("MinuteMetrics Version : " + serviceProperties.MinuteMetrics.Version); } finally { await queueClient.SetServicePropertiesAsync(orignalServiceProperties); } break; case 10: //adding and restoring CORS rules ServiceProperties orignalServicePropertiesCors = await queueClient.GetServicePropertiesAsync(); Console.WriteLine("Original service properties :"); Console.WriteLine("existing CORS count :" + orignalServicePropertiesCors.Cors.CorsRules.Count); try { Console.WriteLine(); Console.WriteLine("adding CORS Rules"); Console.WriteLine("AllowedHeaders = any"); Console.WriteLine("AllowedMethods = Get"); Console.WriteLine("AllowedOrigins = any"); Console.WriteLine("ExposedHeaders = any"); Console.WriteLine("MaxAgeInSeconds = 3600"); // * for any CorsRule corsRule = new CorsRule { AllowedHeaders = new List<string> { "*" }, AllowedMethods = CorsHttpMethods.Get, AllowedOrigins = new List<string> { "*" }, ExposedHeaders = new List<string> { "*" }, MaxAgeInSeconds = 3600 }; //change the service properties ServiceProperties serviceProperties = await queueClient.GetServicePropertiesAsync(); serviceProperties.Cors.CorsRules.Add(corsRule); Console.WriteLine("new CORS count :" + serviceProperties.Cors.CorsRules.Count); await queueClient.SetServicePropertiesAsync(serviceProperties); } finally { await queueClient.SetServicePropertiesAsync(orignalServicePropertiesCors); Console.WriteLine("restoring CORS rules :" + orignalServicePropertiesCors.Cors.CorsRules.Count); } break; case 11: //QUEUE MetaData string quName = "q-" + Guid.NewGuid(); Console.WriteLine("Setting queue metadata"); queue.Metadata.Add("key1", "value1"); queue.Metadata.Add("key2", "value2"); Console.WriteLine("Creating queue with name {0}", quName); await queue.CreateIfNotExistsAsync(); await queue.FetchAttributesAsync(); Console.WriteLine("Get queue metadata:"); foreach (var keyValue in queue.Metadata) { Console.WriteLine(" {0}: {1}", keyValue.Key, keyValue.Value); } Console.WriteLine("Deleting queue with name {0}", quName); queue.DeleteIfExists(); break; case 12: await queue.DeleteIfExistsAsync(); Environment.Exit(0); break; default: Environment.Exit(0); break; } Console.WriteLine(); Console.WriteLine("Select another option or press 0 to exit"); var newSelection = Console.ReadLine(); if (regex.IsMatch(newSelection.ToString())) { selection = Convert.ToInt32(newSelection); } else { Console.WriteLine("Please select a number"); Console.Clear(); await RunQueueStorageOperationsAsync(); } Console.WriteLine(); } } else { Console.WriteLine("Please select a number"); Console.Clear(); await RunQueueStorageOperationsAsync(); } }
public void CloudTableTestCorsMaxHeaders() { 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); } CloudTableClient client = GenerateCloudTableClient(); 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 void BlobServiceCorsTest() { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(context, handler); var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(context, handler); // Create resource group var rgName = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient); // Create storage account string accountName = TestUtilities.GenerateName("sto"); var parameters = StorageManagementTestUtilities.GetDefaultStorageAccountParameters(); var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters); StorageManagementTestUtilities.VerifyAccountProperties(account, true); // implement case try { BlobServiceProperties properties1 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName); BlobServiceProperties properties2 = new BlobServiceProperties(); properties2.DeleteRetentionPolicy = new DeleteRetentionPolicy(); properties2.DeleteRetentionPolicy.Enabled = true; properties2.DeleteRetentionPolicy.Days = 300; properties2.DefaultServiceVersion = "2017-04-17"; properties2.Cors = new CorsRules(); properties2.Cors.CorsRulesProperty = new List <CorsRule>(); properties2.Cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x-ms-meta-target*" }, AllowedMethods = new string[] { "GET", "HEAD", "POST", "OPTIONS", "MERGE", "PUT" }, AllowedOrigins = new string[] { "http://www.contoso.com", "http://www.fabrikam.com" }, ExposedHeaders = new string[] { "x-ms-meta-*" }, MaxAgeInSeconds = 100 }); properties2.Cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "*" }, AllowedMethods = new string[] { "GET" }, AllowedOrigins = new string[] { "*" }, ExposedHeaders = new string[] { "*" }, MaxAgeInSeconds = 2 }); properties2.Cors.CorsRulesProperty.Add(new CorsRule() { AllowedHeaders = new string[] { "x-ms-meta-12345675754564*" }, AllowedMethods = new string[] { "GET", "PUT", "CONNECT" }, AllowedOrigins = new string[] { "http://www.abc23.com", "https://www.fabrikam.com/*" }, ExposedHeaders = new string[] { "x-ms-meta-abc", "x-ms-meta-data*", "x -ms-meta-target*" }, MaxAgeInSeconds = 2000 }); BlobServiceProperties properties3 = storageMgmtClient.BlobServices.SetServiceProperties(rgName, accountName, properties2); Assert.True(properties3.DeleteRetentionPolicy.Enabled); Assert.Equal(300, properties3.DeleteRetentionPolicy.Days); Assert.Equal("2017-04-17", properties3.DefaultServiceVersion); //Validate CORS Rules Assert.Equal(properties2.Cors.CorsRulesProperty.Count, properties3.Cors.CorsRulesProperty.Count); for (int i = 0; i < properties2.Cors.CorsRulesProperty.Count; i++) { CorsRule putRule = properties2.Cors.CorsRulesProperty[i]; CorsRule getRule = properties3.Cors.CorsRulesProperty[i]; Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods); Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } BlobServiceProperties properties4 = storageMgmtClient.BlobServices.GetServiceProperties(rgName, accountName); Assert.True(properties4.DeleteRetentionPolicy.Enabled); Assert.Equal(300, properties4.DeleteRetentionPolicy.Days); Assert.Equal("2017-04-17", properties4.DefaultServiceVersion); //Validate CORS Rules Assert.Equal(properties2.Cors.CorsRulesProperty.Count, properties4.Cors.CorsRulesProperty.Count); for (int i = 0; i < properties2.Cors.CorsRulesProperty.Count; i++) { CorsRule putRule = properties2.Cors.CorsRulesProperty[i]; CorsRule getRule = properties4.Cors.CorsRulesProperty[i]; Assert.Equal(putRule.AllowedHeaders, getRule.AllowedHeaders); Assert.Equal(putRule.AllowedMethods, getRule.AllowedMethods); Assert.Equal(putRule.AllowedOrigins, getRule.AllowedOrigins); Assert.Equal(putRule.ExposedHeaders, getRule.ExposedHeaders); Assert.Equal(putRule.MaxAgeInSeconds, getRule.MaxAgeInSeconds); } } finally { // clean up storageMgmtClient.StorageAccounts.Delete(rgName, accountName); resourcesClient.ResourceGroups.Delete(rgName); } } }
internal void Init() { var version = Assembly.GetExecutingAssembly().GetName().Version; var container = "staticfiles"; var path = version.ToString().Replace(".", "_"); var http = HttpContext.Current; #if DEBUG path = "debug" + "/" + path; #endif if (string.IsNullOrEmpty(_endpoint)) { _endpoint = (_account.BlobEndpoint.AbsoluteUri.TrimEnd('/') + "/"); } _endpoint = _endpoint + container + "/" + path.TrimEnd('/'); var cli = _account.CreateCloudBlobClient(); var newProperties = CurrentProperties(cli); //Set service to new version: newProperties.DefaultServiceVersion = "2013-08-15"; //"2012-02-12"; // "2011-08-18"; // null; cli.SetServiceProperties(newProperties); var addRule = true; if (addRule) { //Add a wide open rule to allow uploads: var ruleWideOpenWriter = new CorsRule() { AllowedHeaders = { "*" }, AllowedOrigins = { "*" }, AllowedMethods = CorsHttpMethods.Options | CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Merge, ExposedHeaders = { "*" }, MaxAgeInSeconds = (int)TimeSpan.FromDays(5).TotalSeconds }; newProperties.Cors.CorsRules.Add(ruleWideOpenWriter); cli.SetServiceProperties(newProperties); } var cont = cli.GetContainerReference(container); cont.CreateIfNotExists(); cont.SetPermissions(new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions { PublicAccess = Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Blob }); var rootdir = http.Server.MapPath("~"); foreach (var folder in _folderstoupload) { var files = new DirectoryInfo(http.Server.MapPath(folder)).EnumerateFiles("*", SearchOption.AllDirectories); foreach (var file in files) { var loc = path + "/" + file.FullName.Replace(rootdir, "").Replace("\\", "/"); var blob = cont.GetBlockBlobReference(loc); blob.DeleteIfExists(); var fs = file.Open(FileMode.Open); blob.UploadFromStream(fs); fs.Dispose(); //blob.UploadFromFile(file.FullName, FileMode.Create); } } }
internal void Init() { var version = Assembly.GetExecutingAssembly().GetName().Version; var container = "staticfiles"; var path = version.ToString().Replace(".", "_"); var http = HttpContext.Current; #if DEBUG path = "debug" + "/" + path; #endif if (string.IsNullOrEmpty(_endpoint)) { _endpoint = (_account.BlobEndpoint.AbsoluteUri.TrimEnd('/') + "/"); } _endpoint = _endpoint + container + "/" + path.TrimEnd('/'); var cli = _account.CreateCloudBlobClient(); var newProperties = CurrentProperties(cli); //Set service to new version: newProperties.DefaultServiceVersion = "2013-08-15"; //"2012-02-12"; // "2011-08-18"; // null; cli.SetServiceProperties(newProperties); var addRule = true; if (addRule) { //Add a wide open rule to allow uploads: var ruleWideOpenWriter = new CorsRule() { AllowedHeaders = { "*" }, AllowedOrigins = { "*" }, AllowedMethods = CorsHttpMethods.Options | CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Merge, ExposedHeaders = { "*" }, MaxAgeInSeconds = (int)TimeSpan.FromDays(5).TotalSeconds }; newProperties.Cors.CorsRules.Add(ruleWideOpenWriter); cli.SetServiceProperties(newProperties); } var cont = cli.GetContainerReference(container); cont.CreateIfNotExists(); cont.SetPermissions(new Microsoft.WindowsAzure.Storage.Blob.BlobContainerPermissions { PublicAccess = Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType.Blob }); var rootdir = http.Server.MapPath("~"); foreach (var folder in _folderstoupload) { var files = new DirectoryInfo(http.Server.MapPath(folder)).EnumerateFiles("*", SearchOption.AllDirectories); foreach (var file in files) { var loc = path + "/" + file.FullName.Replace(rootdir, "").Replace("\\", "/"); var blob = cont.GetBlockBlobReference(loc); blob.DeleteIfExists(); var fs = file.Open(FileMode.Open); blob.UploadFromStream(fs); fs.Dispose(); //blob.UploadFromFile(file.FullName, FileMode.Create); } } }