< Summary

Class:Microsoft.Azure.CognitiveServices.Personalizer.PersonalizerClient
Assembly:Microsoft.Azure.CognitiveServices.Personalizer
File(s):C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Personalizer\src\Customizations\PersonalizerClient.Initialize.cs
C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Personalizer\src\Generated\PersonalizerClient.cs
Covered lines:98
Uncovered lines:56
Coverable lines:154
Total lines:431
Line coverage:63.6% (98 of 154)
Covered branches:20
Total branches:50
Branch coverage:40% (20 of 50)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
CustomInitialize()-100%100%
get_BaseUri()-100%100%
get_SerializationSettings()-100%100%
get_DeserializationSettings()-100%100%
get_Endpoint()-100%100%
get_Credentials()-100%100%
get_ServiceConfiguration()-100%100%
get_Policy()-100%100%
get_Evaluations()-100%100%
get_Events()-100%100%
get_Log()-100%100%
get_Model()-100%100%
.ctor(...)-0%100%
.ctor(...)-100%100%
.ctor(...)-0%100%
.ctor(...)-85.71%75%
.ctor(...)-0%0%
.ctor(...)-0%0%
Initialize()-100%100%
RankWithHttpMessagesAsync()-53.95%44.74%

File(s)

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Personalizer\src\Customizations\PersonalizerClient.Initialize.cs

#LineLine coverage
 1using Newtonsoft.Json.Serialization;
 2
 3namespace Microsoft.Azure.CognitiveServices.Personalizer
 4{
 5    public partial class PersonalizerClient
 6    {
 7        partial void CustomInitialize()
 8        {
 349            SerializationSettings.ContractResolver = new DefaultContractResolver();
 3410            DeserializationSettings.ContractResolver = new DefaultContractResolver();
 3411        }
 12    }
 13}

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\Personalizer\src\Generated\PersonalizerClient.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.Personalizer
 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    /// Personalizer Service is an Azure Cognitive Service that makes it easy
 26    /// to target content and experiences without complex pre-analysis or
 27    /// cleanup of past data. Given a context and featurized content, the
 28    /// Personalizer Service returns which content item to show to users in
 29    /// rewardActionId. As rewards are sent in response to the use of
 30    /// rewardActionId, the reinforcement learning algorithm will improve the
 31    /// model and improve performance of future rank calls.
 32    /// </summary>
 33    public partial class PersonalizerClient : ServiceClient<PersonalizerClient>, IPersonalizerClient
 34    {
 35        /// <summary>
 36        /// The base URI of the service.
 37        /// </summary>
 6838        internal string BaseUri {get; set;}
 39
 40        /// <summary>
 41        /// Gets or sets json serialization settings.
 42        /// </summary>
 8043        public JsonSerializerSettings SerializationSettings { get; private set; }
 44
 45        /// <summary>
 46        /// Gets or sets json deserialization settings.
 47        /// </summary>
 9448        public JsonSerializerSettings DeserializationSettings { get; private set; }
 49
 50        /// <summary>
 51        /// Supported Cognitive Services endpoint.
 52        /// </summary>
 10253        public string Endpoint { get; set; }
 54
 55        /// <summary>
 56        /// Subscription credentials which uniquely identify client subscription.
 57        /// </summary>
 17058        public ServiceClientCredentials Credentials { get; private set; }
 59
 60        /// <summary>
 61        /// Gets the IServiceConfigurationOperations.
 62        /// </summary>
 3863        public virtual IServiceConfigurationOperations ServiceConfiguration { get; private set; }
 64
 65        /// <summary>
 66        /// Gets the IPolicy.
 67        /// </summary>
 4068        public virtual IPolicy Policy { get; private set; }
 69
 70        /// <summary>
 71        /// Gets the IEvaluations.
 72        /// </summary>
 4273        public virtual IEvaluations Evaluations { get; private set; }
 74
 75        /// <summary>
 76        /// Gets the IEvents.
 77        /// </summary>
 3678        public virtual IEvents Events { get; private set; }
 79
 80        /// <summary>
 81        /// Gets the ILog.
 82        /// </summary>
 3883        public virtual ILog Log { get; private set; }
 84
 85        /// <summary>
 86        /// Gets the IModel.
 87        /// </summary>
 4088        public virtual IModel Model { get; private set; }
 89
 90        /// <summary>
 91        /// Initializes a new instance of the PersonalizerClient class.
 92        /// </summary>
 93        /// <param name='httpClient'>
 94        /// HttpClient to be used
 95        /// </param>
 96        /// <param name='disposeHttpClient'>
 97        /// True: will dispose the provided httpClient on calling PersonalizerClient.Dispose(). False: will not dispose 
 098        protected PersonalizerClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient
 99        {
 0100            Initialize();
 0101        }
 102
 103        /// <summary>
 104        /// Initializes a new instance of the PersonalizerClient class.
 105        /// </summary>
 106        /// <param name='handlers'>
 107        /// Optional. The delegating handlers to add to the http client pipeline.
 108        /// </param>
 34109        protected PersonalizerClient(params DelegatingHandler[] handlers) : base(handlers)
 110        {
 34111            Initialize();
 34112        }
 113
 114        /// <summary>
 115        /// Initializes a new instance of the PersonalizerClient class.
 116        /// </summary>
 117        /// <param name='rootHandler'>
 118        /// Optional. The http client handler used to handle http transport.
 119        /// </param>
 120        /// <param name='handlers'>
 121        /// Optional. The delegating handlers to add to the http client pipeline.
 122        /// </param>
 0123        protected PersonalizerClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHand
 124        {
 0125            Initialize();
 0126        }
 127
 128        /// <summary>
 129        /// Initializes a new instance of the PersonalizerClient class.
 130        /// </summary>
 131        /// <param name='credentials'>
 132        /// Required. Subscription credentials which uniquely identify client subscription.
 133        /// </param>
 134        /// <param name='handlers'>
 135        /// Optional. The delegating handlers to add to the http client pipeline.
 136        /// </param>
 137        /// <exception cref="System.ArgumentNullException">
 138        /// Thrown when a required parameter is null
 139        /// </exception>
 34140        public PersonalizerClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(hand
 141        {
 34142            if (credentials == null)
 143            {
 0144                throw new System.ArgumentNullException("credentials");
 145            }
 34146            Credentials = credentials;
 34147            if (Credentials != null)
 148            {
 34149                Credentials.InitializeServiceClient(this);
 150            }
 34151        }
 152
 153        /// <summary>
 154        /// Initializes a new instance of the PersonalizerClient class.
 155        /// </summary>
 156        /// <param name='credentials'>
 157        /// Required. Subscription credentials which uniquely identify client subscription.
 158        /// </param>
 159        /// <param name='httpClient'>
 160        /// HttpClient to be used
 161        /// </param>
 162        /// <param name='disposeHttpClient'>
 163        /// True: will dispose the provided httpClient on calling PersonalizerClient.Dispose(). False: will not dispose 
 164        /// <exception cref="System.ArgumentNullException">
 165        /// Thrown when a required parameter is null
 166        /// </exception>
 0167        public PersonalizerClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) :
 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        /// Initializes a new instance of the PersonalizerClient class.
 182        /// </summary>
 183        /// <param name='credentials'>
 184        /// Required. Subscription credentials which uniquely identify client subscription.
 185        /// </param>
 186        /// <param name='rootHandler'>
 187        /// Optional. The http client handler used to handle http transport.
 188        /// </param>
 189        /// <param name='handlers'>
 190        /// Optional. The delegating handlers to add to the http client pipeline.
 191        /// </param>
 192        /// <exception cref="System.ArgumentNullException">
 193        /// Thrown when a required parameter is null
 194        /// </exception>
 0195        public PersonalizerClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params Delegating
 196        {
 0197            if (credentials == null)
 198            {
 0199                throw new System.ArgumentNullException("credentials");
 200            }
 0201            Credentials = credentials;
 0202            if (Credentials != null)
 203            {
 0204                Credentials.InitializeServiceClient(this);
 205            }
 0206        }
 207
 208        /// <summary>
 209        /// An optional partial-method to perform custom initialization.
 210        ///</summary>
 211        partial void CustomInitialize();
 212        /// <summary>
 213        /// Initializes client properties.
 214        /// </summary>
 215        private void Initialize()
 216        {
 34217            ServiceConfiguration = new ServiceConfigurationOperations(this);
 34218            Policy = new Policy(this);
 34219            Evaluations = new Evaluations(this);
 34220            Events = new Events(this);
 34221            Log = new Log(this);
 34222            Model = new Model(this);
 34223            BaseUri = "{Endpoint}/personalizer/v1.0";
 34224            SerializationSettings = new JsonSerializerSettings
 34225            {
 34226                Formatting = Newtonsoft.Json.Formatting.Indented,
 34227                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 34228                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 34229                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 34230                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 34231                ContractResolver = new ReadOnlyJsonContractResolver(),
 34232                Converters = new  List<JsonConverter>
 34233                    {
 34234                        new Iso8601TimeSpanConverter()
 34235                    }
 34236            };
 34237            DeserializationSettings = new JsonSerializerSettings
 34238            {
 34239                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 34240                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 34241                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 34242                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 34243                ContractResolver = new ReadOnlyJsonContractResolver(),
 34244                Converters = new List<JsonConverter>
 34245                    {
 34246                        new Iso8601TimeSpanConverter()
 34247                    }
 34248            };
 34249            CustomInitialize();
 34250        }
 251        /// <summary>
 252        /// Post Rank.
 253        /// </summary>
 254        /// <remarks>
 255        /// Submit a Personalizer rank request, to get which of the provided actions
 256        /// should be used in the provided context.
 257        /// </remarks>
 258        /// <param name='rankRequest'>
 259        /// A Personalizer request.
 260        /// </param>
 261        /// <param name='customHeaders'>
 262        /// Headers that will be added to request.
 263        /// </param>
 264        /// <param name='cancellationToken'>
 265        /// The cancellation token.
 266        /// </param>
 267        /// <exception cref="ErrorResponseException">
 268        /// Thrown when the operation returned an invalid status code
 269        /// </exception>
 270        /// <exception cref="SerializationException">
 271        /// Thrown when unable to deserialize the response
 272        /// </exception>
 273        /// <exception cref="ValidationException">
 274        /// Thrown when a required parameter is null
 275        /// </exception>
 276        /// <exception cref="System.ArgumentNullException">
 277        /// Thrown when a required parameter is null
 278        /// </exception>
 279        /// <return>
 280        /// A response object containing the response body and response headers.
 281        /// </return>
 282        public async Task<HttpOperationResponse<RankResponse>> RankWithHttpMessagesAsync(RankRequest rankRequest, Dictio
 283        {
 4284            if (Endpoint == null)
 285            {
 0286                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
 287            }
 4288            if (rankRequest == null)
 289            {
 0290                throw new ValidationException(ValidationRules.CannotBeNull, "rankRequest");
 291            }
 4292            if (rankRequest != null)
 293            {
 4294                rankRequest.Validate();
 295            }
 296            // Tracing
 4297            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 4298            string _invocationId = null;
 4299            if (_shouldTrace)
 300            {
 0301                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0302                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0303                tracingParameters.Add("rankRequest", rankRequest);
 0304                tracingParameters.Add("cancellationToken", cancellationToken);
 0305                ServiceClientTracing.Enter(_invocationId, this, "Rank", tracingParameters);
 306            }
 307            // Construct URL
 4308            var _baseUrl = BaseUri;
 4309            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "rank";
 4310            _url = _url.Replace("{Endpoint}", Endpoint);
 311            // Create HTTP transport objects
 4312            var _httpRequest = new HttpRequestMessage();
 4313            HttpResponseMessage _httpResponse = null;
 4314            _httpRequest.Method = new HttpMethod("POST");
 4315            _httpRequest.RequestUri = new System.Uri(_url);
 316            // Set Headers
 317
 318
 4319            if (customHeaders != null)
 320            {
 0321                foreach(var _header in customHeaders)
 322                {
 0323                    if (_httpRequest.Headers.Contains(_header.Key))
 324                    {
 0325                        _httpRequest.Headers.Remove(_header.Key);
 326                    }
 0327                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 328                }
 329            }
 330
 331            // Serialize Request
 4332            string _requestContent = null;
 4333            if(rankRequest != null)
 334            {
 4335                _requestContent = SafeJsonConvert.SerializeObject(rankRequest, SerializationSettings);
 4336                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 4337                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 338            }
 339            // Set Credentials
 4340            if (Credentials != null)
 341            {
 4342                cancellationToken.ThrowIfCancellationRequested();
 4343                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 344            }
 345            // Send Request
 4346            if (_shouldTrace)
 347            {
 0348                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 349            }
 4350            cancellationToken.ThrowIfCancellationRequested();
 4351            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 4352            if (_shouldTrace)
 353            {
 0354                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 355            }
 4356            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 4357            cancellationToken.ThrowIfCancellationRequested();
 4358            string _responseContent = null;
 4359            if ((int)_statusCode != 201)
 360            {
 0361                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 362                try
 363                {
 0364                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0365                    ErrorResponse _errorBody =  SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deser
 0366                    if (_errorBody != null)
 367                    {
 0368                        ex.Body = _errorBody;
 369                    }
 0370                }
 0371                catch (JsonException)
 372                {
 373                    // Ignore the exception
 0374                }
 0375                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0376                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0377                if (_shouldTrace)
 378                {
 0379                    ServiceClientTracing.Error(_invocationId, ex);
 380                }
 0381                _httpRequest.Dispose();
 0382                if (_httpResponse != null)
 383                {
 0384                    _httpResponse.Dispose();
 385                }
 0386                throw ex;
 387            }
 388            // Create Result
 4389            var _result = new HttpOperationResponse<RankResponse>();
 4390            _result.Request = _httpRequest;
 4391            _result.Response = _httpResponse;
 392            // Deserialize Response
 4393            if ((int)_statusCode == 201)
 394            {
 4395                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 396                try
 397                {
 4398                    _result.Body = SafeJsonConvert.DeserializeObject<RankResponse>(_responseContent, DeserializationSett
 4399                }
 0400                catch (JsonException ex)
 401                {
 0402                    _httpRequest.Dispose();
 0403                    if (_httpResponse != null)
 404                    {
 0405                        _httpResponse.Dispose();
 406                    }
 0407                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 408                }
 409            }
 4410            if (_shouldTrace)
 411            {
 0412                ServiceClientTracing.Exit(_invocationId, _result);
 413            }
 4414            return _result;
 4415        }
 416
 417    }
 418}