< Summary

Class:Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker.Runtime
Assembly:Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker
File(s):C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Knowledge.QnAMaker\src\Generated\Runtime.cs
Covered lines:46
Uncovered lines:107
Coverable lines:153
Total lines:367
Line coverage:30% (46 of 153)
Covered branches:17
Total branches:74
Branch coverage:22.9% (17 of 74)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
.ctor(...)-80%50%
get_Client()-100%100%
GenerateAnswerWithHttpMessagesAsync()-52.56%42.11%
TrainWithHttpMessagesAsync()-0%0%

File(s)

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Knowledge.QnAMaker\src\Generated\Runtime.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.Knowledge.QnAMaker
 12{
 13    using Microsoft.Rest;
 14    using Models;
 15    using Newtonsoft.Json;
 16    using System.Collections;
 17    using System.Collections.Generic;
 18    using System.IO;
 19    using System.Linq;
 20    using System.Net;
 21    using System.Net.Http;
 22    using System.Threading;
 23    using System.Threading.Tasks;
 24
 25    /// <summary>
 26    /// Runtime operations.
 27    /// </summary>
 28    public partial class Runtime : IServiceOperations<QnAMakerRuntimeClient>, IRuntime
 29    {
 30        /// <summary>
 31        /// Initializes a new instance of the Runtime class.
 32        /// </summary>
 33        /// <param name='client'>
 34        /// Reference to the service client.
 35        /// </param>
 36        /// <exception cref="System.ArgumentNullException">
 37        /// Thrown when a required parameter is null
 38        /// </exception>
 239        public Runtime(QnAMakerRuntimeClient client)
 40        {
 241            if (client == null)
 42            {
 043                throw new System.ArgumentNullException("client");
 44            }
 245            Client = client;
 246        }
 47
 48        /// <summary>
 49        /// Gets a reference to the QnAMakerRuntimeClient
 50        /// </summary>
 1851        public QnAMakerRuntimeClient Client { get; private set; }
 52
 53        /// <summary>
 54        /// GenerateAnswer call to query the knowledgebase.
 55        /// </summary>
 56        /// <param name='kbId'>
 57        /// Knowledgebase id.
 58        /// </param>
 59        /// <param name='generateAnswerPayload'>
 60        /// Post body of the request.
 61        /// </param>
 62        /// <param name='customHeaders'>
 63        /// Headers that will be added to request.
 64        /// </param>
 65        /// <param name='cancellationToken'>
 66        /// The cancellation token.
 67        /// </param>
 68        /// <exception cref="ErrorResponseException">
 69        /// Thrown when the operation returned an invalid status code
 70        /// </exception>
 71        /// <exception cref="SerializationException">
 72        /// Thrown when unable to deserialize the response
 73        /// </exception>
 74        /// <exception cref="ValidationException">
 75        /// Thrown when a required parameter is null
 76        /// </exception>
 77        /// <exception cref="System.ArgumentNullException">
 78        /// Thrown when a required parameter is null
 79        /// </exception>
 80        /// <return>
 81        /// A response object containing the response body and response headers.
 82        /// </return>
 83        public async Task<HttpOperationResponse<QnASearchResultList>> GenerateAnswerWithHttpMessagesAsync(string kbId, Q
 84        {
 285            if (Client.RuntimeEndpoint == null)
 86            {
 087                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RuntimeEndpoint");
 88            }
 289            if (kbId == null)
 90            {
 091                throw new ValidationException(ValidationRules.CannotBeNull, "kbId");
 92            }
 293            if (generateAnswerPayload == null)
 94            {
 095                throw new ValidationException(ValidationRules.CannotBeNull, "generateAnswerPayload");
 96            }
 97            // Tracing
 298            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 299            string _invocationId = null;
 2100            if (_shouldTrace)
 101            {
 0102                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0103                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0104                tracingParameters.Add("kbId", kbId);
 0105                tracingParameters.Add("generateAnswerPayload", generateAnswerPayload);
 0106                tracingParameters.Add("cancellationToken", cancellationToken);
 0107                ServiceClientTracing.Enter(_invocationId, this, "GenerateAnswer", tracingParameters);
 108            }
 109            // Construct URL
 2110            var _baseUrl = Client.BaseUri;
 2111            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "knowledgebases/{kbId}/generateAnswer";
 2112            _url = _url.Replace("{RuntimeEndpoint}", Client.RuntimeEndpoint);
 2113            _url = _url.Replace("{kbId}", System.Uri.EscapeDataString(kbId));
 114            // Create HTTP transport objects
 2115            var _httpRequest = new HttpRequestMessage();
 2116            HttpResponseMessage _httpResponse = null;
 2117            _httpRequest.Method = new HttpMethod("POST");
 2118            _httpRequest.RequestUri = new System.Uri(_url);
 119            // Set Headers
 120
 121
 2122            if (customHeaders != null)
 123            {
 0124                foreach(var _header in customHeaders)
 125                {
 0126                    if (_httpRequest.Headers.Contains(_header.Key))
 127                    {
 0128                        _httpRequest.Headers.Remove(_header.Key);
 129                    }
 0130                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 131                }
 132            }
 133
 134            // Serialize Request
 2135            string _requestContent = null;
 2136            if(generateAnswerPayload != null)
 137            {
 2138                _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(generateAnswerPayload, Client.Seria
 2139                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 2140                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 141            }
 142            // Set Credentials
 2143            if (Client.Credentials != null)
 144            {
 2145                cancellationToken.ThrowIfCancellationRequested();
 2146                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 147            }
 148            // Send Request
 2149            if (_shouldTrace)
 150            {
 0151                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 152            }
 2153            cancellationToken.ThrowIfCancellationRequested();
 2154            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 2155            if (_shouldTrace)
 156            {
 0157                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 158            }
 2159            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 2160            cancellationToken.ThrowIfCancellationRequested();
 2161            string _responseContent = null;
 2162            if ((int)_statusCode != 200)
 163            {
 0164                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 165                try
 166                {
 0167                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0168                    ErrorResponse _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_res
 0169                    if (_errorBody != null)
 170                    {
 0171                        ex.Body = _errorBody;
 172                    }
 0173                }
 0174                catch (JsonException)
 175                {
 176                    // Ignore the exception
 0177                }
 0178                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0179                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0180                if (_shouldTrace)
 181                {
 0182                    ServiceClientTracing.Error(_invocationId, ex);
 183                }
 0184                _httpRequest.Dispose();
 0185                if (_httpResponse != null)
 186                {
 0187                    _httpResponse.Dispose();
 188                }
 0189                throw ex;
 190            }
 191            // Create Result
 2192            var _result = new HttpOperationResponse<QnASearchResultList>();
 2193            _result.Request = _httpRequest;
 2194            _result.Response = _httpResponse;
 195            // Deserialize Response
 2196            if ((int)_statusCode == 200)
 197            {
 2198                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 199                try
 200                {
 2201                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<QnASearchResultList>(_responseCo
 2202                }
 0203                catch (JsonException ex)
 204                {
 0205                    _httpRequest.Dispose();
 0206                    if (_httpResponse != null)
 207                    {
 0208                        _httpResponse.Dispose();
 209                    }
 0210                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 211                }
 212            }
 2213            if (_shouldTrace)
 214            {
 0215                ServiceClientTracing.Exit(_invocationId, _result);
 216            }
 2217            return _result;
 2218        }
 219
 220        /// <summary>
 221        /// Train call to add suggestions to the knowledgebase.
 222        /// </summary>
 223        /// <param name='kbId'>
 224        /// Knowledgebase id.
 225        /// </param>
 226        /// <param name='trainPayload'>
 227        /// Post body of the request.
 228        /// </param>
 229        /// <param name='customHeaders'>
 230        /// Headers that will be added to request.
 231        /// </param>
 232        /// <param name='cancellationToken'>
 233        /// The cancellation token.
 234        /// </param>
 235        /// <exception cref="ErrorResponseException">
 236        /// Thrown when the operation returned an invalid status code
 237        /// </exception>
 238        /// <exception cref="ValidationException">
 239        /// Thrown when a required parameter is null
 240        /// </exception>
 241        /// <exception cref="System.ArgumentNullException">
 242        /// Thrown when a required parameter is null
 243        /// </exception>
 244        /// <return>
 245        /// A response object containing the response body and response headers.
 246        /// </return>
 247        public async Task<HttpOperationResponse> TrainWithHttpMessagesAsync(string kbId, FeedbackRecordsDTO trainPayload
 248        {
 0249            if (Client.RuntimeEndpoint == null)
 250            {
 0251                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.RuntimeEndpoint");
 252            }
 0253            if (kbId == null)
 254            {
 0255                throw new ValidationException(ValidationRules.CannotBeNull, "kbId");
 256            }
 0257            if (trainPayload == null)
 258            {
 0259                throw new ValidationException(ValidationRules.CannotBeNull, "trainPayload");
 260            }
 261            // Tracing
 0262            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 0263            string _invocationId = null;
 0264            if (_shouldTrace)
 265            {
 0266                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0267                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0268                tracingParameters.Add("kbId", kbId);
 0269                tracingParameters.Add("trainPayload", trainPayload);
 0270                tracingParameters.Add("cancellationToken", cancellationToken);
 0271                ServiceClientTracing.Enter(_invocationId, this, "Train", tracingParameters);
 272            }
 273            // Construct URL
 0274            var _baseUrl = Client.BaseUri;
 0275            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "knowledgebases/{kbId}/train";
 0276            _url = _url.Replace("{RuntimeEndpoint}", Client.RuntimeEndpoint);
 0277            _url = _url.Replace("{kbId}", System.Uri.EscapeDataString(kbId));
 278            // Create HTTP transport objects
 0279            var _httpRequest = new HttpRequestMessage();
 0280            HttpResponseMessage _httpResponse = null;
 0281            _httpRequest.Method = new HttpMethod("POST");
 0282            _httpRequest.RequestUri = new System.Uri(_url);
 283            // Set Headers
 284
 285
 0286            if (customHeaders != null)
 287            {
 0288                foreach(var _header in customHeaders)
 289                {
 0290                    if (_httpRequest.Headers.Contains(_header.Key))
 291                    {
 0292                        _httpRequest.Headers.Remove(_header.Key);
 293                    }
 0294                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 295                }
 296            }
 297
 298            // Serialize Request
 0299            string _requestContent = null;
 0300            if(trainPayload != null)
 301            {
 0302                _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(trainPayload, Client.SerializationS
 0303                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 0304                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 305            }
 306            // Set Credentials
 0307            if (Client.Credentials != null)
 308            {
 0309                cancellationToken.ThrowIfCancellationRequested();
 0310                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 311            }
 312            // Send Request
 0313            if (_shouldTrace)
 314            {
 0315                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 316            }
 0317            cancellationToken.ThrowIfCancellationRequested();
 0318            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 0319            if (_shouldTrace)
 320            {
 0321                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 322            }
 0323            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 0324            cancellationToken.ThrowIfCancellationRequested();
 0325            string _responseContent = null;
 0326            if ((int)_statusCode != 204)
 327            {
 0328                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 329                try
 330                {
 0331                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0332                    ErrorResponse _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_res
 0333                    if (_errorBody != null)
 334                    {
 0335                        ex.Body = _errorBody;
 336                    }
 0337                }
 0338                catch (JsonException)
 339                {
 340                    // Ignore the exception
 0341                }
 0342                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0343                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0344                if (_shouldTrace)
 345                {
 0346                    ServiceClientTracing.Error(_invocationId, ex);
 347                }
 0348                _httpRequest.Dispose();
 0349                if (_httpResponse != null)
 350                {
 0351                    _httpResponse.Dispose();
 352                }
 0353                throw ex;
 354            }
 355            // Create Result
 0356            var _result = new HttpOperationResponse();
 0357            _result.Request = _httpRequest;
 0358            _result.Response = _httpResponse;
 0359            if (_shouldTrace)
 360            {
 0361                ServiceClientTracing.Exit(_invocationId, _result);
 362            }
 0363            return _result;
 0364        }
 365
 366    }
 367}