private void CompareTableServiceProperties(TableServiceProperties expected, TableServiceProperties actual) { Assert.AreEqual(expected.Logging.Read, actual.Logging.Read); Assert.AreEqual(expected.Logging.Version, actual.Logging.Version); Assert.AreEqual(expected.Logging.Write, actual.Logging.Write); Assert.AreEqual(expected.Logging.Delete, actual.Logging.Delete); Assert.AreEqual(expected.Logging.RetentionPolicy.Enabled, actual.Logging.RetentionPolicy.Enabled); Assert.AreEqual(expected.Logging.RetentionPolicy.Days, actual.Logging.RetentionPolicy.Days); Assert.AreEqual(expected.HourMetrics.Enabled, actual.HourMetrics.Enabled); Assert.AreEqual(expected.HourMetrics.Version, actual.HourMetrics.Version); Assert.AreEqual(expected.HourMetrics.IncludeAPIs, actual.HourMetrics.IncludeAPIs); Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Enabled, actual.HourMetrics.RetentionPolicy.Enabled); Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Days, actual.HourMetrics.RetentionPolicy.Days); Assert.AreEqual(expected.MinuteMetrics.Enabled, actual.MinuteMetrics.Enabled); Assert.AreEqual(expected.MinuteMetrics.Version, actual.MinuteMetrics.Version); Assert.AreEqual(expected.MinuteMetrics.IncludeAPIs, actual.MinuteMetrics.IncludeAPIs); Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Enabled, actual.MinuteMetrics.RetentionPolicy.Enabled); Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Days, actual.MinuteMetrics.RetentionPolicy.Days); Assert.AreEqual(expected.Cors.Count, actual.Cors.Count); for (int i = 0; i < expected.Cors.Count; i++) { CorsRule expectedRule = expected.Cors[i]; CorsRule actualRule = actual.Cors[i]; Assert.AreEqual(expectedRule.AllowedHeaders, actualRule.AllowedHeaders); Assert.AreEqual(expectedRule.AllowedMethods, actualRule.AllowedMethods); Assert.AreEqual(expectedRule.AllowedOrigins, actualRule.AllowedOrigins); Assert.AreEqual(expectedRule.MaxAgeInSeconds, actualRule.MaxAgeInSeconds); Assert.AreEqual(expectedRule.ExposedHeaders, actualRule.ExposedHeaders); } }
internal HttpMessage CreateSetPropertiesRequest(TableServiceProperties tableServiceProperties, 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("Content-Type", "application/xml"); request.Headers.Add("Accept", "application/xml"); var content = new XmlWriterContent(); content.XmlWriter.WriteObjectValue(tableServiceProperties, "StorageServiceProperties"); request.Content = content; return(message); }
public async Task GetPropertiesReturnsProperties() { // Get current properties TableServiceProperties responseToChange = await service.GetPropertiesAsync().ConfigureAwait(false); // Change a property responseToChange.Logging.Read = !responseToChange.Logging.Read; // Set properties to the changed one await service.SetPropertiesAsync(responseToChange).ConfigureAwait(false); // Get configured properties // A delay is required to ensure properties are updated in the service TableServiceProperties changedResponse = await RetryUntilExpectedResponse( async() => await service.GetPropertiesAsync().ConfigureAwait(false), result => result.Value.Logging.Read == responseToChange.Logging.Read, 15000).ConfigureAwait(false); // Test each property CompareServiceProperties(responseToChange, changedResponse); }
public async Task GetPropertiesReturnsProperties() { if (_endpointType == TableEndpointType.CosmosTable) { Assert.Ignore("GetProperties is currently not supported by Cosmos endpoints."); } // Get current properties TableServiceProperties responseToChange = await service.GetPropertiesAsync().ConfigureAwait(false); // Change a property responseToChange.Logging.Read = !responseToChange.Logging.Read; // Set properties to the changed one await service.SetPropertiesAsync(responseToChange).ConfigureAwait(false); // Wait 20 sec if on Live mode to ensure properties are updated in the service // Minimum time: Sync - 20 sec; Async - 12 sec if (Mode != RecordedTestMode.Playback) { await Task.Delay(20000); } // Get configured properties TableServiceProperties changedResponse = await service.GetPropertiesAsync().ConfigureAwait(false); // Test each property CompareTableServiceProperties(responseToChange, changedResponse); }
public async Task GetPropertiesReturnsProperties() { if (_endpointType == TableEndpointType.CosmosTable) { Assert.Ignore("GetProperties is currently not supported by Cosmos endpoints."); } // Get current properties TableServiceProperties responseToChange = await service.GetPropertiesAsync().ConfigureAwait(false); // Change a property responseToChange.Logging.Read = !responseToChange.Logging.Read; // Set properties to the changed one await service.SetPropertiesAsync(responseToChange).ConfigureAwait(false); // Get configured properties // A delay is required to ensure properties are updated in the service TableServiceProperties changedResponse = await RetryUntilExpectedResponse( async() => await service.GetPropertiesAsync().ConfigureAwait(false), result => result.Value.Logging.Read == responseToChange.Logging.Read, 15000).ConfigureAwait(false); // Test each property CompareServiceProperties(responseToChange, changedResponse); }
public override void ExecuteCmdlet() { if (StorageServiceType.File == ServiceType) { throw new PSInvalidOperationException(Resources.FileNotSupportLogging); } if (ServiceType != StorageServiceType.Table) { ServiceProperties serviceProperties = Channel.GetStorageServiceProperties(ServiceType, GetRequestOptions(ServiceType), OperationContext); // Premium Account not support classic metrics and logging if (serviceProperties.Logging == null) { AccountProperties accountProperties = Channel.GetAccountProperties(); if (accountProperties.SkuName.Contains("Premium")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "This Storage account doesn't support Classic Logging, since it’s a Premium Storage account: {0}", Channel.StorageContext.StorageAccountName)); } } WriteObject(serviceProperties.Logging); } else //Table use old XSCL { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); if (!tableChannel.IsTokenCredential) { XTable.ServiceProperties serviceProperties = tableChannel.GetStorageTableServiceProperties(GetTableRequestOptions(), TableOperationContext); // Premium Account not support classic metrics and logging if (serviceProperties.Logging == null) { AccountProperties accountProperties = Channel.GetAccountProperties(); if (accountProperties.SkuName.Contains("Premium")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "This Storage account doesn't support Classic Logging, since it’s a Premium Storage account: {0}", Channel.StorageContext.StorageAccountName)); } } WriteObject(serviceProperties.Logging); } else { TableServiceProperties serviceProperties = tableChannel.GetProperties(this.CmdletCancellationToken); // Premium Account does not support classic metrics and logging if (serviceProperties.Logging == null) { this.ThrowIfPremium("This Storage account doesn't support Classic Logging, since it’s a Premium Storage account: {0}"); } WriteObject(PSSeriviceProperties.ConvertLoggingProperties(serviceProperties.Logging)); } } }
// // Summary: // Initializes a new instance of the PSSeriviceProperties class from track 2 service properties. public PSSeriviceProperties(TableServiceProperties properties) { if (properties != null) { this.Logging = PSSeriviceProperties.ConvertLoggingProperties(properties.Logging); this.HourMetrics = PSSeriviceProperties.ConvertMetricsProperties(properties.HourMetrics); this.MinuteMetrics = PSSeriviceProperties.ConvertMetricsProperties(properties.MinuteMetrics); this.DefaultServiceVersion = string.Empty; this.Cors = PSCorsRule.ParseCorsRules(properties.Cors); } }
public virtual Response SetProperties(TableServiceProperties tableServiceProperties, int?timeout = null, string requestId = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ServiceClient.SetProperties"); scope.Start(); try { return(RestClient.SetProperties(tableServiceProperties, timeout, requestId, cancellationToken).GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="tableServiceProperties"> The Table Service properties. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response SetProperties(TableServiceProperties tableServiceProperties, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}"); scope.Start(); try { return(_serviceOperations.SetProperties(tableServiceProperties, cancellationToken: cancellationToken)); } catch (Exception ex) { scope.Failed(ex); throw; } }
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="tableServiceProperties"> The Table Service properties. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task <Response> SetPropertiesAsync(TableServiceProperties tableServiceProperties, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}"); scope.Start(); try { return(await _serviceOperations.SetPropertiesAsync(tableServiceProperties, cancellationToken : cancellationToken).ConfigureAwait(false)); } catch (Exception ex) { scope.Failed(ex); throw; } }
public ResponseWithHeaders <ServiceSetPropertiesHeaders> SetProperties(TableServiceProperties tableServiceProperties, int?timeout = null, CancellationToken cancellationToken = default) { if (tableServiceProperties == null) { throw new ArgumentNullException(nameof(tableServiceProperties)); } using var message = CreateSetPropertiesRequest(tableServiceProperties, 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); } }
public ResponseWithHeaders <TableServiceProperties, 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: { TableServiceProperties value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("StorageServiceProperties") is XElement storageServicePropertiesElement) { value = TableServiceProperties.DeserializeTableServiceProperties(storageServicePropertiesElement); } return(ResponseWithHeaders.FromValue(value, headers, message.Response)); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } }
public override void ExecuteCmdlet() { if (ServiceType != StorageServiceType.Table) { ServiceProperties serviceProperties = Channel.GetStorageServiceProperties(ServiceType, GetRequestOptions(ServiceType), OperationContext); WriteObject(new PSSeriviceProperties(serviceProperties)); } else //Table use old XSCL { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); if (!tableChannel.IsTokenCredential) { XTable.ServiceProperties serviceProperties = tableChannel.GetStorageTableServiceProperties(GetTableRequestOptions(), TableOperationContext); WriteObject(new PSSeriviceProperties(serviceProperties)); } else { TableServiceProperties serviceProperties = tableChannel.GetProperties(this.CmdletCancellationToken); WriteObject(new PSSeriviceProperties(serviceProperties)); } } }
public override void ExecuteCmdlet() { if (ServiceType != StorageServiceType.Table) { ServiceProperties currentServiceProperties = Channel.GetStorageServiceProperties(ServiceType, GetRequestOptions(ServiceType), OperationContext); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.Clean(); serviceProperties.Cors = currentServiceProperties.Cors; serviceProperties.Cors.CorsRules.Clear(); Channel.SetStorageServiceProperties(ServiceType, serviceProperties, GetRequestOptions(ServiceType), OperationContext); } else //Table use old XSCL { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); if (!tableChannel.IsTokenCredential) { XTable.ServiceProperties currentServiceProperties = tableChannel.GetStorageTableServiceProperties(GetTableRequestOptions(), TableOperationContext); XTable.ServiceProperties serviceProperties = new XTable.ServiceProperties(); serviceProperties.Clean(); serviceProperties.Cors = currentServiceProperties.Cors; serviceProperties.Cors.CorsRules.Clear(); tableChannel.SetStorageTableServiceProperties(serviceProperties, GetTableRequestOptions(), TableOperationContext); } else { TableServiceProperties serviceProperties = tableChannel.GetProperties(this.CmdletCancellationToken); serviceProperties.Cors.Clear(); tableChannel.SetProperties(serviceProperties, this.CmdletCancellationToken); } } }
public async Task <ResponseWithHeaders <TableServiceProperties, ServiceGetPropertiesHeaders> > GetPropertiesAsync(int?timeout = null, string requestId = null, CancellationToken cancellationToken = default) { using var message = CreateGetPropertiesRequest(timeout, requestId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new ServiceGetPropertiesHeaders(message.Response); switch (message.Response.Status) { case 200: { TableServiceProperties value = default; var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace); if (document.Element("TableServiceProperties") is XElement tableServicePropertiesElement) { value = TableServiceProperties.DeserializeTableServiceProperties(tableServicePropertiesElement); } return(ResponseWithHeaders.FromValue(value, headers, message.Response)); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } }
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 } }; 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); } } }
/// <summary> /// Sets the properties of a storage account’s Table 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 Table 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 Table 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 <TableServiceProperties> > 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 tableServiceName = "default"; TableServiceProperties parameters = new TableServiceProperties(); 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("tableServiceName", tableServiceName); 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}/tableServices/{tableServiceName}").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("{tableServiceName}", System.Uri.EscapeDataString(tableServiceName)); 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 <TableServiceProperties>(); _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 <TableServiceProperties>(_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); }
/// <summary> /// Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. /// </summary> /// <param name="properties">The Table Service properties.</param> /// <param name="cancellationToken">A CancellationToken controlling the request lifetime.</param> /// <returns></returns> public Response SetProperties(TableServiceProperties properties, CancellationToken cancellationToken) { this.EnsureTableServiceClient(); return(this.tableServiceClient.SetProperties(properties, cancellationToken)); }
public async Task <ResponseWithHeaders <ServiceSetPropertiesHeaders> > SetPropertiesAsync(TableServiceProperties tableServiceProperties, int?timeout = null, string requestId = null, CancellationToken cancellationToken = default) { if (tableServiceProperties == null) { throw new ArgumentNullException(nameof(tableServiceProperties)); } using var message = CreateSetPropertiesRequest(tableServiceProperties, timeout, requestId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); var headers = new ServiceSetPropertiesHeaders(message.Response); switch (message.Response.Status) { case 202: return(ResponseWithHeaders.FromValue(headers, message.Response)); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } }
public virtual Response <TableServiceProperties> SetServiceProperties(string resourceGroupName, string accountName, TableServiceProperties parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("TableServicesOperations.SetServiceProperties"); scope.Start(); try { return(RestClient.SetServiceProperties(resourceGroupName, accountName, parameters, cancellationToken)); } catch (Exception e) { scope.Failed(e); throw; } }
public override void ExecuteCmdlet() { if (ServiceType != StorageServiceType.Table) { ServiceProperties currentServiceProperties = Channel.GetStorageServiceProperties(ServiceType, GetRequestOptions(ServiceType), OperationContext); // Premium Account not support classic metrics and logging if ((MetricsType == ServiceMetricsType.Hour && currentServiceProperties.HourMetrics == null) || (MetricsType == ServiceMetricsType.Minute && currentServiceProperties.MinuteMetrics == null)) { AccountProperties accountProperties = Channel.GetAccountProperties(); if (accountProperties.SkuName.Contains("Premium")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "This Storage account doesn't support Classic Metrics, since it’s a Premium Storage account: {0}", Channel.StorageContext.StorageAccountName)); } } ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.Clean(); bool isHourMetrics = false; switch (MetricsType) { case ServiceMetricsType.Hour: serviceProperties.HourMetrics = currentServiceProperties.HourMetrics; UpdateServiceProperties(serviceProperties.HourMetrics); isHourMetrics = true; break; case ServiceMetricsType.Minute: serviceProperties.MinuteMetrics = currentServiceProperties.MinuteMetrics; UpdateServiceProperties(serviceProperties.MinuteMetrics); isHourMetrics = false; break; } Channel.SetStorageServiceProperties(ServiceType, serviceProperties, GetRequestOptions(ServiceType), OperationContext); if (PassThru) { if (isHourMetrics) { WriteObject(serviceProperties.HourMetrics); } else { WriteObject(serviceProperties.MinuteMetrics); } } } else //Table use old XSCL { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); if (!tableChannel.IsTokenCredential) { XTable.ServiceProperties currentServiceProperties = tableChannel.GetStorageTableServiceProperties(GetTableRequestOptions(), TableOperationContext); // Premium Account not support classic metrics and logging if ((MetricsType == ServiceMetricsType.Hour && currentServiceProperties.HourMetrics == null) || (MetricsType == ServiceMetricsType.Minute && currentServiceProperties.MinuteMetrics == null)) { AccountProperties accountProperties = Channel.GetAccountProperties(); if (accountProperties.SkuName.Contains("Premium")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "This Storage account doesn't support Classic Metrics, since it’s a Premium Storage account: {0}", Channel.StorageContext.StorageAccountName)); } } XTable.ServiceProperties serviceProperties = new XTable.ServiceProperties(); serviceProperties.Clean(); bool isHourMetrics = false; switch (MetricsType) { case ServiceMetricsType.Hour: serviceProperties.HourMetrics = currentServiceProperties.HourMetrics; UpdateServiceProperties(serviceProperties.HourMetrics); isHourMetrics = true; break; case ServiceMetricsType.Minute: serviceProperties.MinuteMetrics = currentServiceProperties.MinuteMetrics; UpdateServiceProperties(serviceProperties.MinuteMetrics); isHourMetrics = false; break; } tableChannel.SetStorageTableServiceProperties(serviceProperties, GetTableRequestOptions(), TableOperationContext); if (PassThru) { if (isHourMetrics) { WriteObject(serviceProperties.HourMetrics); } else { WriteObject(serviceProperties.MinuteMetrics); } } } else { TableServiceProperties serviceProperties = tableChannel.GetProperties(this.CmdletCancellationToken); // Premium Account not support classic metrics and logging if ((MetricsType == ServiceMetricsType.Hour && serviceProperties.HourMetrics == null) || (MetricsType == ServiceMetricsType.Minute && serviceProperties.MinuteMetrics == null)) { this.ThrowIfPremium("This Storage account doesn't support Classic Metrics, since it’s a Premium Storage account: {0}"); } switch (MetricsType) { case ServiceMetricsType.Hour: UpdateServiceProperties(serviceProperties.HourMetrics); break; case ServiceMetricsType.Minute: UpdateServiceProperties(serviceProperties.MinuteMetrics); break; default: throw new ArgumentException($"Unsupported metrics type {MetricsType}"); } tableChannel.SetProperties(serviceProperties, this.CmdletCancellationToken); if (PassThru) { WriteObject(PSSeriviceProperties.ConvertMetricsProperties(MetricsType == ServiceMetricsType.Hour ? serviceProperties.HourMetrics : serviceProperties.MinuteMetrics)); } } } }
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 { StorageTableManagement tableChannel = new StorageTableManagement(Channel.StorageContext); if (!tableChannel.IsTokenCredential) { 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 { 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; } } } else { TableServiceProperties serviceProperties = tableChannel.GetProperties(this.CmdletCancellationToken); serviceProperties.Cors.Clear(); foreach (PSCorsRule corsRule in this.CorsRules) { serviceProperties.Cors.Add(new TableCorsRule( corsRule.AllowedOrigins == null ? string.Empty : string.Join(",", corsRule.AllowedOrigins), this.CheckAndJoinAllowedMethods(corsRule.AllowedMethods), corsRule.AllowedHeaders == null ? string.Empty : string.Join(",", corsRule.AllowedHeaders), corsRule.ExposedHeaders == null ? string.Empty : string.Join(",", corsRule.ExposedHeaders), corsRule.MaxAgeInSeconds)); } try { tableChannel.SetProperties(serviceProperties, this.CmdletCancellationToken); } catch (RequestFailedException ex) { this.WriteExceptionError(ex); throw new InvalidOperationException(Resources.CORSRuleError); } } } if (PassThru) { WriteObject(this.CorsRules); } }
public virtual async Task <Response <TableServiceProperties> > SetServicePropertiesAsync(string resourceGroupName, string accountName, TableServiceProperties parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("TableServicesClient.SetServiceProperties"); scope.Start(); try { return(await RestClient.SetServicePropertiesAsync(resourceGroupName, accountName, parameters, cancellationToken).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. /// </summary> /// <param name="properties">The Table Service properties.</param> /// <param name="cancellationToken">A CancellationToken controlling the request lifetime.</param> /// <returns></returns> public Response SetProperties(TableServiceProperties properties, CancellationToken cancellationToken) { throw new NotImplementedException(); }