public void ODataQuerySupportsEmptyState() { var query = new ODataQuery <Param1>(); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.Foo == null); Assert.Equal("", query.ToString()); var param = new InputParam1 { Value = null }; var paramEncoded = new InputParam1 { Value = "bar/car" }; query = new ODataQuery <Param1>(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.AssignedTo(paramEncoded.Value)); Assert.Equal("$filter=assignedTo('bar%2Fcar')", query.ToString()); }
public async Task <List <Price> > GetPrices(ODataQuery <Price> query, bool firstPageOnly) { List <Price> priceList = new(); string requestUri = path + '?' + query.ToString(); int requestItemCount; Uri nextPageLink = null; //ToDo: Add concurrent readahead support since the paging count doesn't display properly do { if (nextPageLink != null) { requestUri = ConvertNextPageLinkToRelativeURI(nextPageLink); } var response = await http.GetFromJsonAsync <PriceResponse>(requestUri); priceList.AddRange(response.Prices); requestItemCount = response.Count; nextPageLink = response.NextPageLink; } while ( //TODO: Structure this better for concurrent readahead than this firstpageonly option !firstPageOnly && requestItemCount == 100 && Regex.IsMatch(nextPageLink.ToString(), "skip=\\d+$") ); return(priceList); }
public void ODataQuerySupportsImplicitConversionFromFullFilterString() { ODataQuery <Param1> query = "$filter=foo eq 'bar'"; query.Top = 100; Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); }
public void ODataQuerySupportsPartialState() { var query = new ODataQuery <Param1>(p => p.Foo == "bar") { Top = 100 }; Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); }
public void ODataQuerySupportsPartialStateWithSlashes() { var queryString = "$filter=foo eq 'bar%2Fclub'&$top=100"; var query = new ODataQuery <Param1>(p => p.Foo == "bar/club") { Top = 100 }; Assert.Equal(queryString, query.ToString()); }
public void TestQueryInOperator() { var userQuery = new ODataQuery <User>() .WhereIn(u => u.UserPrincipalName, "*****@*****.**", "*****@*****.**") .Top(20) .OrderBy(u => u.MailNickname); var expected = "$top=20&$orderby=mailNickname&$filter=(userPrincipalName eq '*****@*****.**' or userPrincipalName eq '*****@*****.**')"; var actualDecoded = System.Net.WebUtility.UrlDecode(userQuery.ToString()); Assert.Equal(expected, actualDecoded); }
public void TestQueryTwoFilterClauses() { var userQuery = new ODataQuery <User>() .WhereIn(u => u.UserPrincipalName, "*****@*****.**", "*****@*****.**") .Where(u => u.GivenName, "nikos", ODataOperator.GreaterThanEquals) .Top(20) .OrderBy(u => u.MailNickname); var expected = "$top=20&$orderby=mailNickname&$filter=(userPrincipalName eq '*****@*****.**' or userPrincipalName eq '*****@*****.**') and givenName ge 'nikos'"; var actualDecoded = System.Net.WebUtility.UrlDecode(userQuery.ToString()); Assert.Equal(expected, actualDecoded); }
public void ODataQuerySupportsEmptyState() { var query = new ODataQuery <Param1>(); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.Foo == null); Assert.Equal("", query.ToString()); var param = new InputParam1 { Value = null }; query = new ODataQuery <Param1>(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery <Param1>(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); }
public void ODataQuerySupportsAllParameters() { var queryString = "foo eq 'bar'"; var query = new ODataQuery<Param1>(p => p.Foo == "bar") { Expand = "param1", OrderBy = "d", Skip = 10, Top = 100 }; Assert.Equal(string.Format("$filter={0}&$orderby=d&$expand=param1&$top=100&$skip=10", Uri.EscapeDataString(queryString)), query.ToString()); }
/// <summary> /// Lists all user groups. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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 <IPage <GroupContract> > > ListWithHttpMessagesAsync(string resourceGroupName, string serviceName, string uid, ODataQuery <GroupContract> odataQuery = default(ODataQuery <GroupContract>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (uid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "uid"); } if (uid != null) { if (uid.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "uid", 80); } if (uid.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "uid", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(uid, "(^[\\w]+$)|(^[\\w][\\w\\-]+[\\w]$)")) { throw new ValidationException(ValidationRules.Pattern, "uid", "(^[\\w]+$)|(^[\\w][\\w\\-]+[\\w]$)"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("uid", uid); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", 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.ApiManagement/service/{serviceName}/users/{uid}/groups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } 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("GET"); _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; // 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <GroupContract> >(); _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 <Page <GroupContract> >(_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> /// Specify filter parameter with value '$filter=id gt 5 and name eq /// 'foo'&$orderby=id&$top=10' /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> GetWithFilterWithHttpMessagesAsync(ODataQuery <OdataFilter> odataQuery = default(ODataQuery <OdataFilter>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetWithFilter", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/odata/filter").ToString(); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// **Lists the metric values for a resource**. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='timespan'> /// The timespan of the query. It is a string with the following format /// 'startDateTime_ISO/endDateTime_ISO'. /// </param> /// <param name='interval'> /// The interval (i.e. timegrain) of the query. /// </param> /// <param name='metricnames'> /// The names of the metrics (comma separated) to retrieve. /// </param> /// <param name='aggregation'> /// The list of aggregation types (comma separated) to retrieve. /// </param> /// <param name='top'> /// The maximum number of records to retrieve. /// Valid only if $filter is specified. /// Defaults to 10. /// </param> /// <param name='orderby'> /// The aggregation to use for sorting results and the direction of the sort. /// Only one order can be specified. /// Examples: sum asc. /// </param> /// <param name='resultType'> /// Reduces the set of data collected. The syntax allowed depends on the /// operation. See the operation's description for details. Possible values /// include: 'Data', 'Metadata' /// </param> /// <param name='metricnamespace'> /// Metric namespace to query metric definitions for. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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 <ResponseInner> > ListWithHttpMessagesAsync(string resourceUri, ODataQuery <MetadataValue> odataQuery = default(ODataQuery <MetadataValue>), string timespan = default(string), System.TimeSpan?interval = default(System.TimeSpan?), string metricnames = default(string), string aggregation = default(string), int?top = default(int?), string orderby = default(string), ResultType?resultType = default(ResultType?), string metricnamespace = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2018-01-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("timespan", timespan); tracingParameters.Add("interval", interval); tracingParameters.Add("metricnames", metricnames); tracingParameters.Add("aggregation", aggregation); tracingParameters.Add("top", top); tracingParameters.Add("orderby", orderby); tracingParameters.Add("resultType", resultType); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("metricnamespace", metricnamespace); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/metrics").ToString(); _url = _url.Replace("{resourceUri}", resourceUri); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (timespan != null) { _queryParameters.Add(string.Format("timespan={0}", System.Uri.EscapeDataString(timespan))); } if (interval != null) { _queryParameters.Add(string.Format("interval={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(interval, Client.SerializationSettings).Trim('"')))); } if (metricnames != null) { _queryParameters.Add(string.Format("metricnames={0}", System.Uri.EscapeDataString(metricnames))); } if (aggregation != null) { _queryParameters.Add(string.Format("aggregation={0}", System.Uri.EscapeDataString(aggregation))); } if (top != null) { _queryParameters.Add(string.Format("top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("orderby={0}", System.Uri.EscapeDataString(orderby))); } if (resultType != null) { _queryParameters.Add(string.Format("resultType={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(resultType, Client.SerializationSettings).Trim('"')))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (metricnamespace != null) { _queryParameters.Add(string.Format("metricnamespace={0}", System.Uri.EscapeDataString(metricnamespace))); } 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("GET"); _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; // 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <ResponseInner>(); _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 <ResponseInner>(_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 AzureODataTests() { var validSubscription = "1234-5678-9012-3456"; using (var client = new AutoRestAzureSpecialParametersTestClient(Fixture.Uri, new TokenCredentials(Guid.NewGuid().ToString())) { SubscriptionId = validSubscription }) { var filter = new ODataQuery <OdataFilter>(f => f.Id > 5 && f.Name == "foo") { Top = 10, OrderBy = "id" }; Assert.Equal("$filter=id gt 5 and name eq 'foo'&$orderby=id&$top=10", filter.ToString()); client.Odata.GetWithFilter(filter); } }
public void AzureODataTests() { var validSubscription = "1234-5678-9012-3456"; SwaggerSpecRunner.RunTests( SwaggerPath("azure-special-properties.json"), ExpectedPath("AzureSpecials"), generator: "Azure.CSharp"); using (var client = new AutoRestAzureSpecialParametersTestClient(Fixture.Uri, new TokenCredentials(Guid.NewGuid().ToString())) { SubscriptionId = validSubscription }) { var filter = new ODataQuery <OdataFilter>(f => f.Id > 5 && f.Name == "foo") { Top = 10, OrderBy = "id" }; Assert.Equal("$filter=id gt 5 and name eq 'foo'&$orderby=id&$top=10", filter.ToString()); client.Odata.GetWithFilter(filter); } }
public void ODataQuerySupportsCustomDateTimeOffsetFilter() { var param = new Param1 { SubmitTime = DateTimeOffset.Parse("2016-03-28T08:15:00.0971693+00:00"), State = "Ended" }; var filter = new List<string>(); filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O")))); filter.Add(string.Format("state ne '{0}'", param.State)); var filterString = string.Join(" and ", filter.ToArray()); var query = new ODataQuery<Param1> { Filter = filterString }; Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00' and state ne 'Ended'", query.ToString()); }
public void ODataQuerySupportsAllParameters() { var query = new ODataQuery<Param1>(p => p.Foo == "bar") { Expand = "param1", OrderBy = "d", Skip = 10, Top = 100 }; Assert.Equal("$filter=foo eq 'bar'&$orderby=d&$expand=param1&$top=100&$skip=10", query.ToString()); }
public void ODataQuerySupportsPartialState() { var queryString = "foo eq 'bar'"; var query = new ODataQuery <Param1>(p => p.Foo == "bar") { Top = 100 }; Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); }
public void ODataQuerySupportsCustomDateTimeOffsetFilter() { var param = new Param1 { SubmitTime = DateTimeOffset.Parse("2016-03-28T08:15:00.0971693+00:00"), State = "Ended" }; var filter = new List <string>(); filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O")))); filter.Add(string.Format("state ne '{0}'", param.State)); var filterString = string.Join(" and ", filter.ToArray()); var query = new ODataQuery <Param1> { Filter = filterString }; Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00' and state ne 'Ended'", query.ToString()); }
public void ODataQuerySupportsImplicitConversionFromQueryString() { var queryString = "foo eq 'bar'"; ODataQuery <Param1> query = string.Format("$filter={0}&$top=100", queryString); Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); }
public void ODataQuerySupportsAllParameters() { var query = new ODataQuery <Param1>(p => p.Foo == "bar") { Expand = "param1", OrderBy = "d", Skip = 10, Top = 100 }; Assert.Equal("$filter=foo eq 'bar'&$orderby=d&$expand=param1&$top=100&$skip=10", query.ToString()); }
public void ODataQuerySupportsEmptyState() { var query = new ODataQuery<Param1>(); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.Foo == null); Assert.Equal("", query.ToString()); var param = new InputParam1 { Value = null }; query = new ODataQuery<Param1>(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); }
public void ODataQuerySupportsPartialState() { var queryString = "foo eq 'bar'"; var query = new ODataQuery<Param1>(p => p.Foo == "bar") { Top = 100 }; Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); }
public void ODataQuerySupportsPartialStateWithSlashes() { var queryString = "$filter=foo eq 'bar%2Fclub'&$top=100"; var query = new ODataQuery<Param1>(p => p.Foo == "bar/club") { Top = 100 }; Assert.Equal(queryString, query.ToString()); }
/// <summary> /// Gets the Activity Logs for the Tenant.<br>Everything that is /// applicable to the API to get the Activity Logs for the subscription is /// applicable to this API (the parameters, $filter, etc.).<br>One thing /// to point out here is that this API does *not* retrieve the logs at the /// individual subscription of the tenant but only surfaces the logs that were /// generated at the tenant level. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// Used to fetch events with only the given properties.<br>The /// **$select** argument is a comma separated list of property names to be /// returned. Possible values are: *authorization*, *claims*, *correlationId*, /// *description*, *eventDataId*, *eventName*, *eventTimestamp*, *httpRequest*, /// *level*, *operationId*, *operationName*, *properties*, *resourceGroupName*, /// *resourceProviderName*, *resourceId*, *status*, *submissionTimestamp*, /// *subStatus*, *subscriptionId* /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <EventDataInner> > > ListWithHttpMessagesAsync(ODataQuery <EventDataInner> odataQuery = default(ODataQuery <EventDataInner>), string select = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2015-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("select", select); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/microsoft.insights/eventtypes/management/values").ToString(); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select))); } 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("GET"); _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; // 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <EventDataInner> >(); _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 <Page1 <EventDataInner> >(_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 ODataQuerySupportsAllParameters() { var queryString = "foo eq 'bar'"; var query = new ODataQuery <Param1>(p => p.Foo == "bar") { Expand = "param1", OrderBy = "d", Skip = 10, Top = 100 }; Assert.Equal(string.Format("$filter={0}&$orderby=d&$expand=param1&$top=100&$skip=10", Uri.EscapeDataString(queryString)), query.ToString()); }
public void ODataQuerySupportsEmptyState() { var query = new ODataQuery<Param1>(); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.Foo == null); Assert.Equal("", query.ToString()); var param = new InputParam1 { Value = null }; var paramEncoded = new InputParam1 { Value = "bar/car" }; query = new ODataQuery<Param1>(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery<Param1>(p => p.AssignedTo(paramEncoded.Value)); Assert.Equal("$filter=assignedTo('bar%2Fcar')", query.ToString()); }
/// <summary> /// Gets a list of virtual machine extension image versions. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='type'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationResponse <IList <VirtualMachineExtensionImage> > > ListVersionsWithHttpMessagesAsync(string location, string publisherName, string type, ODataQuery <VirtualMachineExtensionImage> odataQuery = default(ODataQuery <VirtualMachineExtensionImage>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (type == null) { throw new ValidationException(ValidationRules.CannotBeNull, "type"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("type", type); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVersions", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{type}", Uri.EscapeDataString(type)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse <IList <VirtualMachineExtensionImage> >(); _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) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject <IList <VirtualMachineExtensionImage> >(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void ODataQuerySupportsPartialState() { var query = new ODataQuery<Param1>(p => p.Foo == "bar") { Top = 100 }; Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); }
/// <summary> /// Gets the list of CRR jobs from the target region. /// </summary> /// <param name='azureRegion'> /// Azure region to hit Api /// </param> /// <param name='parameters'> /// Backup CRR Job request /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// 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 <IPage <JobResource> > > ListWithHttpMessagesAsync(string azureRegion, CrrJobRequest parameters, ODataQuery <JobQueryObject> odataQuery = default(ODataQuery <JobQueryObject>), string skipToken = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (azureRegion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "azureRegion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2018-12-20"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("azureRegion", azureRegion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupCrrJobs").ToString(); _url = _url.Replace("{azureRegion}", System.Uri.EscapeDataString(azureRegion)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } 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("POST"); _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); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <JobResource> >(); _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 <Page <JobResource> >(_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> /// Gets a list of security events. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='managedInstanceName'> /// The name of the managed instance. /// </param> /// <param name='databaseName'> /// The name of the managed database for which the security events are /// retrieved. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skiptoken'> /// An opaque token that identifies a starting point in the collection. /// </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 <IPage <SecurityEvent> > > ListByDatabaseWithHttpMessagesAsync(string resourceGroupName, string managedInstanceName, string databaseName, ODataQuery <SecurityEventsFilterParameters> odataQuery = default(ODataQuery <SecurityEventsFilterParameters>), string skiptoken = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-11-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("skiptoken", skiptoken); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByDatabase", 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.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/securityEvents").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (skiptoken != null) { _queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(skiptoken))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("GET"); _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; // 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 <IPage <SecurityEvent> >(); _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 <Page1 <SecurityEvent> >(_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 string Translate(QueryModel queryModel) { base.VisitQueryModel(queryModel); return(_query.ToString()); }