< Summary

Class:Microsoft.Azure.ContainerRegistry.AccessTokensOperations
Assembly:Microsoft.Azure.ContainerRegistry
File(s):C:\Git\azure-sdk-for-net\sdk\containerregistry\Microsoft.Azure.ContainerRegistry\src\Generated\AccessTokensOperations.cs
Covered lines:111
Uncovered lines:83
Coverable lines:194
Total lines:457
Line coverage:57.2% (111 of 194)
Covered branches:62
Total branches:116
Branch coverage:53.4% (62 of 116)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
.ctor(...)-80%50%
get_Client()-100%100%
GetWithHttpMessagesAsync()-57%53.33%
GetFromLoginWithHttpMessagesAsync()-55.68%53.7%

File(s)

C:\Git\azure-sdk-for-net\sdk\containerregistry\Microsoft.Azure.ContainerRegistry\src\Generated\AccessTokensOperations.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.ContainerRegistry
 12{
 13    using Microsoft.Rest;
 14    using Microsoft.Rest.Azure;
 15    using Models;
 16    using Newtonsoft.Json;
 17    using System.Collections;
 18    using System.Collections.Generic;
 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    /// AccessTokensOperations operations.
 27    /// </summary>
 28    internal partial class AccessTokensOperations : IServiceOperations<AzureContainerRegistryClient>, IAccessTokensOpera
 29    {
 30        /// <summary>
 31        /// Initializes a new instance of the AccessTokensOperations 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>
 6039        internal AccessTokensOperations(AzureContainerRegistryClient client)
 40        {
 6041            if (client == null)
 42            {
 043                throw new System.ArgumentNullException("client");
 44            }
 6045            Client = client;
 6046        }
 47
 48        /// <summary>
 49        /// Gets a reference to the AzureContainerRegistryClient
 50        /// </summary>
 10451        public AzureContainerRegistryClient Client { get; private set; }
 52
 53        /// <summary>
 54        /// Exchange ACR Refresh token for an ACR Access Token
 55        /// </summary>
 56        /// <param name='service'>
 57        /// Indicates the name of your Azure container registry.
 58        /// </param>
 59        /// <param name='scope'>
 60        /// Which is expected to be a valid scope, and can be specified more than once
 61        /// for multiple scope requests. You obtained this from the Www-Authenticate
 62        /// response header from the challenge.
 63        /// </param>
 64        /// <param name='refreshToken'>
 65        /// Must be a valid ACR refresh token
 66        /// </param>
 67        /// <param name='customHeaders'>
 68        /// Headers that will be added to request.
 69        /// </param>
 70        /// <param name='cancellationToken'>
 71        /// The cancellation token.
 72        /// </param>
 73        /// <exception cref="AcrErrorsException">
 74        /// Thrown when the operation returned an invalid status code
 75        /// </exception>
 76        /// <exception cref="SerializationException">
 77        /// Thrown when unable to deserialize the response
 78        /// </exception>
 79        /// <exception cref="ValidationException">
 80        /// Thrown when a required parameter is null
 81        /// </exception>
 82        /// <exception cref="System.ArgumentNullException">
 83        /// Thrown when a required parameter is null
 84        /// </exception>
 85        /// <return>
 86        /// A response object containing the response body and response headers.
 87        /// </return>
 88        public async Task<AzureOperationResponse<AccessToken>> GetWithHttpMessagesAsync(string service, string scope, st
 89        {
 290            if (Client.LoginUri == null)
 91            {
 092                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.LoginUri");
 93            }
 294            if (service == null)
 95            {
 096                throw new ValidationException(ValidationRules.CannotBeNull, "service");
 97            }
 298            if (scope == null)
 99            {
 0100                throw new ValidationException(ValidationRules.CannotBeNull, "scope");
 101            }
 2102            if (refreshToken == null)
 103            {
 0104                throw new ValidationException(ValidationRules.CannotBeNull, "refreshToken");
 105            }
 2106            string grantType = "refresh_token";
 107            // Tracing
 2108            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 2109            string _invocationId = null;
 2110            if (_shouldTrace)
 111            {
 0112                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0113                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0114                tracingParameters.Add("grantType", grantType);
 0115                tracingParameters.Add("service", service);
 0116                tracingParameters.Add("scope", scope);
 0117                tracingParameters.Add("refreshToken", refreshToken);
 0118                tracingParameters.Add("cancellationToken", cancellationToken);
 0119                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
 120            }
 121            // Construct URL
 2122            var _baseUrl = Client.BaseUri;
 2123            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "oauth2/token";
 2124            _url = _url.Replace("{url}", Client.LoginUri);
 2125            List<string> _queryParameters = new List<string>();
 2126            if (_queryParameters.Count > 0)
 127            {
 0128                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
 129            }
 130            // Create HTTP transport objects
 2131            var _httpRequest = new HttpRequestMessage();
 2132            HttpResponseMessage _httpResponse = null;
 2133            _httpRequest.Method = new HttpMethod("POST");
 2134            _httpRequest.RequestUri = new System.Uri(_url);
 135            // Set Headers
 2136            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
 137            {
 2138                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString())
 139            }
 2140            if (Client.AcceptLanguage != null)
 141            {
 2142                if (_httpRequest.Headers.Contains("accept-language"))
 143                {
 0144                    _httpRequest.Headers.Remove("accept-language");
 145                }
 2146                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
 147            }
 148
 149
 2150            if (customHeaders != null)
 151            {
 0152                foreach(var _header in customHeaders)
 153                {
 0154                    if (_httpRequest.Headers.Contains(_header.Key))
 155                    {
 0156                        _httpRequest.Headers.Remove(_header.Key);
 157                    }
 0158                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 159                }
 160            }
 161
 162            // Serialize Request
 2163            string _requestContent = null;
 2164            var values = new List<KeyValuePair<string, string>>();
 2165            if(grantType != null)
 166            {
 2167                values.Add(new KeyValuePair<string,string>("grant_type", grantType));
 168            }
 2169            if(service != null)
 170            {
 2171                values.Add(new KeyValuePair<string,string>("service", service));
 172            }
 2173            if(scope != null)
 174            {
 2175                values.Add(new KeyValuePair<string,string>("scope", scope));
 176            }
 2177            if(refreshToken != null)
 178            {
 2179                values.Add(new KeyValuePair<string,string>("refresh_token", refreshToken));
 180            }
 2181            var _formContent = new FormUrlEncodedContent(values);
 2182            _httpRequest.Content = _formContent;
 183            // Set Credentials
 2184            if (Client.Credentials != null)
 185            {
 2186                cancellationToken.ThrowIfCancellationRequested();
 2187                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 188            }
 189            // Send Request
 2190            if (_shouldTrace)
 191            {
 0192                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 193            }
 2194            cancellationToken.ThrowIfCancellationRequested();
 2195            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 2196            if (_shouldTrace)
 197            {
 0198                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 199            }
 2200            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 2201            cancellationToken.ThrowIfCancellationRequested();
 2202            string _responseContent = null;
 2203            if ((int)_statusCode != 200)
 204            {
 0205                var ex = new AcrErrorsException(string.Format("Operation returned an invalid status code '{0}'", _status
 206                try
 207                {
 0208                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0209                    AcrErrors _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<AcrErrors>(_responseCon
 0210                    if (_errorBody != null)
 211                    {
 0212                        ex.Body = _errorBody;
 213                    }
 0214                }
 0215                catch (JsonException)
 216                {
 217                    // Ignore the exception
 0218                }
 0219                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0220                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0221                if (_shouldTrace)
 222                {
 0223                    ServiceClientTracing.Error(_invocationId, ex);
 224                }
 0225                _httpRequest.Dispose();
 0226                if (_httpResponse != null)
 227                {
 0228                    _httpResponse.Dispose();
 229                }
 0230                throw ex;
 231            }
 232            // Create Result
 2233            var _result = new AzureOperationResponse<AccessToken>();
 2234            _result.Request = _httpRequest;
 2235            _result.Response = _httpResponse;
 2236            if (_httpResponse.Headers.Contains("x-ms-request-id"))
 237            {
 0238                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
 239            }
 240            // Deserialize Response
 2241            if ((int)_statusCode == 200)
 242            {
 2243                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 244                try
 245                {
 2246                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessToken>(_responseContent, C
 2247                }
 0248                catch (JsonException ex)
 249                {
 0250                    _httpRequest.Dispose();
 0251                    if (_httpResponse != null)
 252                    {
 0253                        _httpResponse.Dispose();
 254                    }
 0255                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 256                }
 257            }
 2258            if (_shouldTrace)
 259            {
 0260                ServiceClientTracing.Exit(_invocationId, _result);
 261            }
 2262            return _result;
 2263        }
 264
 265        /// <summary>
 266        /// Exchange Username, Password and Scope an ACR Access Token
 267        /// </summary>
 268        /// <param name='service'>
 269        /// Indicates the name of your Azure container registry.
 270        /// </param>
 271        /// <param name='scope'>
 272        /// Expected to be a valid scope, and can be specified more than once for
 273        /// multiple scope requests. You can obtain this from the Www-Authenticate
 274        /// response header from the challenge.
 275        /// </param>
 276        /// <param name='customHeaders'>
 277        /// Headers that will be added to request.
 278        /// </param>
 279        /// <param name='cancellationToken'>
 280        /// The cancellation token.
 281        /// </param>
 282        /// <exception cref="AcrErrorsException">
 283        /// Thrown when the operation returned an invalid status code
 284        /// </exception>
 285        /// <exception cref="SerializationException">
 286        /// Thrown when unable to deserialize the response
 287        /// </exception>
 288        /// <exception cref="ValidationException">
 289        /// Thrown when a required parameter is null
 290        /// </exception>
 291        /// <exception cref="System.ArgumentNullException">
 292        /// Thrown when a required parameter is null
 293        /// </exception>
 294        /// <return>
 295        /// A response object containing the response body and response headers.
 296        /// </return>
 297        public async Task<AzureOperationResponse<AccessToken>> GetFromLoginWithHttpMessagesAsync(string service, string 
 298        {
 2299            if (Client.LoginUri == null)
 300            {
 0301                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.LoginUri");
 302            }
 2303            if (service == null)
 304            {
 0305                throw new ValidationException(ValidationRules.CannotBeNull, "service");
 306            }
 2307            if (scope == null)
 308            {
 0309                throw new ValidationException(ValidationRules.CannotBeNull, "scope");
 310            }
 311            // Tracing
 2312            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 2313            string _invocationId = null;
 2314            if (_shouldTrace)
 315            {
 0316                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0317                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0318                tracingParameters.Add("service", service);
 0319                tracingParameters.Add("scope", scope);
 0320                tracingParameters.Add("cancellationToken", cancellationToken);
 0321                ServiceClientTracing.Enter(_invocationId, this, "GetFromLogin", tracingParameters);
 322            }
 323            // Construct URL
 2324            var _baseUrl = Client.BaseUri;
 2325            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "oauth2/token";
 2326            _url = _url.Replace("{url}", Client.LoginUri);
 2327            List<string> _queryParameters = new List<string>();
 2328            if (service != null)
 329            {
 2330                _queryParameters.Add(string.Format("service={0}", System.Uri.EscapeDataString(service)));
 331            }
 2332            if (scope != null)
 333            {
 2334                _queryParameters.Add(string.Format("scope={0}", System.Uri.EscapeDataString(scope)));
 335            }
 2336            if (_queryParameters.Count > 0)
 337            {
 2338                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
 339            }
 340            // Create HTTP transport objects
 2341            var _httpRequest = new HttpRequestMessage();
 2342            HttpResponseMessage _httpResponse = null;
 2343            _httpRequest.Method = new HttpMethod("GET");
 2344            _httpRequest.RequestUri = new System.Uri(_url);
 345            // Set Headers
 2346            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
 347            {
 2348                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString())
 349            }
 2350            if (Client.AcceptLanguage != null)
 351            {
 2352                if (_httpRequest.Headers.Contains("accept-language"))
 353                {
 0354                    _httpRequest.Headers.Remove("accept-language");
 355                }
 2356                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
 357            }
 358
 359
 2360            if (customHeaders != null)
 361            {
 0362                foreach(var _header in customHeaders)
 363                {
 0364                    if (_httpRequest.Headers.Contains(_header.Key))
 365                    {
 0366                        _httpRequest.Headers.Remove(_header.Key);
 367                    }
 0368                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 369                }
 370            }
 371
 372            // Serialize Request
 2373            string _requestContent = null;
 374            // Set Credentials
 2375            if (Client.Credentials != null)
 376            {
 2377                cancellationToken.ThrowIfCancellationRequested();
 2378                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 379            }
 380            // Send Request
 2381            if (_shouldTrace)
 382            {
 0383                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 384            }
 2385            cancellationToken.ThrowIfCancellationRequested();
 2386            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 2387            if (_shouldTrace)
 388            {
 0389                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 390            }
 2391            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 2392            cancellationToken.ThrowIfCancellationRequested();
 2393            string _responseContent = null;
 2394            if ((int)_statusCode != 200)
 395            {
 0396                var ex = new AcrErrorsException(string.Format("Operation returned an invalid status code '{0}'", _status
 397                try
 398                {
 0399                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0400                    AcrErrors _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<AcrErrors>(_responseCon
 0401                    if (_errorBody != null)
 402                    {
 0403                        ex.Body = _errorBody;
 404                    }
 0405                }
 0406                catch (JsonException)
 407                {
 408                    // Ignore the exception
 0409                }
 0410                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0411                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0412                if (_shouldTrace)
 413                {
 0414                    ServiceClientTracing.Error(_invocationId, ex);
 415                }
 0416                _httpRequest.Dispose();
 0417                if (_httpResponse != null)
 418                {
 0419                    _httpResponse.Dispose();
 420                }
 0421                throw ex;
 422            }
 423            // Create Result
 2424            var _result = new AzureOperationResponse<AccessToken>();
 2425            _result.Request = _httpRequest;
 2426            _result.Response = _httpResponse;
 2427            if (_httpResponse.Headers.Contains("x-ms-request-id"))
 428            {
 0429                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
 430            }
 431            // Deserialize Response
 2432            if ((int)_statusCode == 200)
 433            {
 2434                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 435                try
 436                {
 2437                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessToken>(_responseContent, C
 2438                }
 0439                catch (JsonException ex)
 440                {
 0441                    _httpRequest.Dispose();
 0442                    if (_httpResponse != null)
 443                    {
 0444                        _httpResponse.Dispose();
 445                    }
 0446                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 447                }
 448            }
 2449            if (_shouldTrace)
 450            {
 0451                ServiceClientTracing.Exit(_invocationId, _result);
 452            }
 2453            return _result;
 2454        }
 455
 456    }
 457}