public async Task SetPropertiesAsync_ExistingProperties() { // Arrange QueueServiceClient service = GetServiceClient_SharedKey(); QueueServiceProperties properties = await service.GetPropertiesAsync(); QueueCorsRule[] originalCors = properties.Cors.ToArray(); properties.Cors = new[] { new QueueCorsRule { MaxAgeInSeconds = 1000, AllowedHeaders = "x-ms-meta-data*,x-ms-meta-target*,x-ms-meta-abc", AllowedMethods = "PUT,GET", AllowedOrigins = "*", ExposedHeaders = "x-ms-meta-*" } }; // Act await service.SetPropertiesAsync(properties); // Assert properties = await service.GetPropertiesAsync(); Assert.AreEqual(1, properties.Cors.Count()); Assert.IsTrue(properties.Cors[0].MaxAgeInSeconds == 1000); // Cleanup properties.Cors = originalCors; await service.SetPropertiesAsync(properties); properties = await service.GetPropertiesAsync(); Assert.AreEqual(originalCors.Count(), properties.Cors.Count()); }
/// <summary> /// Sets the properties of the queue service. /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties"/>. /// </summary> /// <param name="properties"> /// <see cref="QueueServiceProperties"/> /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// <see cref="CancellationToken"/> /// </param> /// <returns> /// <see cref="Response"/> /// </returns> private async Task <Response> SetPropertiesInternal( QueueServiceProperties properties, bool async, CancellationToken cancellationToken) { using (Pipeline.BeginLoggingScope(nameof(QueueServiceClient))) { Pipeline.LogMethodEnter( nameof(QueueServiceClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(properties)}: {properties}"); try { return(await QueueRestClient.Service.SetPropertiesAsync( ClientDiagnostics, Pipeline, Uri, properties : properties, version : Version.ToVersionString(), async : async, cancellationToken : cancellationToken) .ConfigureAwait(false)); } catch (Exception ex) { Pipeline.LogException(ex); throw; } finally { Pipeline.LogMethodExit(nameof(QueueServiceClient)); } } }
//------------------------------------------------- // Enable diagnostic logs //------------------------------------------------- public void EnableDiagnosticLogs() { var connectionString = Constants.connectionString; // <Snippet_EnableDiagnosticLogs> QueueServiceClient queueServiceClient = new QueueServiceClient(connectionString); QueueServiceProperties serviceProperties = queueServiceClient.GetProperties().Value; serviceProperties.Logging.Delete = true; QueueRetentionPolicy retentionPolicy = new QueueRetentionPolicy(); retentionPolicy.Enabled = true; retentionPolicy.Days = 2; serviceProperties.Logging.RetentionPolicy = retentionPolicy; serviceProperties.HourMetrics = null; serviceProperties.MinuteMetrics = null; serviceProperties.Cors = null; queueServiceClient.SetProperties(serviceProperties); // </Snippet_EnableDiagnosticLogs> Console.WriteLine("Diagnostic logs are now enabled"); }
internal HttpMessage CreateSetPropertiesRequest(QueueServiceProperties storageServiceProperties, int?timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.AppendRaw(_url, false); uri.AppendPath("/", false); uri.AppendQuery("restype", "service", true); uri.AppendQuery("comp", "properties", true); if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", _version); request.Headers.Add("Accept", "application/xml"); request.Headers.Add("Content-Type", "application/xml"); var content = new XmlWriterContent(); content.XmlWriter.WriteObjectValue(storageServiceProperties, "StorageServiceProperties"); request.Content = content; return(message); }
/// <summary> /// Sets the properties of the queue service. /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties"/>. /// </summary> /// <param name="properties"> /// <see cref="QueueServiceProperties"/> /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// <see cref="CancellationToken"/> /// </param> /// <returns> /// <see cref="Task{Response}"/> /// </returns> private async Task <Response> SetPropertiesAsync( QueueServiceProperties properties, bool async, CancellationToken cancellationToken) { using (this.Pipeline.BeginLoggingScope(nameof(QueueServiceClient))) { this.Pipeline.LogMethodEnter( nameof(QueueServiceClient), message: $"{nameof(this.Uri)}: {this.Uri}\n" + $"{nameof(properties)}: {properties}"); try { return(await QueueRestClient.Service.SetPropertiesAsync( this.Pipeline, this.Uri, properties : properties, async : async, cancellationToken : cancellationToken) .ConfigureAwait(false)); } catch (Exception ex) { this.Pipeline.LogException(ex); throw; } finally { this.Pipeline.LogMethodExit(nameof(QueueServiceClient)); } } }
/// <summary> /// Sets the properties of the queue service. /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties"/>. /// </summary> /// <param name="properties"> /// <see cref="QueueServiceProperties"/> /// </param> /// <param name="cancellationToken"> /// <see cref="CancellationToken"/> /// </param> /// <returns> /// <see cref="Response"/> /// </returns> public virtual Response SetProperties( QueueServiceProperties properties, CancellationToken cancellationToken = default) => this.SetPropertiesAsync( properties, false, // async cancellationToken) .EnsureCompleted();
/// <summary> /// Sets the properties of the queue service. /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties"/>. /// </summary> /// <param name="properties"> /// <see cref="QueueServiceProperties"/> /// </param> /// <param name="cancellationToken"> /// <see cref="CancellationToken"/> /// </param> /// <returns> /// <see cref="Task{Response}"/> /// </returns> public virtual async Task <Response> SetPropertiesAsync( QueueServiceProperties properties, CancellationToken cancellationToken = default) => await this.SetPropertiesAsync( properties, true, // async cancellationToken) .ConfigureAwait(false);
/// <summary> /// Sets the properties of the queue service. /// /// For more information, see /// <see href="https://docs.microsoft.com/rest/api/storageservices/set-queue-service-properties"> /// Set Queue Service Properties</see>. /// </summary> /// <param name="properties"> /// <see cref="QueueServiceProperties"/> /// </param> /// <param name="async"> /// Whether to invoke the operation asynchronously. /// </param> /// <param name="cancellationToken"> /// <see cref="CancellationToken"/> /// </param> /// <returns> /// <see cref="Response"/> /// </returns> private async Task <Response> SetPropertiesInternal( QueueServiceProperties properties, bool async, CancellationToken cancellationToken) { using (ClientConfiguration.Pipeline.BeginLoggingScope(nameof(QueueServiceClient))) { ClientConfiguration.Pipeline.LogMethodEnter( nameof(QueueServiceClient), message: $"{nameof(Uri)}: {Uri}\n" + $"{nameof(properties)}: {properties}"); DiagnosticScope scope = ClientConfiguration.ClientDiagnostics.CreateScope($"{nameof(QueueServiceClient)}.{nameof(SetProperties)}"); try { ResponseWithHeaders <ServiceSetPropertiesHeaders> response; scope.Start(); if (async) { response = await _serviceRestClient.SetPropertiesAsync( storageServiceProperties : properties, cancellationToken : cancellationToken) .ConfigureAwait(false); } else { response = _serviceRestClient.SetProperties( storageServiceProperties: properties, cancellationToken: cancellationToken); } return(response.GetRawResponse()); } catch (Exception ex) { ClientConfiguration.Pipeline.LogException(ex); scope.Failed(ex); throw; } finally { ClientConfiguration.Pipeline.LogMethodExit(nameof(QueueServiceClient)); scope.Dispose(); } } }
public async Task SetPropertiesAsync_Error() { // Arrange QueueServiceClient service = GetServiceClient_SharedKey(); QueueServiceProperties properties = (await service.GetPropertiesAsync()).Value; QueueServiceClient invalidService = InstrumentClient( new QueueServiceClient( GetServiceClient_SharedKey().Uri, GetOptions())); // Act await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>( invalidService.SetPropertiesAsync(properties), e => { }); }
public async Task Ctor_AzureSasCredential() { // Arrange string sas = GetNewAccountSasCredentials(resourceTypes: AccountSasResourceTypes.Service).ToString(); await using DisposingQueue test = await GetTestQueueAsync(); Uri uri = GetServiceClient_SharedKey().Uri; // Act var sasClient = InstrumentClient(new QueueServiceClient(uri, new AzureSasCredential(sas), GetOptions())); QueueServiceProperties properties = await sasClient.GetPropertiesAsync(); // Assert Assert.IsNotNull(properties); }
public ResponseWithHeaders <ServiceSetPropertiesHeaders> SetProperties(QueueServiceProperties storageServiceProperties, int?timeout = null, CancellationToken cancellationToken = default) { if (storageServiceProperties == null) { throw new ArgumentNullException(nameof(storageServiceProperties)); } using var message = CreateSetPropertiesRequest(storageServiceProperties, timeout); _pipeline.Send(message, cancellationToken); var headers = new ServiceSetPropertiesHeaders(message.Response); switch (message.Response.Status) { case 202: return(ResponseWithHeaders.FromValue(headers, message.Response)); default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } }
//------------------------------------------------- // Update log retention period //------------------------------------------------- public void UpdateLogRetentionPeriod() { var connectionString = Constants.connectionString; // <Snippet_ViewRetentionPeriod> BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); QueueServiceClient queueServiceClient = new QueueServiceClient(connectionString); BlobServiceProperties blobServiceProperties = blobServiceClient.GetProperties().Value; QueueServiceProperties queueServiceProperties = queueServiceClient.GetProperties().Value; Console.WriteLine("Retention period for logs from the blob service is: " + blobServiceProperties.Logging.RetentionPolicy.Days.ToString()); Console.WriteLine("Retention period for logs from the queue service is: " + queueServiceProperties.Logging.RetentionPolicy.Days.ToString()); // </Snippet_ViewRetentionPeriod> // <Snippet_ModifyRetentionPeriod> BlobRetentionPolicy blobRetentionPolicy = new BlobRetentionPolicy(); blobRetentionPolicy.Enabled = true; blobRetentionPolicy.Days = 4; QueueRetentionPolicy queueRetentionPolicy = new QueueRetentionPolicy(); queueRetentionPolicy.Enabled = true; queueRetentionPolicy.Days = 4; blobServiceProperties.Logging.RetentionPolicy = blobRetentionPolicy; blobServiceProperties.Cors = null; queueServiceProperties.Logging.RetentionPolicy = queueRetentionPolicy; queueServiceProperties.Cors = null; blobServiceClient.SetProperties(blobServiceProperties); queueServiceClient.SetProperties(queueServiceProperties); Console.WriteLine("Retention policy for blobs and queues is updated"); // </Snippet_ModifyRetentionPeriod> }
public async Task SetPropertiesAsync() { // Arrange QueueServiceClient service = GetServiceClient_SharedKey(); QueueServiceProperties originalProperties = await service.GetPropertiesAsync(); QueueServiceProperties properties = GetQueueServiceProperties(); // Act await service.SetPropertiesAsync(properties); // Assert QueueServiceProperties responseProperties = await service.GetPropertiesAsync(); Assert.AreEqual(properties.Cors.Count, responseProperties.Cors.Count); Assert.AreEqual(properties.Cors[0].AllowedHeaders, responseProperties.Cors[0].AllowedHeaders); Assert.AreEqual(properties.Cors[0].AllowedMethods, responseProperties.Cors[0].AllowedMethods); Assert.AreEqual(properties.Cors[0].AllowedOrigins, responseProperties.Cors[0].AllowedOrigins); Assert.AreEqual(properties.Cors[0].ExposedHeaders, responseProperties.Cors[0].ExposedHeaders); Assert.AreEqual(properties.Cors[0].MaxAgeInSeconds, responseProperties.Cors[0].MaxAgeInSeconds); Assert.AreEqual(properties.Logging.Read, responseProperties.Logging.Read); Assert.AreEqual(properties.Logging.Write, responseProperties.Logging.Write); Assert.AreEqual(properties.Logging.Delete, responseProperties.Logging.Delete); Assert.AreEqual(properties.Logging.Version, responseProperties.Logging.Version); Assert.AreEqual(properties.Logging.RetentionPolicy.Days, responseProperties.Logging.RetentionPolicy.Days); Assert.AreEqual(properties.Logging.RetentionPolicy.Enabled, responseProperties.Logging.RetentionPolicy.Enabled); Assert.AreEqual(properties.HourMetrics.Enabled, responseProperties.HourMetrics.Enabled); Assert.AreEqual(properties.HourMetrics.IncludeApis, responseProperties.HourMetrics.IncludeApis); Assert.AreEqual(properties.HourMetrics.Version, responseProperties.HourMetrics.Version); Assert.AreEqual(properties.HourMetrics.RetentionPolicy.Days, responseProperties.HourMetrics.RetentionPolicy.Days); Assert.AreEqual(properties.HourMetrics.RetentionPolicy.Enabled, responseProperties.HourMetrics.RetentionPolicy.Enabled); Assert.AreEqual(properties.MinuteMetrics.Enabled, responseProperties.MinuteMetrics.Enabled); Assert.AreEqual(properties.MinuteMetrics.IncludeApis, responseProperties.MinuteMetrics.IncludeApis); Assert.AreEqual(properties.MinuteMetrics.Version, responseProperties.MinuteMetrics.Version); Assert.AreEqual(properties.MinuteMetrics.RetentionPolicy.Days, responseProperties.MinuteMetrics.RetentionPolicy.Days); Assert.AreEqual(properties.MinuteMetrics.RetentionPolicy.Enabled, responseProperties.MinuteMetrics.RetentionPolicy.Enabled); // Clean Up await service.SetPropertiesAsync(originalProperties); }
public ResponseWithHeaders <QueueServiceProperties, ServiceGetPropertiesHeaders> GetProperties(int?timeout = null, CancellationToken cancellationToken = default) { using var message = CreateGetPropertiesRequest(timeout); _pipeline.Send(message, cancellationToken); var headers = new ServiceGetPropertiesHeaders(message.Response); switch (message.Response.Status) { case 200: { QueueServiceProperties value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("StorageServiceProperties") is XElement storageServicePropertiesElement) { value = QueueServiceProperties.DeserializeQueueServiceProperties(storageServicePropertiesElement); } return(ResponseWithHeaders.FromValue(value, headers, message.Response)); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } }
/// <summary> /// Sets the properties of a storage account’s Queue service, including /// properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) /// rules. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. The name is /// case insensitive. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cors'> /// Specifies CORS rules for the Queue service. You can include up to five /// CorsRule elements in the request. If no CorsRule elements are included in /// the request body, all CORS rules will be deleted, and CORS will be disabled /// for the Queue service. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <QueueServiceProperties> > SetServicePropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, CorsRules cors = default(CorsRules), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new ValidationException(ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "accountName", 3); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ApiVersion != null) { if (Client.ApiVersion.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } string queueServiceName = "default"; QueueServiceProperties parameters = new QueueServiceProperties(); if (cors != null) { parameters.Cors = cors; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("queueServiceName", queueServiceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "SetServiceProperties", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/{queueServiceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{queueServiceName}", System.Uri.EscapeDataString(queueServiceName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <QueueServiceProperties>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <QueueServiceProperties>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void QueueServiceCorsTest() { 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 = "centraluseuap", Kind = Kind.StorageV2, Sku = new Sku { Name = SkuName.StandardLRS } }; var account = storageMgmtClient.StorageAccounts.Create(rgName, accountName, parameters); // implement case try { QueueServiceProperties properties1 = storageMgmtClient.QueueServices.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 }); QueueServiceProperties properties3 = storageMgmtClient.QueueServices.SetServiceProperties(rgName, accountName, cors); //Validate CORS Rules 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); } QueueServiceProperties properties4 = storageMgmtClient.QueueServices.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); } } }
public virtual Response <QueueServiceProperties> SetServiceProperties(string resourceGroupName, string accountName, QueueServiceProperties parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("QueueServicesOperations.SetServiceProperties"); scope.Start(); try { return(RestClient.SetServiceProperties(resourceGroupName, accountName, parameters, cancellationToken)); } catch (Exception e) { scope.Failed(e); throw; } }
public virtual async Task <Response <QueueServiceProperties> > SetServicePropertiesAsync(string resourceGroupName, string accountName, QueueServiceProperties parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("QueueServicesClient.SetServiceProperties"); scope.Start(); try { return(await RestClient.SetServicePropertiesAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }