< Summary

Class:Microsoft.Azure.CognitiveServices.Language.TextAnalytics.TextAnalyticsClient
Assembly:Microsoft.Azure.CognitiveServices.Language.TextAnalytics
File(s):C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Language.TextAnalytics\src\Generated\TextAnalytics\TextAnalyticsClient.cs
Covered lines:205
Uncovered lines:169
Coverable lines:374
Total lines:918
Line coverage:54.8% (205 of 374)
Covered branches:67
Total branches:164
Branch coverage:40.8% (67 of 164)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
get_BaseUri()-100%100%
get_SerializationSettings()-100%100%
get_DeserializationSettings()-100%100%
get_Endpoint()-100%100%
get_Credentials()-100%100%
.ctor(...)-0%100%
.ctor(...)-100%100%
.ctor(...)-0%100%
.ctor(...)-85.71%75%
.ctor(...)-0%0%
.ctor(...)-0%0%
Initialize()-100%100%
DetectLanguageWithHttpMessagesAsync()-52.56%42.11%
EntitiesWithHttpMessagesAsync()-52.56%42.11%
KeyPhrasesWithHttpMessagesAsync()-52.56%42.11%
SentimentWithHttpMessagesAsync()-52.56%42.11%

File(s)

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Language.TextAnalytics\src\Generated\TextAnalytics\TextAnalyticsClient.cs

#LineLine coverage
 1// <auto-generated>
 2// Copyright (c) Microsoft Corporation. All rights reserved.
 3// Licensed under the MIT License. See License.txt in the project root for
 4// license information.
 5//
 6// Code generated by Microsoft (R) AutoRest Code Generator.
 7// Changes may cause incorrect behavior and will be lost if the code is
 8// regenerated.
 9// </auto-generated>
 10
 11namespace Microsoft.Azure.CognitiveServices.Language.TextAnalytics
 12{
 13    using Microsoft.Rest;
 14    using Microsoft.Rest.Serialization;
 15    using Models;
 16    using Newtonsoft.Json;
 17    using System.Collections;
 18    using System.Collections.Generic;
 19    using System.Net;
 20    using System.Net.Http;
 21    using System.Threading;
 22    using System.Threading.Tasks;
 23
 24    /// <summary>
 25    /// The Text Analytics API is a suite of text analytics web services built
 26    /// with best-in-class Microsoft machine learning algorithms. The API can
 27    /// be used to analyze unstructured text for tasks such as sentiment
 28    /// analysis, key phrase extraction and language detection. No training
 29    /// data is needed to use this API; just bring your text data. This API
 30    /// uses advanced natural language processing techniques to deliver best in
 31    /// class predictions. Further documentation can be found in
 32    /// https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview
 33    /// </summary>
 34    public partial class TextAnalyticsClient : ServiceClient<TextAnalyticsClient>, ITextAnalyticsClient
 35    {
 36        /// <summary>
 37        /// The base URI of the service.
 38        /// </summary>
 3239        internal string BaseUri {get; set;}
 40
 41        /// <summary>
 42        /// Gets or sets json serialization settings.
 43        /// </summary>
 3244        public JsonSerializerSettings SerializationSettings { get; private set; }
 45
 46        /// <summary>
 47        /// Gets or sets json deserialization settings.
 48        /// </summary>
 3249        public JsonSerializerSettings DeserializationSettings { get; private set; }
 50
 51        /// <summary>
 52        /// Supported Cognitive Services endpoints (protocol and hostname, for example:
 53        /// https://westus.api.cognitive.microsoft.com).
 54        /// </summary>
 4855        public string Endpoint { get; set; }
 56
 57        /// <summary>
 58        /// Subscription credentials which uniquely identify client subscription.
 59        /// </summary>
 8060        public ServiceClientCredentials Credentials { get; private set; }
 61
 62        /// <summary>
 63        /// Initializes a new instance of the TextAnalyticsClient class.
 64        /// </summary>
 65        /// <param name='httpClient'>
 66        /// HttpClient to be used
 67        /// </param>
 68        /// <param name='disposeHttpClient'>
 69        /// True: will dispose the provided httpClient on calling TextAnalyticsClient.Dispose(). False: will not dispose
 070        protected TextAnalyticsClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClien
 71        {
 072            Initialize();
 073        }
 74
 75        /// <summary>
 76        /// Initializes a new instance of the TextAnalyticsClient class.
 77        /// </summary>
 78        /// <param name='handlers'>
 79        /// Optional. The delegating handlers to add to the http client pipeline.
 80        /// </param>
 1681        protected TextAnalyticsClient(params DelegatingHandler[] handlers) : base(handlers)
 82        {
 1683            Initialize();
 1684        }
 85
 86        /// <summary>
 87        /// Initializes a new instance of the TextAnalyticsClient class.
 88        /// </summary>
 89        /// <param name='rootHandler'>
 90        /// Optional. The http client handler used to handle http transport.
 91        /// </param>
 92        /// <param name='handlers'>
 93        /// Optional. The delegating handlers to add to the http client pipeline.
 94        /// </param>
 095        protected TextAnalyticsClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHan
 96        {
 097            Initialize();
 098        }
 99
 100        /// <summary>
 101        /// Initializes a new instance of the TextAnalyticsClient class.
 102        /// </summary>
 103        /// <param name='credentials'>
 104        /// Required. Subscription credentials which uniquely identify client subscription.
 105        /// </param>
 106        /// <param name='handlers'>
 107        /// Optional. The delegating handlers to add to the http client pipeline.
 108        /// </param>
 109        /// <exception cref="System.ArgumentNullException">
 110        /// Thrown when a required parameter is null
 111        /// </exception>
 16112        public TextAnalyticsClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(han
 113        {
 16114            if (credentials == null)
 115            {
 0116                throw new System.ArgumentNullException("credentials");
 117            }
 16118            Credentials = credentials;
 16119            if (Credentials != null)
 120            {
 16121                Credentials.InitializeServiceClient(this);
 122            }
 16123        }
 124
 125        /// <summary>
 126        /// Initializes a new instance of the TextAnalyticsClient class.
 127        /// </summary>
 128        /// <param name='credentials'>
 129        /// Required. Subscription credentials which uniquely identify client subscription.
 130        /// </param>
 131        /// <param name='httpClient'>
 132        /// HttpClient to be used
 133        /// </param>
 134        /// <param name='disposeHttpClient'>
 135        /// True: will dispose the provided httpClient on calling TextAnalyticsClient.Dispose(). False: will not dispose
 136        /// <exception cref="System.ArgumentNullException">
 137        /// Thrown when a required parameter is null
 138        /// </exception>
 0139        public TextAnalyticsClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) 
 140        {
 0141            if (credentials == null)
 142            {
 0143                throw new System.ArgumentNullException("credentials");
 144            }
 0145            Credentials = credentials;
 0146            if (Credentials != null)
 147            {
 0148                Credentials.InitializeServiceClient(this);
 149            }
 0150        }
 151
 152        /// <summary>
 153        /// Initializes a new instance of the TextAnalyticsClient class.
 154        /// </summary>
 155        /// <param name='credentials'>
 156        /// Required. Subscription credentials which uniquely identify client subscription.
 157        /// </param>
 158        /// <param name='rootHandler'>
 159        /// Optional. The http client handler used to handle http transport.
 160        /// </param>
 161        /// <param name='handlers'>
 162        /// Optional. The delegating handlers to add to the http client pipeline.
 163        /// </param>
 164        /// <exception cref="System.ArgumentNullException">
 165        /// Thrown when a required parameter is null
 166        /// </exception>
 0167        public TextAnalyticsClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params Delegatin
 168        {
 0169            if (credentials == null)
 170            {
 0171                throw new System.ArgumentNullException("credentials");
 172            }
 0173            Credentials = credentials;
 0174            if (Credentials != null)
 175            {
 0176                Credentials.InitializeServiceClient(this);
 177            }
 0178        }
 179
 180        /// <summary>
 181        /// An optional partial-method to perform custom initialization.
 182        ///</summary>
 183        partial void CustomInitialize();
 184        /// <summary>
 185        /// Initializes client properties.
 186        /// </summary>
 187        private void Initialize()
 188        {
 16189            BaseUri = "{Endpoint}/text/analytics/v2.1";
 16190            SerializationSettings = new JsonSerializerSettings
 16191            {
 16192                Formatting = Newtonsoft.Json.Formatting.Indented,
 16193                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 16194                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 16195                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 16196                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 16197                ContractResolver = new ReadOnlyJsonContractResolver(),
 16198                Converters = new  List<JsonConverter>
 16199                    {
 16200                        new Iso8601TimeSpanConverter()
 16201                    }
 16202            };
 16203            DeserializationSettings = new JsonSerializerSettings
 16204            {
 16205                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 16206                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 16207                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 16208                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 16209                ContractResolver = new ReadOnlyJsonContractResolver(),
 16210                Converters = new List<JsonConverter>
 16211                    {
 16212                        new Iso8601TimeSpanConverter()
 16213                    }
 16214            };
 215            CustomInitialize();
 16216        }
 217        /// <summary>
 218        /// The API returns the detected language and a numeric score between 0 and 1.
 219        /// </summary>
 220        /// <remarks>
 221        /// Scores close to 1 indicate 100% certainty that the identified language is
 222        /// true. A total of 120 languages are supported.
 223        /// </remarks>
 224        /// <param name='showStats'>
 225        /// (optional) if set to true, response will contain input and document level
 226        /// statistics.
 227        /// </param>
 228        /// <param name='languageBatchInput'>
 229        /// Collection of documents to analyze.
 230        /// </param>
 231        /// <param name='customHeaders'>
 232        /// Headers that will be added to request.
 233        /// </param>
 234        /// <param name='cancellationToken'>
 235        /// The cancellation token.
 236        /// </param>
 237        /// <exception cref="ErrorResponseException">
 238        /// Thrown when the operation returned an invalid status code
 239        /// </exception>
 240        /// <exception cref="SerializationException">
 241        /// Thrown when unable to deserialize the response
 242        /// </exception>
 243        /// <exception cref="ValidationException">
 244        /// Thrown when a required parameter is null
 245        /// </exception>
 246        /// <exception cref="System.ArgumentNullException">
 247        /// Thrown when a required parameter is null
 248        /// </exception>
 249        /// <return>
 250        /// A response object containing the response body and response headers.
 251        /// </return>
 252        public async Task<HttpOperationResponse<LanguageBatchResult>> DetectLanguageWithHttpMessagesAsync(bool? showStat
 253        {
 4254            if (Endpoint == null)
 255            {
 0256                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
 257            }
 258            // Tracing
 4259            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 4260            string _invocationId = null;
 4261            if (_shouldTrace)
 262            {
 0263                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0264                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0265                tracingParameters.Add("showStats", showStats);
 0266                tracingParameters.Add("languageBatchInput", languageBatchInput);
 0267                tracingParameters.Add("cancellationToken", cancellationToken);
 0268                ServiceClientTracing.Enter(_invocationId, this, "DetectLanguage", tracingParameters);
 269            }
 270            // Construct URL
 4271            var _baseUrl = BaseUri;
 4272            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "languages";
 4273            _url = _url.Replace("{Endpoint}", Endpoint);
 4274            List<string> _queryParameters = new List<string>();
 4275            if (showStats != null)
 276            {
 0277                _queryParameters.Add(string.Format("showStats={0}", System.Uri.EscapeDataString(SafeJsonConvert.Serializ
 278            }
 4279            if (_queryParameters.Count > 0)
 280            {
 0281                _url += "?" + string.Join("&", _queryParameters);
 282            }
 283            // Create HTTP transport objects
 4284            var _httpRequest = new HttpRequestMessage();
 4285            HttpResponseMessage _httpResponse = null;
 4286            _httpRequest.Method = new HttpMethod("POST");
 4287            _httpRequest.RequestUri = new System.Uri(_url);
 288            // Set Headers
 289
 290
 4291            if (customHeaders != null)
 292            {
 0293                foreach(var _header in customHeaders)
 294                {
 0295                    if (_httpRequest.Headers.Contains(_header.Key))
 296                    {
 0297                        _httpRequest.Headers.Remove(_header.Key);
 298                    }
 0299                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 300                }
 301            }
 302
 303            // Serialize Request
 4304            string _requestContent = null;
 4305            if(languageBatchInput != null)
 306            {
 4307                _requestContent = SafeJsonConvert.SerializeObject(languageBatchInput, SerializationSettings);
 4308                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 4309                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 310            }
 311            // Set Credentials
 4312            if (Credentials != null)
 313            {
 4314                cancellationToken.ThrowIfCancellationRequested();
 4315                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 316            }
 317            // Send Request
 4318            if (_shouldTrace)
 319            {
 0320                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 321            }
 4322            cancellationToken.ThrowIfCancellationRequested();
 4323            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 4324            if (_shouldTrace)
 325            {
 0326                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 327            }
 4328            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 4329            cancellationToken.ThrowIfCancellationRequested();
 4330            string _responseContent = null;
 4331            if ((int)_statusCode != 200)
 332            {
 0333                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 334                try
 335                {
 0336                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0337                    ErrorResponse _errorBody =  SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deser
 0338                    if (_errorBody != null)
 339                    {
 0340                        ex.Body = _errorBody;
 341                    }
 0342                }
 0343                catch (JsonException)
 344                {
 345                    // Ignore the exception
 0346                }
 0347                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0348                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0349                if (_shouldTrace)
 350                {
 0351                    ServiceClientTracing.Error(_invocationId, ex);
 352                }
 0353                _httpRequest.Dispose();
 0354                if (_httpResponse != null)
 355                {
 0356                    _httpResponse.Dispose();
 357                }
 0358                throw ex;
 359            }
 360            // Create Result
 4361            var _result = new HttpOperationResponse<LanguageBatchResult>();
 4362            _result.Request = _httpRequest;
 4363            _result.Response = _httpResponse;
 364            // Deserialize Response
 4365            if ((int)_statusCode == 200)
 366            {
 4367                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 368                try
 369                {
 4370                    _result.Body = SafeJsonConvert.DeserializeObject<LanguageBatchResult>(_responseContent, Deserializat
 4371                }
 0372                catch (JsonException ex)
 373                {
 0374                    _httpRequest.Dispose();
 0375                    if (_httpResponse != null)
 376                    {
 0377                        _httpResponse.Dispose();
 378                    }
 0379                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 380                }
 381            }
 4382            if (_shouldTrace)
 383            {
 0384                ServiceClientTracing.Exit(_invocationId, _result);
 385            }
 4386            return _result;
 4387        }
 388
 389        /// <summary>
 390        /// The API returns a list of recognized entities in a given document.
 391        /// </summary>
 392        /// <remarks>
 393        /// To get even more information on each recognized entity we recommend using
 394        /// the Bing Entity Search API by querying for the recognized entities names.
 395        /// See the &lt;a
 396        /// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-lang
 397        /// languages in Text Analytics API&lt;/a&gt; for the list of enabled
 398        /// languages.
 399        /// </remarks>
 400        /// <param name='showStats'>
 401        /// (optional) if set to true, response will contain input and document level
 402        /// statistics.
 403        /// </param>
 404        /// <param name='multiLanguageBatchInput'>
 405        /// Collection of documents to analyze.
 406        /// </param>
 407        /// <param name='customHeaders'>
 408        /// Headers that will be added to request.
 409        /// </param>
 410        /// <param name='cancellationToken'>
 411        /// The cancellation token.
 412        /// </param>
 413        /// <exception cref="ErrorResponseException">
 414        /// Thrown when the operation returned an invalid status code
 415        /// </exception>
 416        /// <exception cref="SerializationException">
 417        /// Thrown when unable to deserialize the response
 418        /// </exception>
 419        /// <exception cref="ValidationException">
 420        /// Thrown when a required parameter is null
 421        /// </exception>
 422        /// <exception cref="System.ArgumentNullException">
 423        /// Thrown when a required parameter is null
 424        /// </exception>
 425        /// <return>
 426        /// A response object containing the response body and response headers.
 427        /// </return>
 428        public async Task<HttpOperationResponse<EntitiesBatchResult>> EntitiesWithHttpMessagesAsync(bool? showStats = de
 429        {
 4430            if (Endpoint == null)
 431            {
 0432                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
 433            }
 434            // Tracing
 4435            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 4436            string _invocationId = null;
 4437            if (_shouldTrace)
 438            {
 0439                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0440                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0441                tracingParameters.Add("showStats", showStats);
 0442                tracingParameters.Add("multiLanguageBatchInput", multiLanguageBatchInput);
 0443                tracingParameters.Add("cancellationToken", cancellationToken);
 0444                ServiceClientTracing.Enter(_invocationId, this, "Entities", tracingParameters);
 445            }
 446            // Construct URL
 4447            var _baseUrl = BaseUri;
 4448            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "entities";
 4449            _url = _url.Replace("{Endpoint}", Endpoint);
 4450            List<string> _queryParameters = new List<string>();
 4451            if (showStats != null)
 452            {
 0453                _queryParameters.Add(string.Format("showStats={0}", System.Uri.EscapeDataString(SafeJsonConvert.Serializ
 454            }
 4455            if (_queryParameters.Count > 0)
 456            {
 0457                _url += "?" + string.Join("&", _queryParameters);
 458            }
 459            // Create HTTP transport objects
 4460            var _httpRequest = new HttpRequestMessage();
 4461            HttpResponseMessage _httpResponse = null;
 4462            _httpRequest.Method = new HttpMethod("POST");
 4463            _httpRequest.RequestUri = new System.Uri(_url);
 464            // Set Headers
 465
 466
 4467            if (customHeaders != null)
 468            {
 0469                foreach(var _header in customHeaders)
 470                {
 0471                    if (_httpRequest.Headers.Contains(_header.Key))
 472                    {
 0473                        _httpRequest.Headers.Remove(_header.Key);
 474                    }
 0475                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 476                }
 477            }
 478
 479            // Serialize Request
 4480            string _requestContent = null;
 4481            if(multiLanguageBatchInput != null)
 482            {
 4483                _requestContent = SafeJsonConvert.SerializeObject(multiLanguageBatchInput, SerializationSettings);
 4484                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 4485                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 486            }
 487            // Set Credentials
 4488            if (Credentials != null)
 489            {
 4490                cancellationToken.ThrowIfCancellationRequested();
 4491                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 492            }
 493            // Send Request
 4494            if (_shouldTrace)
 495            {
 0496                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 497            }
 4498            cancellationToken.ThrowIfCancellationRequested();
 4499            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 4500            if (_shouldTrace)
 501            {
 0502                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 503            }
 4504            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 4505            cancellationToken.ThrowIfCancellationRequested();
 4506            string _responseContent = null;
 4507            if ((int)_statusCode != 200)
 508            {
 0509                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 510                try
 511                {
 0512                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0513                    ErrorResponse _errorBody =  SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deser
 0514                    if (_errorBody != null)
 515                    {
 0516                        ex.Body = _errorBody;
 517                    }
 0518                }
 0519                catch (JsonException)
 520                {
 521                    // Ignore the exception
 0522                }
 0523                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0524                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0525                if (_shouldTrace)
 526                {
 0527                    ServiceClientTracing.Error(_invocationId, ex);
 528                }
 0529                _httpRequest.Dispose();
 0530                if (_httpResponse != null)
 531                {
 0532                    _httpResponse.Dispose();
 533                }
 0534                throw ex;
 535            }
 536            // Create Result
 4537            var _result = new HttpOperationResponse<EntitiesBatchResult>();
 4538            _result.Request = _httpRequest;
 4539            _result.Response = _httpResponse;
 540            // Deserialize Response
 4541            if ((int)_statusCode == 200)
 542            {
 4543                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 544                try
 545                {
 4546                    _result.Body = SafeJsonConvert.DeserializeObject<EntitiesBatchResult>(_responseContent, Deserializat
 4547                }
 0548                catch (JsonException ex)
 549                {
 0550                    _httpRequest.Dispose();
 0551                    if (_httpResponse != null)
 552                    {
 0553                        _httpResponse.Dispose();
 554                    }
 0555                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 556                }
 557            }
 4558            if (_shouldTrace)
 559            {
 0560                ServiceClientTracing.Exit(_invocationId, _result);
 561            }
 4562            return _result;
 4563        }
 564
 565        /// <summary>
 566        /// The API returns a list of strings denoting the key talking points in the
 567        /// input text.
 568        /// </summary>
 569        /// <remarks>
 570        /// See the &lt;a
 571        /// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages"
 572        /// Analytics Documentation&lt;/a&gt; for details about the languages that are
 573        /// supported by key phrase extraction.
 574        /// </remarks>
 575        /// <param name='showStats'>
 576        /// (optional) if set to true, response will contain input and document level
 577        /// statistics.
 578        /// </param>
 579        /// <param name='multiLanguageBatchInput'>
 580        /// Collection of documents to analyze. Documents can now contain a language
 581        /// field to indicate the text language
 582        /// </param>
 583        /// <param name='customHeaders'>
 584        /// Headers that will be added to request.
 585        /// </param>
 586        /// <param name='cancellationToken'>
 587        /// The cancellation token.
 588        /// </param>
 589        /// <exception cref="ErrorResponseException">
 590        /// Thrown when the operation returned an invalid status code
 591        /// </exception>
 592        /// <exception cref="SerializationException">
 593        /// Thrown when unable to deserialize the response
 594        /// </exception>
 595        /// <exception cref="ValidationException">
 596        /// Thrown when a required parameter is null
 597        /// </exception>
 598        /// <exception cref="System.ArgumentNullException">
 599        /// Thrown when a required parameter is null
 600        /// </exception>
 601        /// <return>
 602        /// A response object containing the response body and response headers.
 603        /// </return>
 604        public async Task<HttpOperationResponse<KeyPhraseBatchResult>> KeyPhrasesWithHttpMessagesAsync(bool? showStats =
 605        {
 4606            if (Endpoint == null)
 607            {
 0608                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
 609            }
 610            // Tracing
 4611            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 4612            string _invocationId = null;
 4613            if (_shouldTrace)
 614            {
 0615                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0616                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0617                tracingParameters.Add("showStats", showStats);
 0618                tracingParameters.Add("multiLanguageBatchInput", multiLanguageBatchInput);
 0619                tracingParameters.Add("cancellationToken", cancellationToken);
 0620                ServiceClientTracing.Enter(_invocationId, this, "KeyPhrases", tracingParameters);
 621            }
 622            // Construct URL
 4623            var _baseUrl = BaseUri;
 4624            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "keyPhrases";
 4625            _url = _url.Replace("{Endpoint}", Endpoint);
 4626            List<string> _queryParameters = new List<string>();
 4627            if (showStats != null)
 628            {
 0629                _queryParameters.Add(string.Format("showStats={0}", System.Uri.EscapeDataString(SafeJsonConvert.Serializ
 630            }
 4631            if (_queryParameters.Count > 0)
 632            {
 0633                _url += "?" + string.Join("&", _queryParameters);
 634            }
 635            // Create HTTP transport objects
 4636            var _httpRequest = new HttpRequestMessage();
 4637            HttpResponseMessage _httpResponse = null;
 4638            _httpRequest.Method = new HttpMethod("POST");
 4639            _httpRequest.RequestUri = new System.Uri(_url);
 640            // Set Headers
 641
 642
 4643            if (customHeaders != null)
 644            {
 0645                foreach(var _header in customHeaders)
 646                {
 0647                    if (_httpRequest.Headers.Contains(_header.Key))
 648                    {
 0649                        _httpRequest.Headers.Remove(_header.Key);
 650                    }
 0651                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 652                }
 653            }
 654
 655            // Serialize Request
 4656            string _requestContent = null;
 4657            if(multiLanguageBatchInput != null)
 658            {
 4659                _requestContent = SafeJsonConvert.SerializeObject(multiLanguageBatchInput, SerializationSettings);
 4660                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 4661                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 662            }
 663            // Set Credentials
 4664            if (Credentials != null)
 665            {
 4666                cancellationToken.ThrowIfCancellationRequested();
 4667                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 668            }
 669            // Send Request
 4670            if (_shouldTrace)
 671            {
 0672                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 673            }
 4674            cancellationToken.ThrowIfCancellationRequested();
 4675            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 4676            if (_shouldTrace)
 677            {
 0678                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 679            }
 4680            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 4681            cancellationToken.ThrowIfCancellationRequested();
 4682            string _responseContent = null;
 4683            if ((int)_statusCode != 200)
 684            {
 0685                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 686                try
 687                {
 0688                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0689                    ErrorResponse _errorBody =  SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deser
 0690                    if (_errorBody != null)
 691                    {
 0692                        ex.Body = _errorBody;
 693                    }
 0694                }
 0695                catch (JsonException)
 696                {
 697                    // Ignore the exception
 0698                }
 0699                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0700                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0701                if (_shouldTrace)
 702                {
 0703                    ServiceClientTracing.Error(_invocationId, ex);
 704                }
 0705                _httpRequest.Dispose();
 0706                if (_httpResponse != null)
 707                {
 0708                    _httpResponse.Dispose();
 709                }
 0710                throw ex;
 711            }
 712            // Create Result
 4713            var _result = new HttpOperationResponse<KeyPhraseBatchResult>();
 4714            _result.Request = _httpRequest;
 4715            _result.Response = _httpResponse;
 716            // Deserialize Response
 4717            if ((int)_statusCode == 200)
 718            {
 4719                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 720                try
 721                {
 4722                    _result.Body = SafeJsonConvert.DeserializeObject<KeyPhraseBatchResult>(_responseContent, Deserializa
 4723                }
 0724                catch (JsonException ex)
 725                {
 0726                    _httpRequest.Dispose();
 0727                    if (_httpResponse != null)
 728                    {
 0729                        _httpResponse.Dispose();
 730                    }
 0731                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 732                }
 733            }
 4734            if (_shouldTrace)
 735            {
 0736                ServiceClientTracing.Exit(_invocationId, _result);
 737            }
 4738            return _result;
 4739        }
 740
 741        /// <summary>
 742        /// The API returns a numeric score between 0 and 1.
 743        /// </summary>
 744        /// <remarks>
 745        /// Scores close to 1 indicate positive sentiment, while scores close to 0
 746        /// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
 747        /// (e.g. a factoid statement). See the &lt;a
 748        /// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages"
 749        /// Analytics Documentation&lt;/a&gt; for details about the languages that are
 750        /// supported by sentiment analysis.
 751        /// </remarks>
 752        /// <param name='showStats'>
 753        /// (optional) if set to true, response will contain input and document level
 754        /// statistics.
 755        /// </param>
 756        /// <param name='multiLanguageBatchInput'>
 757        /// Collection of documents to analyze.
 758        /// </param>
 759        /// <param name='customHeaders'>
 760        /// Headers that will be added to request.
 761        /// </param>
 762        /// <param name='cancellationToken'>
 763        /// The cancellation token.
 764        /// </param>
 765        /// <exception cref="HttpOperationException">
 766        /// Thrown when the operation returned an invalid status code
 767        /// </exception>
 768        /// <exception cref="SerializationException">
 769        /// Thrown when unable to deserialize the response
 770        /// </exception>
 771        /// <exception cref="ValidationException">
 772        /// Thrown when a required parameter is null
 773        /// </exception>
 774        /// <exception cref="System.ArgumentNullException">
 775        /// Thrown when a required parameter is null
 776        /// </exception>
 777        /// <return>
 778        /// A response object containing the response body and response headers.
 779        /// </return>
 780        public async Task<HttpOperationResponse<SentimentBatchResult>> SentimentWithHttpMessagesAsync(bool? showStats = 
 781        {
 4782            if (Endpoint == null)
 783            {
 0784                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
 785            }
 786            // Tracing
 4787            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 4788            string _invocationId = null;
 4789            if (_shouldTrace)
 790            {
 0791                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0792                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0793                tracingParameters.Add("showStats", showStats);
 0794                tracingParameters.Add("multiLanguageBatchInput", multiLanguageBatchInput);
 0795                tracingParameters.Add("cancellationToken", cancellationToken);
 0796                ServiceClientTracing.Enter(_invocationId, this, "Sentiment", tracingParameters);
 797            }
 798            // Construct URL
 4799            var _baseUrl = BaseUri;
 4800            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "sentiment";
 4801            _url = _url.Replace("{Endpoint}", Endpoint);
 4802            List<string> _queryParameters = new List<string>();
 4803            if (showStats != null)
 804            {
 0805                _queryParameters.Add(string.Format("showStats={0}", System.Uri.EscapeDataString(SafeJsonConvert.Serializ
 806            }
 4807            if (_queryParameters.Count > 0)
 808            {
 0809                _url += "?" + string.Join("&", _queryParameters);
 810            }
 811            // Create HTTP transport objects
 4812            var _httpRequest = new HttpRequestMessage();
 4813            HttpResponseMessage _httpResponse = null;
 4814            _httpRequest.Method = new HttpMethod("POST");
 4815            _httpRequest.RequestUri = new System.Uri(_url);
 816            // Set Headers
 817
 818
 4819            if (customHeaders != null)
 820            {
 0821                foreach(var _header in customHeaders)
 822                {
 0823                    if (_httpRequest.Headers.Contains(_header.Key))
 824                    {
 0825                        _httpRequest.Headers.Remove(_header.Key);
 826                    }
 0827                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 828                }
 829            }
 830
 831            // Serialize Request
 4832            string _requestContent = null;
 4833            if(multiLanguageBatchInput != null)
 834            {
 4835                _requestContent = SafeJsonConvert.SerializeObject(multiLanguageBatchInput, SerializationSettings);
 4836                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 4837                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 838            }
 839            // Set Credentials
 4840            if (Credentials != null)
 841            {
 4842                cancellationToken.ThrowIfCancellationRequested();
 4843                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 844            }
 845            // Send Request
 4846            if (_shouldTrace)
 847            {
 0848                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 849            }
 4850            cancellationToken.ThrowIfCancellationRequested();
 4851            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 4852            if (_shouldTrace)
 853            {
 0854                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 855            }
 4856            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 4857            cancellationToken.ThrowIfCancellationRequested();
 4858            string _responseContent = null;
 4859            if ((int)_statusCode != 200)
 860            {
 0861                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 862                try
 863                {
 0864                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0865                    ErrorResponse _errorBody =  SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deser
 0866                    if (_errorBody != null)
 867                    {
 0868                        ex.Body = _errorBody;
 869                    }
 0870                }
 0871                catch (JsonException)
 872                {
 873                    // Ignore the exception
 0874                }
 0875                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0876                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0877                if (_shouldTrace)
 878                {
 0879                    ServiceClientTracing.Error(_invocationId, ex);
 880                }
 0881                _httpRequest.Dispose();
 0882                if (_httpResponse != null)
 883                {
 0884                    _httpResponse.Dispose();
 885                }
 0886                throw ex;
 887            }
 888            // Create Result
 4889            var _result = new HttpOperationResponse<SentimentBatchResult>();
 4890            _result.Request = _httpRequest;
 4891            _result.Response = _httpResponse;
 892            // Deserialize Response
 4893            if ((int)_statusCode == 200)
 894            {
 4895                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 896                try
 897                {
 4898                    _result.Body = SafeJsonConvert.DeserializeObject<SentimentBatchResult>(_responseContent, Deserializa
 4899                }
 0900                catch (JsonException ex)
 901                {
 0902                    _httpRequest.Dispose();
 0903                    if (_httpResponse != null)
 904                    {
 0905                        _httpResponse.Dispose();
 906                    }
 0907                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 908                }
 909            }
 4910            if (_shouldTrace)
 911            {
 0912                ServiceClientTracing.Exit(_invocationId, _result);
 913            }
 4914            return _result;
 4915        }
 916
 917    }
 918}