示例#1
0
        /// <summary>
        /// The AutoSuggest API lets you send a search query to Bing and get back a
        /// list of suggestions. This section provides technical details about the
        /// query parameters and headers that you use to request suggestions and the
        /// JSON response objects that contain them.
        /// </summary>
        /// <param name='query'>
        /// The user's search term.
        /// </param>
        /// <param name='acceptLanguage'>
        /// A comma-delimited list of one or more languages to use for user interface
        /// strings. The list is in decreasing order of preference. For additional
        /// information, including expected format, see
        /// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
        /// header and the setLang query parameter are mutually exclusive; do not
        /// specify both. If you set this header, you must also specify the
        /// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#cc)
        /// query parameter. To determine the market to return results for, Bing uses
        /// the first supported language it finds from the list and combines it with
        /// the cc parameter value. If the list does not include a supported language,
        /// Bing finds the closest language and market that supports the request or it
        /// uses an aggregated or default market for the results. To determine the
        /// market that Bing used, see the BingAPIs-Market header. Use this header and
        /// the cc query parameter only if you specify multiple languages. Otherwise,
        /// use the
        /// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#mkt)
        /// and
        /// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-autosuggest-api-v7-reference#setlang)
        /// query parameters. A user interface string is a string that's used as a
        /// label in a user interface. There are few user interface strings in the JSON
        /// response objects. Any links to Bing.com properties in the response objects
        /// apply the specified language.
        /// </param>
        /// <param name='pragma'>
        /// By default, Bing returns cached content, if available. To prevent Bing from
        /// returning cached content, set the Pragma header to no-cache (for example,
        /// Pragma: no-cache).
        /// </param>
        /// <param name='userAgent'>
        /// The user agent originating the request. Bing uses the user agent to provide
        /// mobile users with an optimized experience. Although optional, you are
        /// encouraged to always specify this header. The user-agent should be the same
        /// string that any commonly used browser sends. For information about user
        /// agents, see [RFC
        /// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
        /// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
        /// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
        /// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
        /// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
        /// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
        /// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
        /// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
        /// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
        /// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
        /// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
        /// </param>
        /// <param name='clientId'>
        /// Bing uses this header to provide users with consistent behavior across Bing
        /// API calls. Bing often flights new features and improvements, and it uses
        /// the client ID as a key for assigning traffic on different flights. If you
        /// do not use the same client ID for a user across multiple requests, then
        /// Bing may assign the user to multiple conflicting flights. Being assigned to
        /// multiple conflicting flights can lead to an inconsistent user experience.
        /// For example, if the second request has a different flight assignment than
        /// the first, the experience may be unexpected. Also, Bing can use the client
        /// ID to tailor web results to that client ID’s search history, providing a
        /// richer experience for the user. Bing also uses this header to help improve
        /// result rankings by analyzing the activity generated by a client ID. The
        /// relevance improvements help with better quality of results delivered by
        /// Bing APIs and in turn enables higher click-through rates for the API
        /// consumer. IMPORTANT: Although optional, you should consider this header
        /// required. Persisting the client ID across multiple requests for the same
        /// end user and device combination enables 1) the API consumer to receive a
        /// consistent user experience, and 2) higher click-through rates via better
        /// quality of results from the Bing APIs. Each user that uses your application
        /// on the device must have a unique, Bing generated client ID. If you do not
        /// include this header in the request, Bing generates an ID and returns it in
        /// the X-MSEdge-ClientID response header. The only time that you should NOT
        /// include this header in a request is the first time the user uses your app
        /// on that device. Use the client ID for each Bing API request that your app
        /// makes for this user on the device. Persist the client ID. To persist the ID
        /// in a browser app, use a persistent HTTP cookie to ensure the ID is used
        /// across all sessions. Do not use a session cookie. For other apps such as
        /// mobile apps, use the device's persistent storage to persist the ID. The
        /// next time the user uses your app on that device, get the client ID that you
        /// persisted. Bing responses may or may not include this header. If the
        /// response includes this header, capture the client ID and use it for all
        /// subsequent Bing requests for the user on that device. If you include the
        /// X-MSEdge-ClientID, you must not include cookies in the request.
        /// </param>
        /// <param name='clientIp'>
        /// The IPv4 or IPv6 address of the client device. The IP address is used to
        /// discover the user's location. Bing uses the location information to
        /// determine safe search behavior. Although optional, you are encouraged to
        /// always specify this header and the X-Search-Location header. Do not
        /// obfuscate the address (for example, by changing the last octet to 0).
        /// Obfuscating the address results in the location not being anywhere near the
        /// device's actual location, which may result in Bing serving erroneous
        /// results.
        /// </param>
        /// <param name='location'>
        /// A semicolon-delimited list of key/value pairs that describe the client's
        /// geographical location. Bing uses the location information to determine safe
        /// search behavior and to return relevant local content. Specify the key/value
        /// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
        /// to specify the user's location. lat (required): The latitude of the
        /// client's location, in degrees. The latitude must be greater than or equal
        /// to -90.0 and less than or equal to +90.0. Negative values indicate southern
        /// latitudes and positive values indicate northern latitudes. long (required):
        /// The longitude of the client's location, in degrees. The longitude must be
        /// greater than or equal to -180.0 and less than or equal to +180.0. Negative
        /// values indicate western longitudes and positive values indicate eastern
        /// longitudes. re (required): The radius, in meters, which specifies the
        /// horizontal accuracy of the coordinates. Pass the value returned by the
        /// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
        /// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
        /// (optional): The UTC UNIX timestamp of when the client was at the location.
        /// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
        /// (optional): The client's relative heading or direction of travel. Specify
        /// the direction of travel as degrees from 0 through 360, counting clockwise
        /// relative to true north. Specify this key only if the sp key is nonzero. sp
        /// (optional): The horizontal velocity (speed), in meters per second, that the
        /// client device is traveling. alt (optional): The altitude of the client
        /// device, in meters. are (optional): The radius, in meters, that specifies
        /// the vertical accuracy of the coordinates. Specify this key only if you
        /// specify the alt key. Although many of the keys are optional, the more
        /// information that you provide, the more accurate the location results are.
        /// Although optional, you are encouraged to always specify the user's
        /// geographical location. Providing the location is especially important if
        /// the client's IP address does not accurately reflect the user's physical
        /// location (for example, if the client uses VPN). For optimal results, you
        /// should include this header and the X-MSEdge-ClientIP header, but at a
        /// minimum, you should include this header.
        /// </param>
        /// <param name='countryCode'>
        /// A 2-character country code of the country where the results come from. This
        /// API supports only the United States market. If you specify this query
        /// parameter, it must be set to us. If you set this parameter, you must also
        /// specify the Accept-Language header. Bing uses the first supported language
        /// it finds from the languages list, and combine that language with the
        /// country code that you specify to determine the market to return results
        /// for. If the languages list does not include a supported language, Bing
        /// finds the closest language and market that supports the request, or it may
        /// use an aggregated or default market for the results instead of a specified
        /// one. You should use this query parameter and the Accept-Language query
        /// parameter only if you specify multiple languages; otherwise, you should use
        /// the mkt and setLang query parameters. This parameter and the mkt query
        /// parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='market'>
        /// The market where the results come from. You are strongly encouraged to
        /// always specify the market, if known. Specifying the market helps Bing route
        /// the request and return an appropriate and optimal response. This parameter
        /// and the cc query parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='safeSearch'>
        /// Filter suggestions for adult content. The following are the possible filter
        /// values. Off: Return suggestions with adult text, images, or videos.
        /// Moderate: Return suggestion with adult text but not adult images or videos.
        /// Strict: Do not return news articles with adult text, images, or videos. If
        /// the request comes from a market that Bing's adult policy requires that
        /// safeSearch is set to Strict, Bing ignores the safeSearch value and uses
        /// Strict. If you use the site: query operator, there is the chance that the
        /// response may contain adult content regardless of what the safeSearch query
        /// parameter is set to. Use site: only if you are aware of the content on the
        /// site and your scenario supports the possibility of adult content. Possible
        /// values include: 'Off', 'Moderate', 'Strict'
        /// </param>
        /// <param name='setLang'>
        /// The language to use for user interface strings. Specify the language using
        /// the ISO 639-1 2-letter language code. For example, the language code for
        /// English is EN. The default is EN (English). Although optional, you should
        /// always specify the language. Typically, you set setLang to the same
        /// language specified by mkt unless the user wants the user interface strings
        /// displayed in a different language. This parameter and the Accept-Language
        /// header are mutually exclusive; do not specify both. A user interface string
        /// is a string that's used as a label in a user interface. There are few user
        /// interface strings in the JSON response objects. Also, any links to Bing.com
        /// properties in the response objects apply the specified language.
        /// </param>
        /// <param name='responseFormat'>
        /// The media type to use for the response. The following are the possible
        /// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
        /// JSONLD, the response body includes JSON-LD objects that contain the search
        /// results.
        /// </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 <HttpOperationResponse <Suggestions> > AutoSuggestMethodWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string safeSearch = default(string), string setLang = default(string), IList <string> responseFormat = default(IList <string>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
            }
            if (query == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "query");
            }
            string xBingApisSDK = "true";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("xBingApisSDK", xBingApisSDK);
                tracingParameters.Add("acceptLanguage", acceptLanguage);
                tracingParameters.Add("pragma", pragma);
                tracingParameters.Add("userAgent", userAgent);
                tracingParameters.Add("clientId", clientId);
                tracingParameters.Add("clientIp", clientIp);
                tracingParameters.Add("location", location);
                tracingParameters.Add("countryCode", countryCode);
                tracingParameters.Add("market", market);
                tracingParameters.Add("query", query);
                tracingParameters.Add("safeSearch", safeSearch);
                tracingParameters.Add("setLang", setLang);
                tracingParameters.Add("responseFormat", responseFormat);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "AutoSuggestMethod", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Suggestions";

            _url = _url.Replace("{Endpoint}", Endpoint);
            List <string> _queryParameters = new List <string>();

            if (countryCode != null)
            {
                _queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
            }
            if (market != null)
            {
                _queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
            }
            if (query != null)
            {
                _queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
            }
            if (safeSearch != null)
            {
                _queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
            }
            if (setLang != null)
            {
                _queryParameters.Add(string.Format("setLang={0}", System.Uri.EscapeDataString(setLang)));
            }
            if (responseFormat != null)
            {
                _queryParameters.Add(string.Format("ResponseFormat={0}", System.Uri.EscapeDataString(string.Join(",", responseFormat))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + 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 (xBingApisSDK != null)
            {
                if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
                {
                    _httpRequest.Headers.Remove("X-BingApis-SDK");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
            }
            if (acceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("Accept-Language"))
                {
                    _httpRequest.Headers.Remove("Accept-Language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
            }
            if (pragma != null)
            {
                if (_httpRequest.Headers.Contains("Pragma"))
                {
                    _httpRequest.Headers.Remove("Pragma");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Pragma", pragma);
            }
            if (userAgent != null)
            {
                if (_httpRequest.Headers.Contains("User-Agent"))
                {
                    _httpRequest.Headers.Remove("User-Agent");
                }
                _httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
            }
            if (clientId != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientID");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
            }
            if (clientIp != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientIP");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
            }
            if (location != null)
            {
                if (_httpRequest.Headers.Contains("X-Search-Location"))
                {
                    _httpRequest.Headers.Remove("X-Search-Location");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
            }


            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 (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await 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 = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, 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 HttpOperationResponse <Suggestions>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <Suggestions>(_responseContent, 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);
        }
示例#2
0
        private async Task <RavenJToken> CheckForErrorsAndReturnCachedResultIfAnyAsync(bool readErrorString)
        {
            if (Response.IsSuccessStatusCode)
            {
                return(null);
            }
            if (Response.StatusCode == HttpStatusCode.Unauthorized ||
                Response.StatusCode == HttpStatusCode.NotFound ||
                Response.StatusCode == HttpStatusCode.Conflict)
            {
                factory.InvokeLogRequest(owner, () => new RequestResultArgs
                {
                    DurationMilliseconds = CalculateDuration(),
                    Method     = Method,
                    HttpResult = (int)Response.StatusCode,
                    Status     = RequestStatus.ErrorOnServer,
                    Result     = Response.StatusCode.ToString(),
                    Url        = Url,
                    PostedData = postedData
                });

                throw ErrorResponseException.FromResponseMessage(Response, readErrorString);
            }

            if (Response.StatusCode == HttpStatusCode.NotModified &&
                CachedRequestDetails != null)
            {
                factory.UpdateCacheTime(this);
                var result = factory.GetCachedResponse(this, ResponseHeaders);

                // here we explicitly need to get Response.Headers, and NOT ResponseHeaders because we are
                // getting the value _right now_ from the secondary, and don't care about the 304, the force check
                // is still valid
                HandleReplicationStatusChanges(ResponseHeaders, primaryUrl, operationUrl);

                factory.InvokeLogRequest(owner, () => new RequestResultArgs
                {
                    DurationMilliseconds = CalculateDuration(),
                    Method     = Method,
                    HttpResult = (int)Response.StatusCode,
                    Status     = RequestStatus.Cached,
                    Result     = result.ToString(),
                    Url        = Url,
                    PostedData = postedData
                });

                return(result);
            }


            using (var sr = new StreamReader(await Response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false)))
            {
                var readToEnd = sr.ReadToEnd();

                factory.InvokeLogRequest(owner, () => new RequestResultArgs
                {
                    DurationMilliseconds = CalculateDuration(),
                    Method     = Method,
                    HttpResult = (int)Response.StatusCode,
                    Status     = RequestStatus.Cached,
                    Result     = readToEnd,
                    Url        = Url,
                    PostedData = postedData
                });

                if (string.IsNullOrWhiteSpace(readToEnd))
                {
                    throw ErrorResponseException.FromResponseMessage(Response);
                }

                RavenJObject ravenJObject;
                try
                {
                    ravenJObject = RavenJObject.Parse(readToEnd);
                }
                catch (Exception e)
                {
                    throw new ErrorResponseException(Response, readToEnd, e);
                }
                if (ravenJObject.ContainsKey("IndexDefinitionProperty"))
                {
                    throw new IndexCompilationException(ravenJObject.Value <string>("Message"))
                          {
                              IndexDefinitionProperty = ravenJObject.Value <string>("IndexDefinitionProperty"),
                              ProblematicText         = ravenJObject.Value <string>("ProblematicText")
                          };
                }
                if (Response.StatusCode == HttpStatusCode.BadRequest && ravenJObject.ContainsKey("Message"))
                {
                    throw new BadRequestException(ravenJObject.Value <string>("Message"), ErrorResponseException.FromResponseMessage(Response));
                }
                if (ravenJObject.ContainsKey("Error"))
                {
                    var sb = new StringBuilder();
                    foreach (var prop in ravenJObject)
                    {
                        if (prop.Key == "Error")
                        {
                            continue;
                        }

                        sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                    }

                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                    }
                    sb.Append(ravenJObject.Value <string>("Error"));

                    throw new ErrorResponseException(Response, sb.ToString(), readToEnd);
                }
                throw new ErrorResponseException(Response, readToEnd);
            }
        }
示例#3
0
        private static async Task <ErrorResponseException> CreateErrorResponseExceptionAsync(HttpResponseMessage response)
        {
            using (var sr = new StreamReader(await response.GetResponseStreamWithHttpDecompression().ConfigureAwait(false)))
            {
                var readToEnd = sr.ReadToEnd();

                if (string.IsNullOrWhiteSpace(readToEnd))
                {
                    throw ErrorResponseException.FromResponseMessage(response);
                }

                RavenJObject ravenJObject;
                try
                {
                    ravenJObject = RavenJObject.Parse(readToEnd);
                }
                catch (Exception e)
                {
                    throw new ErrorResponseException(response, readToEnd, e);
                }

                if (response.StatusCode == HttpStatusCode.BadRequest && ravenJObject.ContainsKey("Message"))
                {
                    throw new BadRequestException(ravenJObject.Value <string>("Message"), ErrorResponseException.FromResponseMessage(response));
                }

                if (ravenJObject.ContainsKey("Error"))
                {
                    var sb = new StringBuilder();
                    foreach (var prop in ravenJObject)
                    {
                        if (prop.Key == "Error")
                        {
                            continue;
                        }

                        sb.Append(prop.Key).Append(": ").AppendLine(prop.Value.ToString(Formatting.Indented));
                    }

                    if (sb.Length > 0)
                    {
                        sb.AppendLine();
                    }
                    sb.Append(ravenJObject.Value <string>("Error"));

                    throw new ErrorResponseException(response, sb.ToString(), readToEnd);
                }

                throw new ErrorResponseException(response, readToEnd);
            }
        }
示例#4
0
        public async Task <Action <HttpClient> > DoOAuthRequestAsync(string baseUrl, string oauthSource, string apiKey)
        {
            if (oauthSource == null)
            {
                throw new ArgumentNullException("oauthSource");
            }

            string serverRSAExponent = null;
            string serverRSAModulus  = null;
            string challenge         = null;

            // Note that at two tries will be needed in the normal case.
            // The first try will get back a challenge,
            // the second try will try authentication. If something goes wrong server-side though
            // (e.g. the server was just rebooted or the challenge timed out for some reason), we
            // might get a new challenge back, so we try a third time just in case.
            int tries = 0;

            while (true)
            {
                tries++;
#if !DNXCORE50
                var handler = new WebRequestHandler();
#else
                var handler = new WinHttpHandler();
#endif

                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("grant_type", "client_credentials");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")
                    {
                        CharSet = "UTF-8"
                    });

                    string data = null;
                    if (!string.IsNullOrEmpty(serverRSAExponent) && !string.IsNullOrEmpty(serverRSAModulus) && !string.IsNullOrEmpty(challenge))
                    {
                        var exponent = OAuthHelper.ParseBytes(serverRSAExponent);
                        var modulus  = OAuthHelper.ParseBytes(serverRSAModulus);

                        var apiKeyParts = apiKey.Split(new[] { '/' }, StringSplitOptions.None);
                        if (apiKeyParts.Length > 2)
                        {
                            apiKeyParts[1] = string.Join("/", apiKeyParts.Skip(1));
                        }
                        if (apiKeyParts.Length < 2)
                        {
                            throw new InvalidOperationException("Invalid API key");
                        }

                        var apiKeyName = apiKeyParts[0].Trim();
                        var apiSecret  = apiKeyParts[1].Trim();

                        data = OAuthHelper.DictionaryToString(new Dictionary <string, string> {
                            { OAuthHelper.Keys.RSAExponent, serverRSAExponent }, { OAuthHelper.Keys.RSAModulus, serverRSAModulus }, { OAuthHelper.Keys.EncryptedData, OAuthHelper.EncryptAsymmetric(exponent, modulus, OAuthHelper.DictionaryToString(new Dictionary <string, string> {
                                    { OAuthHelper.Keys.APIKeyName, apiKeyName }, { OAuthHelper.Keys.Challenge, challenge }, { OAuthHelper.Keys.Response, OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret)) }
                                })) }
                        });
                    }

                    var requestUri = oauthSource;

                    var response = await httpClient.PostAsync(requestUri, data != null?(HttpContent) new CompressedStringContent(data, true) : new StringContent("")).AddUrlIfFaulting(new Uri(requestUri)).ConvertSecurityExceptionToServerNotFound();

                    if (response.IsSuccessStatusCode == false)
                    {
                        // We've already tried three times and failed
                        if (tries >= 3)
                        {
                            throw ErrorResponseException.FromResponseMessage(response);
                        }

                        if (response.StatusCode != HttpStatusCode.PreconditionFailed)
                        {
                            throw ErrorResponseException.FromResponseMessage(response);
                        }

                        var header = response.Headers.GetFirstValue("WWW-Authenticate");
                        if (header == null || header.StartsWith(OAuthHelper.Keys.WWWAuthenticateHeaderKey) == false)
                        {
                            throw new ErrorResponseException(response, "Got invalid WWW-Authenticate value");
                        }

                        var challengeDictionary = OAuthHelper.ParseDictionary(header.Substring(OAuthHelper.Keys.WWWAuthenticateHeaderKey.Length).Trim());
                        serverRSAExponent = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAExponent);
                        serverRSAModulus  = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAModulus);
                        challenge         = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Challenge);

                        if (string.IsNullOrEmpty(serverRSAExponent) || string.IsNullOrEmpty(serverRSAModulus) || string.IsNullOrEmpty(challenge))
                        {
                            throw new InvalidOperationException("Invalid response from server, could not parse raven authentication information: " + header);
                        }

                        continue;
                    }

                    using (var stream = await response.GetResponseStreamWithHttpDecompression())
                        using (var reader = new StreamReader(stream))
                        {
                            var currentOauthToken = reader.ReadToEnd();
                            CurrentOauthToken           = currentOauthToken;
                            CurrentOauthTokenWithBearer = "Bearer " + currentOauthToken;

                            ScheduleTokenRefresh(oauthSource, apiKey);

                            return((Action <HttpClient>)(SetAuthorization));
                        }
                }
            }
        }
        /// <summary>
        /// Lists a collection of properties defined within a service instance.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List 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 <NotificationContract> > > ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (nextPageLink == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("nextPageLink", nextPageLink);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListByServiceNext", tracingParameters);
            }
            // Construct URL
            string _url = "{nextLink}";

            _url = _url.Replace("{nextLink}", nextPageLink);
            List <string> _queryParameters = new List <string>();

            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 <NotificationContract> >();

            _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 <NotificationContract> >(_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);
        }
示例#6
0
        /// <summary>
        /// Get a collection of all goals
        /// </summary>
        /// <param name='types'>
        /// The goal types(e.g Steps, CaloriesBurned) filter.
        /// </param>
        /// <param name='windowTypes'>
        /// The goal window types(e.g Daily, Weekly) filter.
        /// </param>
        /// <param name='startDate'>
        /// The start date for date range filter.
        /// </param>
        /// <param name='endDate'>
        /// The end date for date range filter.
        /// </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 <HttpOperationResponse <GoalsResponse> > GetWithHttpMessagesAsync(string types = default(string), string windowTypes = default(string), System.DateTime?startDate = default(System.DateTime?), System.DateTime?endDate = default(System.DateTime?), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.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("types", types);
                tracingParameters.Add("windowTypes", windowTypes);
                tracingParameters.Add("startDate", startDate);
                tracingParameters.Add("endDate", endDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Goals").ToString();
            List <string> _queryParameters = new List <string>();

            if (types != null)
            {
                _queryParameters.Add(string.Format("types={0}", System.Uri.EscapeDataString(types)));
            }
            if (windowTypes != null)
            {
                _queryParameters.Add(string.Format("windowTypes={0}", System.Uri.EscapeDataString(windowTypes)));
            }
            if (startDate != null)
            {
                _queryParameters.Add(string.Format("startDate={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(startDate, Client.SerializationSettings).Trim('"'))));
            }
            if (endDate != null)
            {
                _queryParameters.Add(string.Format("endDate={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(endDate, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + 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 (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 = Microsoft.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 HttpOperationResponse <GoalsResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <GoalsResponse>(_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);
        }
示例#7
0
        /// <summary>
        /// apps - Assign a LUIS Azure account to an application
        /// </summary>
        /// <remarks>
        /// Assigns an Azure account to the application.
        /// </remarks>
        /// <param name='azureRegion'>
        /// Supported Azure regions for Cognitive Services endpoints. Possible values
        /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
        /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
        /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
        /// </param>
        /// <param name='azureCloud'>
        /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
        /// include: 'com', 'us'
        /// </param>
        /// <param name='appId'>
        /// The application ID.
        /// </param>
        /// <param name='azureAccountInfoObject'>
        /// The Azure account information object.
        /// </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 <HttpOperationResponse <OperationStatus> > AssignToAppWithHttpMessagesAsync(AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, AzureAccountInfoObject azureAccountInfoObject = default(AzureAccountInfoObject), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (azureAccountInfoObject != null)
            {
                azureAccountInfoObject.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("azureRegion", azureRegion);
                tracingParameters.Add("azureCloud", azureCloud);
                tracingParameters.Add("appId", appId);
                tracingParameters.Add("azureAccountInfoObject", azureAccountInfoObject);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "AssignToApp", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "apps/{appId}/azureaccounts";

            _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(azureRegion, Client.SerializationSettings).Trim('"'));
            _url = _url.Replace("{AzureCloud}", Rest.Serialization.SafeJsonConvert.SerializeObject(azureCloud, Client.SerializationSettings).Trim('"'));
            _url = _url.Replace("{appId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(appId, Client.SerializationSettings).Trim('"')));
            // 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 (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 (azureAccountInfoObject != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(azureAccountInfoObject, 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 != 201)
            {
                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 HttpOperationResponse <OperationStatus>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <OperationStatus>(_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);
        }
示例#8
0
        /// <summary>
        /// Remove an action plan objective
        /// </summary>
        /// <param name='actionPlanId'>
        /// The instance of the plan that the objective belongs to.
        /// </param>
        /// <param name='objectiveId'>
        /// The instance of the objective to delete.
        /// </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>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> DeleteWithHttpMessagesAsync(System.Guid actionPlanId, System.Guid objectiveId, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.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("actionPlanId", actionPlanId);
                tracingParameters.Add("objectiveId", objectiveId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "ActionPlans/{actionPlanId}/Objectives/{objectiveId}").ToString();

            _url = _url.Replace("{actionPlanId}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(actionPlanId, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{objectiveId}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(objectiveId, Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("DELETE");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            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 != 204)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Microsoft.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 HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#9
0
        /// <summary>
        /// Parse response errors if any and return relevant error messages
        /// </summary>
        /// <param name="response"></param>
        internal static void ParseError(IRestResponse response)
        {
            if (response == null)
            {
                throw new ConnectionException("Response is nil. Please report this issue https://github.com/minio/minio-dotnet/issues");
            }
            if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode))
            {
                throw new RedirectionException("Redirection detected. Please report this issue https://github.com/minio/minio-dotnet/issues");
            }

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                ErrorResponse errorResponse = new ErrorResponse();

                if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) ||
                    HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode))
                {
                    MinioException e = null;

                    foreach (Parameter parameter in response.Headers)
                    {
                        if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.HostId = parameter.Value.ToString();
                        }
                        if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.RequestId = parameter.Value.ToString();
                        }
                        if (parameter.Name.Equals("x-amz-bucket-region", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.BucketRegion = parameter.Value.ToString();
                        }
                    }

                    errorResponse.Resource = response.Request.Resource;

                    if (HttpStatusCode.NotFound.Equals(response.StatusCode))
                    {
                        int  pathLength = response.Request.Resource.Split('/').Count();
                        bool isAWS      = response.ResponseUri.Host.EndsWith("s3.amazonaws.com");
                        bool isVirtual  = isAWS && !(response.ResponseUri.Host.StartsWith("s3.amazonaws.com"));

                        if (pathLength > 1)
                        {
                            errorResponse.Code = "NoSuchKey";
                            var bucketName = response.Request.Resource.Split('/')[0];
                            var objectName = response.Request.Resource.Split('/')[1];
                            if (objectName == "")
                            {
                                e = new BucketNotFoundException(bucketName, "Not found.");
                            }
                            else
                            {
                                e = new ObjectNotFoundException(objectName, "Not found.");
                            }
                        }
                        else if (pathLength == 1)
                        {
                            var resource = response.Request.Resource.Split('/')[0];

                            if (isAWS && isVirtual && response.Request.Resource != "")
                            {
                                errorResponse.Code = "NoSuchKey";
                                e = new ObjectNotFoundException(resource, "Not found.");
                            }
                            else
                            {
                                errorResponse.Code = "NoSuchBucket";
                                BucketRegionCache.Instance.Remove(resource);
                                e = new BucketNotFoundException(resource, "Not found.");
                            }
                        }
                        else
                        {
                            e = new InternalClientException("404 without body resulted in path with less than two components");
                        }
                    }
                    else if (HttpStatusCode.Forbidden.Equals(response.StatusCode))
                    {
                        errorResponse.Code = "Forbidden";
                        e = new AccessDeniedException("Access denied on the resource: " + response.Request.Resource);
                    }
                    e.Response = errorResponse;
                    throw e;
                }
                throw new InternalClientException("Unsuccessful response from server without XML error: " + response.ErrorMessage);
            }

            if (response.StatusCode.Equals(HttpStatusCode.NotFound) && response.Request.Resource.EndsWith("?location") &&
                response.Request.Method.Equals(Method.GET))
            {
                var bucketName = response.Request.Resource.Split('?')[0];
                BucketRegionCache.Instance.Remove(bucketName);
                throw new BucketNotFoundException(bucketName, "Not found.");
            }

            var           contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);
            var           stream       = new MemoryStream(contentBytes);
            ErrorResponse errResponse  = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream));

            // Handle XML response for Bucket Policy not found case
            if (response.StatusCode.Equals(HttpStatusCode.NotFound) && response.Request.Resource.EndsWith("?policy") &&
                response.Request.Method.Equals(Method.GET) && (errResponse.Code.Equals("NoSuchBucketPolicy")))
            {
                ErrorResponseException ErrorException = new ErrorResponseException(errResponse.Message, errResponse.Code);
                ErrorException.Response = errResponse;
                ErrorException.XmlError = response.Content;
                throw ErrorException;
            }

            MinioException MinioException = new MinioException(errResponse.Message);

            MinioException.Response = errResponse;
            MinioException.XmlError = response.Content;
            throw MinioException;
        }
示例#10
0
        /// <summary>
        /// Gets all the extraction features for the specified application version.
        /// </summary>
        /// <param name='appId'>
        /// The application ID.
        /// </param>
        /// <param name='versionId'>
        /// The version ID.
        /// </param>
        /// <param name='skip'>
        /// The number of entries to skip. Default value is 0.
        /// </param>
        /// <param name='take'>
        /// The number of entries to return. Maximum page size is 500. Default is 100.
        /// </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 <HttpOperationResponse <FeaturesResponseObject> > ListWithHttpMessagesAsync(System.Guid appId, string versionId, int?skip = 0, int?take = 100, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (versionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "versionId");
            }
            if (skip < 0)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "skip", 0);
            }
            if (take > 500)
            {
                throw new ValidationException(ValidationRules.InclusiveMaximum, "take", 500);
            }
            if (take < 0)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "take", 0);
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("appId", appId);
                tracingParameters.Add("versionId", versionId);
                tracingParameters.Add("skip", skip);
                tracingParameters.Add("take", take);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "apps/{appId}/versions/{versionId}/features";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            _url = _url.Replace("{appId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(appId, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{versionId}", System.Uri.EscapeDataString(versionId));
            List <string> _queryParameters = new List <string>();

            if (skip != null)
            {
                _queryParameters.Add(string.Format("skip={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
            }
            if (take != null)
            {
                _queryParameters.Add(string.Format("take={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(take, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + 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 (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 HttpOperationResponse <FeaturesResponseObject>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <FeaturesResponseObject>(_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);
        }
示例#11
0
        /// <summary>
        /// Train call to add suggestions to the knowledgebase.
        /// </summary>
        /// <param name='kbId'>
        /// Knowledgebase id.
        /// </param>
        /// <param name='trainPayload'>
        /// Post body of the request.
        /// </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="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 <HttpOperationResponse> TrainWithHttpMessagesAsync(string kbId, FeedbackRecordsDTO trainPayload, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.RuntimeEndpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RuntimeEndpoint");
            }
            if (kbId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "kbId");
            }
            if (trainPayload == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "trainPayload");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("kbId", kbId);
                tracingParameters.Add("trainPayload", trainPayload);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Train", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "knowledgebases/{kbId}/train";

            _url = _url.Replace("{RuntimeEndpoint}", Client.RuntimeEndpoint);
            _url = _url.Replace("{kbId}", System.Uri.EscapeDataString(kbId));
            // 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 (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 (trainPayload != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(trainPayload, 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 != 204)
            {
                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 HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#12
0
 public AzureHDInsightRuntimeScriptActionOperationResource(RuntimeScriptAction runtimeScriptAction, ErrorResponseException errorResponse)
     : base(runtimeScriptAction)
 {
     if (errorResponse != null)
     {
         ErrorMessage   = errorResponse.Body?.Message;
         OperationState = errorResponse.Body?.Code;
     }
     else
     {
         OperationState = AsyncOperationState.Succeeded.ToString();
     }
 }
示例#13
0
        /// <summary>
        /// Returns a list of storage accounts.
        /// </summary>
        /// <param name='location'>
        /// Resource location.
        /// </param>
        /// <param name='filter'>
        /// Filter string
        /// </param>
        /// <param name='summary'>
        /// Switch for whether summary or detailed information is returned.
        /// </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 <StorageAccount> > > ListWithHttpMessagesAsync(string location, string filter = default(string), bool?summary = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (location == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "location");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("location", location);
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("summary", summary);
                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.Storage.Admin/locations/{location}/storageaccounts").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
            }
            if (summary != null)
            {
                _queryParameters.Add(string.Format("summary={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(summary, Client.SerializationSettings).Trim('"'))));
            }
            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);
                }
            }

            // add Prefer: odata.maxpagesize=1000 for paging
            if (_httpRequest.Headers.Contains("Prefer"))
            {
                _httpRequest.Headers.Remove("Prefer");
            }
            _httpRequest.Headers.TryAddWithoutValidation("Prefer", "odata.maxpagesize=1000");

            // 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 <StorageAccount> >();

            _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 <StorageAccount> >(_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 Timeseries for a given Experiment
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Name of the Resource group within the Azure subscription.
        /// </param>
        /// <param name='profileName'>
        /// The Profile identifier associated with the Tenant and Partner
        /// </param>
        /// <param name='experimentName'>
        /// The Experiment identifier associated with the Experiment
        /// </param>
        /// <param name='startDateTimeUTC'>
        /// The start DateTime of the Timeseries in UTC
        /// </param>
        /// <param name='endDateTimeUTC'>
        /// The end DateTime of the Timeseries in UTC
        /// </param>
        /// <param name='aggregationInterval'>
        /// The aggregation interval of the Timeseries. Possible values include:
        /// 'Hourly', 'Daily'
        /// </param>
        /// <param name='timeseriesType'>
        /// The type of Timeseries. Possible values include: 'MeasurementCounts',
        /// 'LatencyP50', 'LatencyP75', 'LatencyP95'
        /// </param>
        /// <param name='endpoint'>
        /// The specific endpoint
        /// </param>
        /// <param name='country'>
        /// The country associated with the Timeseries. Values are country ISO codes as
        /// specified here- https://www.iso.org/iso-3166-country-codes.html
        /// </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 <Timeseries> > GetTimeseriesWithHttpMessagesAsync(string resourceGroupName, string profileName, string experimentName, System.DateTime startDateTimeUTC, System.DateTime endDateTimeUTC, string aggregationInterval, string timeseriesType, string endpoint = default(string), string country = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 80)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80);
                }
                if (resourceGroupName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$");
                }
            }
            if (profileName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
            }
            if (profileName != null)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(profileName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "profileName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$");
                }
            }
            if (experimentName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "experimentName");
            }
            if (experimentName != null)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(experimentName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "experimentName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$");
                }
            }
            if (aggregationInterval == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "aggregationInterval");
            }
            if (timeseriesType == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "timeseriesType");
            }
            string apiVersion = "2019-11-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("apiVersion", apiVersion);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("profileName", profileName);
                tracingParameters.Add("experimentName", experimentName);
                tracingParameters.Add("startDateTimeUTC", startDateTimeUTC);
                tracingParameters.Add("endDateTimeUTC", endDateTimeUTC);
                tracingParameters.Add("aggregationInterval", aggregationInterval);
                tracingParameters.Add("timeseriesType", timeseriesType);
                tracingParameters.Add("endpoint", endpoint);
                tracingParameters.Add("country", country);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetTimeseries", 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.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}/Timeseries").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{profileName}", System.Uri.EscapeDataString(profileName));
            _url = _url.Replace("{experimentName}", System.Uri.EscapeDataString(experimentName));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            _queryParameters.Add(string.Format("startDateTimeUTC={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(startDateTimeUTC, Client.SerializationSettings).Trim('"'))));
            _queryParameters.Add(string.Format("endDateTimeUTC={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(endDateTimeUTC, Client.SerializationSettings).Trim('"'))));
            if (aggregationInterval != null)
            {
                _queryParameters.Add(string.Format("aggregationInterval={0}", System.Uri.EscapeDataString(aggregationInterval)));
            }
            if (timeseriesType != null)
            {
                _queryParameters.Add(string.Format("timeseriesType={0}", System.Uri.EscapeDataString(timeseriesType)));
            }
            if (endpoint != null)
            {
                _queryParameters.Add(string.Format("endpoint={0}", System.Uri.EscapeDataString(endpoint)));
            }
            if (country != null)
            {
                _queryParameters.Add(string.Format("country={0}", System.Uri.EscapeDataString(country)));
            }
            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 <Timeseries>();

            _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 <Timeseries>(_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);
        }
示例#15
0
        /// <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='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 <IEnumerable <MetricInner> > > ListWithHttpMessagesAsync(string resourceUri, ODataQuery <MetricInner> odataQuery = default(ODataQuery <MetricInner>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceUri == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
            }
            string apiVersion = "2016-09-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("apiVersion", apiVersion);
                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 (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 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 <IEnumerable <MetricInner> >();

            _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 <MetricInner> >(_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);
        }
        private void SynchronizeInternalAsync(ISyncCallback callback, long syncSequenceId, int retry)
        {
            if (retry < 0)
            {
                var e = new SyncConflictingException();

                if (Logger.LoggingConfig.LogInnerMostError)
                {
                    _logger.Error(e, "Sync failed due to retry less than 0");
                }

                callback.OnError(this, new SyncConflictingException());
                return;
            }

            // pull from remote

            var lastSyncRevisions = _local.GetLastSyncRevision(IdentityId, Name);

            _remote.ListUpdatesAsync(IdentityId, Name, lastSyncRevisions,
                                     (listUpdatesErr, datasetUpdates) =>
            {
                if (syncSequenceId != _currentSyncSequenceId)
                {
                    var e = new SyncCanceledException();
                    callback.OnError(this, e);

                    if (Logger.LoggingConfig.LogInnerMostError)
                    {
                        _logger.Error(e, "INTERNAL LOG - Sync Failed due to inconsistent syncSequenceId.");
                    }

                    return;
                }

                if (listUpdatesErr != null)
                {
                    var e = new SyncNetworkException("Failed to pull from remote", listUpdatesErr);

                    if (Logger.LoggingConfig.LogInnerMostError)
                    {
                        _logger.Error(e, "INTERNAL LOG - Failed to pull from remote");
                    }

                    callback.OnError(this, e);
                    return;
                }

                if (!MergeRemoteRecords(callback, datasetUpdates))
                {
                    return;
                }

                // push to remote.
                // includes the records whose region is different.
                var localChanges = _local.GetDirtyRecords(IdentityId, Name);

                if (localChanges.Count == 0)
                {
                    callback.OnSuccess(this);
                    return;
                }

                _remote.PutRecordsAsync(IdentityId, Name,
                                        SdkUtils.ConvertSyncRevisionToString(datasetUpdates.SyncRevisions),
                                        datasetUpdates.SyncSessionToken, localChanges, (putErr, putResult) =>
                {
                    if (syncSequenceId != _currentSyncSequenceId)
                    {
                        var e = new SyncCanceledException();

                        if (Logger.LoggingConfig.LogInnerMostError)
                        {
                            _logger.Error(e, "INTERNAL LOG - Sync failed due to inconsistency of syncSequenceId");
                        }

                        callback.OnError(this, e);
                        return;
                    }

                    if (putErr != null)
                    {
                        if (Logger.LoggingConfig.LogInnerMostError)
                        {
                            _logger.Error(putErr, "INTERNAL LOG - Failed to push to remote: {0}", putErr.Message);
                        }

                        if (ErrorResponseException.IsDatasetConflict(putErr))
                        {
                            SynchronizeInternalAsync(callback, syncSequenceId, --retry);
                            return;
                        }

                        callback.OnError(this, new SyncNetworkException("Failed to push to remote", putErr));
                        return;
                    }

                    _local.ConditionallyPutRecords(IdentityId, Name, putResult.Records, localChanges);
                    _local.UpdateLastSyncRevision(IdentityId, Name, putResult.SyncRevisions);

                    callback.OnSuccess(this);
                });
            });
        }
        /// <summary>
        /// Elevates the caller's access to match their billing profile access.
        /// </summary>
        /// <param name='billingAccountName'>
        /// billing Account Id.
        /// </param>
        /// <param name='invoiceSectionName'>
        /// InvoiceSection Id.
        /// </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="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> ElevateToBillingProfileWithHttpMessagesAsync(string billingAccountName, string invoiceSectionName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (billingAccountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "billingAccountName");
            }
            if (invoiceSectionName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "invoiceSectionName");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("billingAccountName", billingAccountName);
                tracingParameters.Add("invoiceSectionName", invoiceSectionName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ElevateToBillingProfile", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/elevate").ToString();

            _url = _url.Replace("{billingAccountName}", System.Uri.EscapeDataString(billingAccountName));
            _url = _url.Replace("{invoiceSectionName}", System.Uri.EscapeDataString(invoiceSectionName));
            List <string> _queryParameters = new List <string>();

            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;

            // 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 != 204)
            {
                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();

            _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);
        }
示例#18
0
 private static void VerifyCode(ErrorResponseException exception, HttpStatusCode code)
 {
     exception.StatusCode.Should().Be(code);
 }
示例#19
0
        /// <summary>
        /// Post a collection of goal instances
        /// </summary>
        /// <param name='goalsWrapper'>
        /// The collection of goal instances to create.
        /// </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 <HttpOperationResponse <GoalsResponse> > CreateWithHttpMessagesAsync(GoalsWrapper goalsWrapper, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (goalsWrapper == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "goalsWrapper");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("goalsWrapper", goalsWrapper);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Goals").ToString();
            // 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 (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 (goalsWrapper != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(goalsWrapper, 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 != 201)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Microsoft.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 HttpOperationResponse <GoalsResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <GoalsResponse>(_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);
        }
示例#20
0
        /// <summary>
        /// Re-generates an endpoint key.
        /// </summary>
        /// <param name='keyType'>
        /// Type of Key
        /// </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 <HttpOperationResponse <EndpointKeysDTO> > RefreshKeysWithHttpMessagesAsync(string keyType, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (keyType == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "keyType");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("keyType", keyType);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "RefreshKeys", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "endpointkeys/{keyType}";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            _url = _url.Replace("{keyType}", System.Uri.EscapeDataString(keyType));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            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 HttpOperationResponse <EndpointKeysDTO>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <EndpointKeysDTO>(_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>
        /// The Custom Image Search API lets you send an image search query to Bing and
        /// get image results found in your custom view of the web.
        /// </summary>
        /// <param name='customConfig'>
        /// The identifier for the custom search configuration
        /// </param>
        /// <param name='query'>
        /// The user's search query term. The term cannot be empty. The term may
        /// contain [Bing Advanced
        /// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example,
        /// to limit images to a specific domain, use the
        /// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help
        /// improve relevance of an insights query (see
        /// [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
        /// you should always include the user's query term. Use this parameter only
        /// with the Image Search API.Do not specify this parameter when calling the
        /// Trending Images API.
        /// </param>
        /// <param name='acceptLanguage'>
        /// A comma-delimited list of one or more languages to use for user interface
        /// strings. The list is in decreasing order of preference. For additional
        /// information, including expected format, see
        /// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
        /// header and the
        /// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang)
        /// query parameter are mutually exclusive; do not specify both. If you set
        /// this header, you must also specify the
        /// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc)
        /// query parameter. To determine the market to return results for, Bing uses
        /// the first supported language it finds from the list and combines it with
        /// the cc parameter value. If the list does not include a supported language,
        /// Bing finds the closest language and market that supports the request or it
        /// uses an aggregated or default market for the results. To determine the
        /// market that Bing used, see the BingAPIs-Market header. Use this header and
        /// the cc query parameter only if you specify multiple languages. Otherwise,
        /// use the
        /// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt)
        /// and
        /// [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang)
        /// query parameters. A user interface string is a string that's used as a
        /// label in a user interface. There are few user interface strings in the JSON
        /// response objects. Any links to Bing.com properties in the response objects
        /// apply the specified language.
        /// </param>
        /// <param name='userAgent'>
        /// The user agent originating the request. Bing uses the user agent to provide
        /// mobile users with an optimized experience. Although optional, you are
        /// encouraged to always specify this header. The user-agent should be the same
        /// string that any commonly used browser sends. For information about user
        /// agents, see [RFC
        /// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
        /// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
        /// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
        /// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
        /// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
        /// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
        /// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
        /// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
        /// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
        /// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
        /// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
        /// </param>
        /// <param name='clientId'>
        /// Bing uses this header to provide users with consistent behavior across Bing
        /// API calls. Bing often flights new features and improvements, and it uses
        /// the client ID as a key for assigning traffic on different flights. If you
        /// do not use the same client ID for a user across multiple requests, then
        /// Bing may assign the user to multiple conflicting flights. Being assigned to
        /// multiple conflicting flights can lead to an inconsistent user experience.
        /// For example, if the second request has a different flight assignment than
        /// the first, the experience may be unexpected. Also, Bing can use the client
        /// ID to tailor web results to that client ID’s search history, providing a
        /// richer experience for the user. Bing also uses this header to help improve
        /// result rankings by analyzing the activity generated by a client ID. The
        /// relevance improvements help with better quality of results delivered by
        /// Bing APIs and in turn enables higher click-through rates for the API
        /// consumer. IMPORTANT: Although optional, you should consider this header
        /// required. Persisting the client ID across multiple requests for the same
        /// end user and device combination enables 1) the API consumer to receive a
        /// consistent user experience, and 2) higher click-through rates via better
        /// quality of results from the Bing APIs. Each user that uses your application
        /// on the device must have a unique, Bing generated client ID. If you do not
        /// include this header in the request, Bing generates an ID and returns it in
        /// the X-MSEdge-ClientID response header. The only time that you should NOT
        /// include this header in a request is the first time the user uses your app
        /// on that device. Use the client ID for each Bing API request that your app
        /// makes for this user on the device. Persist the client ID. To persist the ID
        /// in a browser app, use a persistent HTTP cookie to ensure the ID is used
        /// across all sessions. Do not use a session cookie. For other apps such as
        /// mobile apps, use the device's persistent storage to persist the ID. The
        /// next time the user uses your app on that device, get the client ID that you
        /// persisted. Bing responses may or may not include this header. If the
        /// response includes this header, capture the client ID and use it for all
        /// subsequent Bing requests for the user on that device. If you include the
        /// X-MSEdge-ClientID, you must not include cookies in the request.
        /// </param>
        /// <param name='clientIp'>
        /// The IPv4 or IPv6 address of the client device. The IP address is used to
        /// discover the user's location. Bing uses the location information to
        /// determine safe search behavior. Although optional, you are encouraged to
        /// always specify this header and the X-Search-Location header. Do not
        /// obfuscate the address (for example, by changing the last octet to 0).
        /// Obfuscating the address results in the location not being anywhere near the
        /// device's actual location, which may result in Bing serving erroneous
        /// results.
        /// </param>
        /// <param name='location'>
        /// A semicolon-delimited list of key/value pairs that describe the client's
        /// geographical location. Bing uses the location information to determine safe
        /// search behavior and to return relevant local content. Specify the key/value
        /// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
        /// to specify the user's location. lat (required): The latitude of the
        /// client's location, in degrees. The latitude must be greater than or equal
        /// to -90.0 and less than or equal to +90.0. Negative values indicate southern
        /// latitudes and positive values indicate northern latitudes. long (required):
        /// The longitude of the client's location, in degrees. The longitude must be
        /// greater than or equal to -180.0 and less than or equal to +180.0. Negative
        /// values indicate western longitudes and positive values indicate eastern
        /// longitudes. re (required): The radius, in meters, which specifies the
        /// horizontal accuracy of the coordinates. Pass the value returned by the
        /// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
        /// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
        /// (optional): The UTC UNIX timestamp of when the client was at the location.
        /// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
        /// (optional): The client's relative heading or direction of travel. Specify
        /// the direction of travel as degrees from 0 through 360, counting clockwise
        /// relative to true north. Specify this key only if the sp key is nonzero. sp
        /// (optional): The horizontal velocity (speed), in meters per second, that the
        /// client device is traveling. alt (optional): The altitude of the client
        /// device, in meters. are (optional): The radius, in meters, that specifies
        /// the vertical accuracy of the coordinates. Specify this key only if you
        /// specify the alt key. Although many of the keys are optional, the more
        /// information that you provide, the more accurate the location results are.
        /// Although optional, you are encouraged to always specify the user's
        /// geographical location. Providing the location is especially important if
        /// the client's IP address does not accurately reflect the user's physical
        /// location (for example, if the client uses VPN). For optimal results, you
        /// should include this header and the X-MSEdge-ClientIP header, but at a
        /// minimum, you should include this header.
        /// </param>
        /// <param name='aspect'>
        /// Filter images by the following aspect ratios. All: Do not filter by
        /// aspect.Specifying this value is the same as not specifying the aspect
        /// parameter. Square: Return images with standard aspect ratio. Wide: Return
        /// images with wide screen aspect ratio. Tall: Return images with tall aspect
        /// ratio. Possible values include: 'All', 'Square', 'Wide', 'Tall'
        /// </param>
        /// <param name='color'>
        /// Filter images by the following color options. ColorOnly: Return color
        /// images. Monochrome: Return black and white images. Return images with one
        /// of the following dominant colors: Black, Blue, Brown, Gray, Green, Orange,
        /// Pink, Purple, Red, Teal, White, Yellow. Possible values include:
        /// 'ColorOnly', 'Monochrome', 'Black', 'Blue', 'Brown', 'Gray', 'Green',
        /// 'Orange', 'Pink', 'Purple', 'Red', 'Teal', 'White', 'Yellow'
        /// </param>
        /// <param name='countryCode'>
        /// A 2-character country code of the country where the results come from. For
        /// a list of possible values, see [Market
        /// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes).
        /// If you set this parameter, you must also specify the
        /// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
        /// header. Bing uses the first supported language it finds from the languages
        /// list, and combine that language with the country code that you specify to
        /// determine the market to return results for. If the languages list does not
        /// include a supported language, Bing finds the closest language and market
        /// that supports the request, or it may use an aggregated or default market
        /// for the results instead of a specified one. You should use this query
        /// parameter and the Accept-Language query parameter only if you specify
        /// multiple languages; otherwise, you should use the mkt and setLang query
        /// parameters. This parameter and the
        /// [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt)
        /// query parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='count'>
        /// The number of images to return in the response. The actual number delivered
        /// may be less than requested. The default is 35. The maximum value is 150.
        /// You use this parameter along with the offset parameter to page results.For
        /// example, if your user interface displays 20 images per page, set count to
        /// 20 and offset to 0 to get the first page of results.For each subsequent
        /// page, increment offset by 20 (for example, 0, 20, 40). Use this parameter
        /// only with the Image Search API.Do not specify this parameter when calling
        /// the Insights, Trending Images, or Web Search APIs.
        /// </param>
        /// <param name='freshness'>
        /// Filter images by the following discovery options. Day: Return images
        /// discovered by Bing within the last 24 hours. Week: Return images discovered
        /// by Bing within the last 7 days. Month: Return images discovered by Bing
        /// within the last 30 days. Possible values include: 'Day', 'Week', 'Month'
        /// </param>
        /// <param name='height'>
        /// Filter images that have the specified height, in pixels. You may use this
        /// filter with the size filter to return small images that have a height of
        /// 150 pixels.
        /// </param>
        /// <param name='id'>
        /// An ID that uniquely identifies an image. Use this parameter to ensure that
        /// the specified image is the first image in the list of images that Bing
        /// returns. The
        /// [Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image)
        /// object's imageId field contains the ID that you set this parameter to.
        /// </param>
        /// <param name='imageContent'>
        /// Filter images by the following content types. Face: Return images that show
        /// only a person's face. Portrait: Return images that show only a person's
        /// head and shoulders. Possible values include: 'Face', 'Portrait'
        /// </param>
        /// <param name='imageType'>
        /// Filter images by the following image types. AnimatedGif: Return only
        /// animated GIFs. Clipart: Return only clip art images. Line: Return only line
        /// drawings. Photo: Return only photographs(excluding line drawings, animated
        /// Gifs, and clip art). Shopping: Return only images that contain items where
        /// Bing knows of a merchant that is selling the items. This option is valid in
        /// the en - US market only.Transparent: Return only images with a transparent
        /// background. Possible values include: 'AnimatedGif', 'Clipart', 'Line',
        /// 'Photo', 'Shopping', 'Transparent'
        /// </param>
        /// <param name='license'>
        /// Filter images by the following license types. All: Do not filter by license
        /// type.Specifying this value is the same as not specifying the license
        /// parameter. Any: Return images that are under any license type. The response
        /// doesn't include images that do not specify a license or the license is
        /// unknown. Public: Return images where the creator has waived their exclusive
        /// rights, to the fullest extent allowed by law. Share: Return images that may
        /// be shared with others. Changing or editing the image might not be allowed.
        /// Also, modifying, sharing, and using the image for commercial purposes might
        /// not be allowed. Typically, this option returns the most images.
        /// ShareCommercially: Return images that may be shared with others for
        /// personal or commercial purposes. Changing or editing the image might not be
        /// allowed. Modify: Return images that may be modified, shared, and used.
        /// Changing or editing the image might not be allowed. Modifying, sharing, and
        /// using the image for commercial purposes might not be allowed.
        /// ModifyCommercially: Return images that may be modified, shared, and used
        /// for personal or commercial purposes. Typically, this option returns the
        /// fewest images. For more information about these license types, see [Filter
        /// Images By License Type](http://go.microsoft.com/fwlink/?LinkId=309768).
        /// Possible values include: 'All', 'Any', 'Public', 'Share',
        /// 'ShareCommercially', 'Modify', 'ModifyCommercially'
        /// </param>
        /// <param name='market'>
        /// The market where the results come from. Typically, mkt is the country where
        /// the user is making the request from. However, it could be a different
        /// country if the user is not located in a country where Bing delivers
        /// results. The market must be in the form &lt;language code&gt;-&lt;country
        /// code&gt;. For example, en-US. The string is case insensitive. For a list of
        /// possible market values, see [Market
        /// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes).
        /// NOTE: If known, you are encouraged to always specify the market. Specifying
        /// the market helps Bing route the request and return an appropriate and
        /// optimal response. If you specify a market that is not listed in [Market
        /// Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes),
        /// Bing uses a best fit market code based on an internal mapping that is
        /// subject to change. This parameter and the
        /// [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc)
        /// query parameter are mutually exclusive—do not specify both.
        /// </param>
        /// <param name='maxFileSize'>
        /// Filter images that are less than or equal to the specified file size. The
        /// maximum file size that you may specify is 520,192 bytes. If you specify a
        /// larger value, the API uses 520,192. It is possible that the response may
        /// include images that are slightly larger than the specified maximum. You may
        /// specify this filter and minFileSize to filter images within a range of file
        /// sizes.
        /// </param>
        /// <param name='maxHeight'>
        /// Filter images that have a height that is less than or equal to the
        /// specified height. Specify the height in pixels. You may specify this filter
        /// and minHeight to filter images within a range of heights. This filter and
        /// the height filter are mutually exclusive.
        /// </param>
        /// <param name='maxWidth'>
        /// Filter images that have a width that is less than or equal to the specified
        /// width. Specify the width in pixels. You may specify this filter and
        /// maxWidth to filter images within a range of widths. This filter and the
        /// width filter are mutually exclusive.
        /// </param>
        /// <param name='minFileSize'>
        /// Filter images that are greater than or equal to the specified file size.
        /// The maximum file size that you may specify is 520,192 bytes. If you specify
        /// a larger value, the API uses 520,192. It is possible that the response may
        /// include images that are slightly smaller than the specified minimum. You
        /// may specify this filter and maxFileSize to filter images within a range of
        /// file sizes.
        /// </param>
        /// <param name='minHeight'>
        /// Filter images that have a height that is greater than or equal to the
        /// specified height. Specify the height in pixels. You may specify this filter
        /// and maxHeight to filter images within a range of heights. This filter and
        /// the height filter are mutually exclusive.
        /// </param>
        /// <param name='minWidth'>
        /// Filter images that have a width that is greater than or equal to the
        /// specified width. Specify the width in pixels. You may specify this filter
        /// and maxWidth to filter images within a range of widths. This filter and the
        /// width filter are mutually exclusive.
        /// </param>
        /// <param name='offset'>
        /// The zero-based offset that indicates the number of images to skip before
        /// returning images. The default is 0. The offset should be less than
        /// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#totalestimatedmatches)
        /// - count). Use this parameter along with the count parameter to page
        /// results. For example, if your user interface displays 20 images per page,
        /// set count to 20 and offset to 0 to get the first page of results. For each
        /// subsequent page, increment offset by 20 (for example, 0, 20, 40). It is
        /// possible for multiple pages to include some overlap in results. To prevent
        /// duplicates, see
        /// [nextOffset](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#nextoffset).
        /// Use this parameter only with the Image API. Do not specify this parameter
        /// when calling the Trending Images API or the Web Search API.
        /// </param>
        /// <param name='safeSearch'>
        /// Filter images for adult content. The following are the possible filter
        /// values. Off: May return images with adult content. If the request is
        /// through the Image Search API, the response includes thumbnail images that
        /// are clear (non-fuzzy). However, if the request is through the Web Search
        /// API, the response includes thumbnail images that are pixelated (fuzzy).
        /// Moderate: If the request is through the Image Search API, the response
        /// doesn't include images with adult content. If the request is through the
        /// Web Search API, the response may include images with adult content (the
        /// thumbnail images are pixelated (fuzzy)). Strict: Do not return images with
        /// adult content. The default is Moderate. If the request comes from a market
        /// that Bing's adult policy requires that safeSearch is set to Strict, Bing
        /// ignores the safeSearch value and uses Strict. If you use the site: query
        /// operator, there is the chance that the response may contain adult content
        /// regardless of what the safeSearch query parameter is set to. Use site: only
        /// if you are aware of the content on the site and your scenario supports the
        /// possibility of adult content. Possible values include: 'Off', 'Moderate',
        /// 'Strict'
        /// </param>
        /// <param name='size'>
        /// Filter images by the following sizes. All: Do not filter by size.
        /// Specifying this value is the same as not specifying the size parameter.
        /// Small: Return images that are less than 200x200 pixels. Medium: Return
        /// images that are greater than or equal to 200x200 pixels but less than
        /// 500x500 pixels. Large: Return images that are 500x500 pixels or larger.
        /// Wallpaper: Return wallpaper images. You may use this parameter along with
        /// the height or width parameters. For example, you may use height and size to
        /// request small images that are 150 pixels tall. Possible values include:
        /// 'All', 'Small', 'Medium', 'Large', 'Wallpaper'
        /// </param>
        /// <param name='setLang'>
        /// The language to use for user interface strings. Specify the language using
        /// the ISO 639-1 2-letter language code. For example, the language code for
        /// English is EN. The default is EN (English). Although optional, you should
        /// always specify the language. Typically, you set setLang to the same
        /// language specified by mkt unless the user wants the user interface strings
        /// displayed in a different language. This parameter and the
        /// [Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
        /// header are mutually exclusive; do not specify both. A user interface string
        /// is a string that's used as a label in a user interface. There are few user
        /// interface strings in the JSON response objects. Also, any links to Bing.com
        /// properties in the response objects apply the specified language.
        /// </param>
        /// <param name='width'>
        /// Filter images that have the specified width, in pixels. You may use this
        /// filter with the size filter to return small images that have a width of 150
        /// pixels.
        /// </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<HttpOperationResponse<Images>> ImageSearchWithHttpMessagesAsync(string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string aspect = default(string), string color = default(string), string countryCode = default(string), int? count = default(int?), string freshness = default(string), int? height = default(int?), string id = default(string), string imageContent = default(string), string imageType = default(string), string license = default(string), string market = default(string), long? maxFileSize = default(long?), long? maxHeight = default(long?), long? maxWidth = default(long?), long? minFileSize = default(long?), long? minHeight = default(long?), long? minWidth = default(long?), long? offset = default(long?), string safeSearch = default(string), string size = default(string), string setLang = default(string), int? width = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (customConfig == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "customConfig");
            }
            if (query == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "query");
            }
            string xBingApisSDK = "true";
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("xBingApisSDK", xBingApisSDK);
                tracingParameters.Add("acceptLanguage", acceptLanguage);
                tracingParameters.Add("userAgent", userAgent);
                tracingParameters.Add("clientId", clientId);
                tracingParameters.Add("clientIp", clientIp);
                tracingParameters.Add("location", location);
                tracingParameters.Add("customConfig", customConfig);
                tracingParameters.Add("aspect", aspect);
                tracingParameters.Add("color", color);
                tracingParameters.Add("countryCode", countryCode);
                tracingParameters.Add("count", count);
                tracingParameters.Add("freshness", freshness);
                tracingParameters.Add("height", height);
                tracingParameters.Add("id", id);
                tracingParameters.Add("imageContent", imageContent);
                tracingParameters.Add("imageType", imageType);
                tracingParameters.Add("license", license);
                tracingParameters.Add("market", market);
                tracingParameters.Add("maxFileSize", maxFileSize);
                tracingParameters.Add("maxHeight", maxHeight);
                tracingParameters.Add("maxWidth", maxWidth);
                tracingParameters.Add("minFileSize", minFileSize);
                tracingParameters.Add("minHeight", minHeight);
                tracingParameters.Add("minWidth", minWidth);
                tracingParameters.Add("offset", offset);
                tracingParameters.Add("query", query);
                tracingParameters.Add("safeSearch", safeSearch);
                tracingParameters.Add("size", size);
                tracingParameters.Add("setLang", setLang);
                tracingParameters.Add("width", width);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ImageSearch", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "images/search";
            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            List<string> _queryParameters = new List<string>();
            if (customConfig != null)
            {
                _queryParameters.Add(string.Format("customConfig={0}", System.Uri.EscapeDataString(customConfig)));
            }
            if (aspect != null)
            {
                _queryParameters.Add(string.Format("aspect={0}", System.Uri.EscapeDataString(aspect)));
            }
            if (color != null)
            {
                _queryParameters.Add(string.Format("color={0}", System.Uri.EscapeDataString(color)));
            }
            if (countryCode != null)
            {
                _queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
            }
            if (count != null)
            {
                _queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
            }
            if (freshness != null)
            {
                _queryParameters.Add(string.Format("freshness={0}", System.Uri.EscapeDataString(freshness)));
            }
            if (height != null)
            {
                _queryParameters.Add(string.Format("height={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(height, Client.SerializationSettings).Trim('"'))));
            }
            if (id != null)
            {
                _queryParameters.Add(string.Format("id={0}", System.Uri.EscapeDataString(id)));
            }
            if (imageContent != null)
            {
                _queryParameters.Add(string.Format("imageContent={0}", System.Uri.EscapeDataString(imageContent)));
            }
            if (imageType != null)
            {
                _queryParameters.Add(string.Format("imageType={0}", System.Uri.EscapeDataString(imageType)));
            }
            if (license != null)
            {
                _queryParameters.Add(string.Format("license={0}", System.Uri.EscapeDataString(license)));
            }
            if (market != null)
            {
                _queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
            }
            if (maxFileSize != null)
            {
                _queryParameters.Add(string.Format("maxFileSize={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxFileSize, Client.SerializationSettings).Trim('"'))));
            }
            if (maxHeight != null)
            {
                _queryParameters.Add(string.Format("maxHeight={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxHeight, Client.SerializationSettings).Trim('"'))));
            }
            if (maxWidth != null)
            {
                _queryParameters.Add(string.Format("maxWidth={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxWidth, Client.SerializationSettings).Trim('"'))));
            }
            if (minFileSize != null)
            {
                _queryParameters.Add(string.Format("minFileSize={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minFileSize, Client.SerializationSettings).Trim('"'))));
            }
            if (minHeight != null)
            {
                _queryParameters.Add(string.Format("minHeight={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minHeight, Client.SerializationSettings).Trim('"'))));
            }
            if (minWidth != null)
            {
                _queryParameters.Add(string.Format("minWidth={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minWidth, Client.SerializationSettings).Trim('"'))));
            }
            if (offset != null)
            {
                _queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(offset, Client.SerializationSettings).Trim('"'))));
            }
            if (query != null)
            {
                _queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
            }
            if (safeSearch != null)
            {
                _queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
            }
            if (size != null)
            {
                _queryParameters.Add(string.Format("size={0}", System.Uri.EscapeDataString(size)));
            }
            if (setLang != null)
            {
                _queryParameters.Add(string.Format("setLang={0}", System.Uri.EscapeDataString(setLang)));
            }
            if (width != null)
            {
                _queryParameters.Add(string.Format("width={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(width, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + 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 (xBingApisSDK != null)
            {
                if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
                {
                    _httpRequest.Headers.Remove("X-BingApis-SDK");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
            }
            if (acceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("Accept-Language"))
                {
                    _httpRequest.Headers.Remove("Accept-Language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
            }
            if (userAgent != null)
            {
                if (_httpRequest.Headers.Contains("User-Agent"))
                {
                    _httpRequest.Headers.Remove("User-Agent");
                }
                _httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
            }
            if (clientId != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientID");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
            }
            if (clientIp != null)
            {
                if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
                {
                    _httpRequest.Headers.Remove("X-MSEdge-ClientIP");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
            }
            if (location != null)
            {
                if (_httpRequest.Headers.Contains("X-Search-Location"))
                {
                    _httpRequest.Headers.Remove("X-Search-Location");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
            }


            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 HttpOperationResponse<Images>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Images>(_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;
        }
示例#22
0
        protected override void ProcessRecordInternal()
        {
            if (ShouldProcess(
                    target: string.Format("Create/update a diagnostic setting for resource Id: {0}", this.ResourceId),
                    action: "Create/update a diagnostic setting"))
            {
                WriteWarningWithTimestamp("The arguments Categories and Timegrains now have aliases Category and Timegrain respectively. The plural names will be removed in future releases.");
                DiagnosticSettingsResource properties;

                // Name defaults to 'service'
                string settingName = string.IsNullOrWhiteSpace(this.Name) ? TempServiceName : this.Name.Trim();

                if (this.InputObject == null)
                {
                    // If InputObject is null process the way it was done before
                    WriteDebugWithTimestamp("Processing using command line arguments");
                    HashSet <string> usedParams = new HashSet <string>(this.MyInvocation.BoundParameters.Keys, StringComparer.OrdinalIgnoreCase);

                    this.isStorageParamPresent      = usedParams.Contains(StorageAccountIdParamName);
                    this.isServiceBusParamPresent   = usedParams.Contains(ServiceBusRuleIdParamName);
                    this.isEventHubParamPresent     = usedParams.Contains(EventHubNameParamName);
                    this.isEventHubRuleParamPresent = usedParams.Contains(EventHubRuleIdParamName);
                    this.isWorkspaceParamPresent    = usedParams.Contains(WorkspacetIdParamName);
                    this.isEnbledParameterPresent   = usedParams.Contains(EnabledParamName);

                    if (!this.isStorageParamPresent &&
                        !this.isServiceBusParamPresent &&
                        !this.isEventHubParamPresent &&
                        !this.isEventHubRuleParamPresent &&
                        !this.isWorkspaceParamPresent &&
                        !this.isEnbledParameterPresent)
                    {
                        throw new ArgumentException("No operation is specified");
                    }

                    try
                    {
                        WriteDebugWithTimestamp(string.Format(CultureInfo.InvariantCulture, "Listing existing diagnostics settings for resourceId '{0}'", this.ResourceId));
                        IList <DiagnosticSettingsResource> listSettings   = this.MonitorManagementClient.DiagnosticSettings.ListAsync(resourceUri: this.ResourceId, cancellationToken: CancellationToken.None).Result.Value;
                        DiagnosticSettingsResource         singleResource = listSettings.FirstOrDefault(e => string.Equals(e.Name, settingName, StringComparison.OrdinalIgnoreCase));
                        if (singleResource == null)
                        {
                            // Creating a new setting with settingName as name
                            WriteDebugWithTimestamp(string.Format(CultureInfo.InvariantCulture, "Diagnostic setting named: '{0}' not found in list of {1} settings. Creating a new one.", settingName, listSettings.Count));

                            properties         = new DiagnosticSettingsResource();
                            properties.Logs    = new List <LogSettings>();
                            properties.Metrics = new List <MetricSettings>();
                        }
                        else
                        {
                            // Updating existing name, regardless of name
                            WriteDebugWithTimestamp(string.Format(CultureInfo.InvariantCulture, "Updating existing diagnostic setting '{0}'", settingName));
                            properties = singleResource;
                        }
                    }
                    catch (AggregateException ex)
                    {
                        WriteDebugWithTimestamp("Aggregate exception {0}", ex.ToString());
                        ErrorResponseException ex1 = ex.InnerException as ErrorResponseException;
                        if (ex1 != null && ex1.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            WriteDebugWithTimestamp("Inner exception is NotFound");
                            properties         = new DiagnosticSettingsResource();
                            properties.Logs    = new List <LogSettings>();
                            properties.Metrics = new List <MetricSettings>();
                        }
                        else
                        {
                            WriteDebugWithTimestamp("Inner exception is different NotFound: {0}", ex.InnerException.ToString());
                            throw ex.InnerException;
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteDebugWithTimestamp("Unexpected exception thrown: {0}", ex.ToString());
                        throw;
                    }

                    WriteDebugWithTimestamp("Merging data. Existing setting is: {0}", properties == null ? "null" : "not null");
                    SetStorage(properties);

                    SetServiceBus(properties);

                    SetEventHubRule(properties);

                    SetWorkspace(properties);

                    if (this.Categories == null && this.MetricCategory == null && this.Timegrains == null)
                    {
                        WriteDebugWithTimestamp("Changing the enable properties");
                        SetAllCategoriesAndTimegrains(properties);
                    }
                    else
                    {
                        WriteDebugWithTimestamp("Setting categories and time grains");
                        if (this.Categories != null)
                        {
                            SetSelectedCategories(properties);
                        }

                        if (this.MetricCategory != null)
                        {
                            SetSelectedMetricsCategories(properties);
                        }

                        if (this.Timegrains != null)
                        {
                            SetSelectedTimegrains(properties);
                        }
                    }

                    if (this.RetentionEnabled.HasValue)
                    {
                        WriteDebugWithTimestamp("Setting retention");
                        SetRetention(properties);
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(this.InputObject.Id) || string.IsNullOrWhiteSpace(this.InputObject.Name))
                    {
                        throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "InputObject is inconsistent: Id is incomplete or malformed, Id: '{0}', Name: '{1}'", this.InputObject.Id, this.InputObject.Name));
                    }

                    // This is new functionality to keep the previous as it was before
                    WriteDebugWithTimestamp("Processing using InputObject");
                    properties = this.InputObject;

                    // Take Name and ResourceId from the input Object
                    string idSuffix = "/diagnosticSettings/" + this.InputObject.Name;
                    bool   foundCue = this.InputObject.Id.EndsWith(idSuffix);
                    if (foundCue)
                    {
                        this.ResourceId = this.InputObject.Id.Substring(0, this.InputObject.Id.Length - idSuffix.Length);
                        settingName     = this.InputObject.Name;
                    }
                    else
                    {
                        throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "InputObject is inconsistent: Id is incomplete or malformed, Id: '{0}', Name: '{1}'", this.InputObject.Id, this.InputObject.Name));
                    }
                }

                WriteDebugWithTimestamp("Copying diagnostic settings");
                DiagnosticSettingsResource putParameters = CopySettings(properties);

                WriteDebugWithTimestamp(string.Format(CultureInfo.InvariantCulture, "Sending create/update request setting: {0}", settingName));
                DiagnosticSettingsResource result = this.MonitorManagementClient.DiagnosticSettings.CreateOrUpdateAsync(
                    resourceUri: this.ResourceId,
                    name: settingName,
                    parameters: putParameters,
                    cancellationToken: CancellationToken.None).Result;

                WriteDebugWithTimestamp("Successful operation. Sending output");
                WriteObject(new PSServiceDiagnosticSettings(result));
            }
        }
        /// <summary>
        /// Gets the operation status for a private endpoint connection.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='operationId'>
        /// Operation id
        /// </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 <OperationStatus> > GetOperationStatusWithHttpMessagesAsync(string vaultName, string resourceGroupName, string privateEndpointConnectionName, string operationId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (vaultName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
            }
            if (privateEndpointConnectionName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName");
            }
            if (operationId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "operationId");
            }
            string apiVersion = "2020-02-02";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("vaultName", vaultName);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("privateEndpointConnectionName", privateEndpointConnectionName);
                tracingParameters.Add("operationId", operationId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetOperationStatus", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}/operationsStatus/{operationId}").ToString();

            _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
            _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName));
            _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
            List <string> _queryParameters = new List <string>();

            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 (GenerateClientRequestId != null && GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, 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 <OperationStatus>();

            _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 = SafeJsonConvert.DeserializeObject <OperationStatus>(_responseContent, 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);
        }
示例#24
0
        /// <summary>
        /// Deletes a private endpoint connection with a given name.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group. The name is case insensitive.
        /// </param>
        /// <param name='accountName'>
        /// Cosmos DB database account name.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </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="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string privateEndpointConnectionName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            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);
                }
            }
            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 (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 (accountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
            }
            if (accountName != null)
            {
                if (accountName.Length > 50)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
                }
                if (accountName.Length < 3)
                {
                    throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
                }
            }
            if (privateEndpointConnectionName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName");
            }
            // 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("privateEndpointConnectionName", privateEndpointConnectionName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
            _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName));
            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("DELETE");
            _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 != 202 && (int)_statusCode != 204)
            {
                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();

            _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 a collection of properties defined within a service instance.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the API Management service.
        /// </param>
        /// <param name='top'>
        /// Number of records to return.
        /// </param>
        /// <param name='skip'>
        /// Number of records to skip.
        /// </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 <NotificationContract> > > ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, int?top = default(int?), int?skip = default(int?), 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 (top < 1)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "top", 1);
            }
            if (skip < 0)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "skip", 0);
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2019-12-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("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("top", top);
                tracingParameters.Add("skip", skip);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListByService", 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}/notifications").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (top != null)
            {
                _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
            }
            if (skip != null)
            {
                _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
            }
            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 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 <NotificationContract> >();

            _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 <NotificationContract> >(_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);
        }
示例#26
0
        /// <summary>
        /// Executes a query that allows traversing relationships and filtering by
        /// property values.
        /// Status codes:
        /// 200 (OK): Success.
        /// 400 (Bad Request): The request is invalid.
        /// </summary>
        /// <param name='querySpecification'>
        /// The query specification to execute.
        /// </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 <QueryResult, QueryQueryTwinsHeaders> > QueryTwinsWithHttpMessagesAsync(QuerySpecification querySpecification, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (querySpecification == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "querySpecification");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("querySpecification", querySpecification);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "QueryTwins", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "query").ToString();
            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("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 (querySpecification != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(querySpecification, 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Microsoft.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 <QueryResult, QueryQueryTwinsHeaders>();

            _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <QueryResult>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <QueryQueryTwinsHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#27
0
        /// <summary>
        /// Creates or updates a Sql pool data masking rule.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group. The name is case insensitive.
        /// </param>
        /// <param name='workspaceName'>
        /// The name of the workspace
        /// </param>
        /// <param name='sqlPoolName'>
        /// SQL pool name
        /// </param>
        /// <param name='dataMaskingRuleName'>
        /// The name of the data masking rule.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for creating or updating a data masking rule.
        /// </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 <DataMaskingRule> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string sqlPoolName, string dataMaskingRuleName, DataMaskingRule parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            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);
                }
            }
            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 (workspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
            }
            if (sqlPoolName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "sqlPoolName");
            }
            if (dataMaskingRuleName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "dataMaskingRuleName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            if (parameters != null)
            {
                parameters.Validate();
            }
            string dataMaskingPolicyName = "Default";
            // 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("workspaceName", workspaceName);
                tracingParameters.Add("sqlPoolName", sqlPoolName);
                tracingParameters.Add("dataMaskingPolicyName", dataMaskingPolicyName);
                tracingParameters.Add("dataMaskingRuleName", dataMaskingRuleName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/dataMaskingPolicies/{dataMaskingPolicyName}/rules/{dataMaskingRuleName}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
            _url = _url.Replace("{sqlPoolName}", System.Uri.EscapeDataString(sqlPoolName));
            _url = _url.Replace("{dataMaskingPolicyName}", System.Uri.EscapeDataString(dataMaskingPolicyName));
            _url = _url.Replace("{dataMaskingRuleName}", System.Uri.EscapeDataString(dataMaskingRuleName));
            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 && (int)_statusCode != 201)
            {
                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 <DataMaskingRule>();

            _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 <DataMaskingRule>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <DataMaskingRule>(_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);
        }
示例#28
0
        /// <summary>
        /// Execute an Analytics query
        /// </summary>
        /// <remarks>
        /// Executes an Analytics query for data.
        /// Please refer to<see href="https://docs.microsoft.com/azure/azure-monitor/logs/api/overview">this example</see> for using POST.
        /// with an Analytics query.
        /// </remarks>
        /// <param name='query'>
        /// The query to execute.
        /// </param>
        /// <param name='timespan'>
        /// Optional. The timespan over which to query data. This is an ISO8601 time
        /// period value.  This timespan is applied in addition to any that are
        /// specified in the query expression.
        /// </param>
        /// <param name='workspaces'>
        /// A list of workspaces that are included in the query.
        /// </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 <HttpOperationResponse <QueryResults> > QueryWithHttpMessagesAsync(string query, System.TimeSpan?timespan = default(System.TimeSpan?), IList <string> workspaces = default(IList <string>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (WorkspaceId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.WorkspaceId");
            }
            if (query == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "query");
            }
            QueryBody body = new QueryBody();

            if (query != null || timespan != null || workspaces != null)
            {
                body.Query      = query;
                body.Timespan   = timespan;
                body.Workspaces = workspaces;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Query", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "workspaces/{workspaceId}/query").ToString();

            _url = _url.Replace("{workspaceId}", System.Uri.EscapeDataString(WorkspaceId));
            // 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 (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 (body != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(body, 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 (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await 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 = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, 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 HttpOperationResponse <QueryResults>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <QueryResults>(_responseContent, 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);
        }