< Summary

Class:Microsoft.Azure.EventGrid.EventGridClient
Assembly:Microsoft.Azure.EventGrid
File(s):C:\Git\azure-sdk-for-net\sdk\eventgrid\Microsoft.Azure.EventGrid\src\Generated\EventGridClient.cs
Covered lines:101
Uncovered lines:59
Coverable lines:160
Total lines:420
Line coverage:63.1% (101 of 160)
Covered branches:36
Total branches:68
Branch coverage:52.9% (36 of 68)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
get_BaseUri()-100%100%
get_SerializationSettings()-100%100%
get_DeserializationSettings()-100%100%
get_Credentials()-100%100%
get_ApiVersion()-0%100%
get_AcceptLanguage()-100%100%
get_LongRunningOperationRetryTimeout()-0%100%
get_GenerateClientRequestId()-100%100%
.ctor(...)-0%100%
.ctor(...)-100%100%
.ctor(...)-0%100%
.ctor(...)-85.71%75%
.ctor(...)-0%0%
.ctor(...)-0%0%
Initialize()-100%100%
PublishEventsWithHttpMessagesAsync()-59.09%58.93%

File(s)

C:\Git\azure-sdk-for-net\sdk\eventgrid\Microsoft.Azure.EventGrid\src\Generated\EventGridClient.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.EventGrid
 12{
 13    using Microsoft.Rest;
 14    using Microsoft.Rest.Azure;
 15    using Microsoft.Rest.Serialization;
 16    using Models;
 17    using Newtonsoft.Json;
 18    using System.Collections;
 19    using System.Collections.Generic;
 20    using System.Linq;
 21    using System.Net;
 22    using System.Net.Http;
 23    using System.Threading;
 24    using System.Threading.Tasks;
 25
 26    /// <summary>
 27    /// EventGrid Client
 28    /// </summary>
 29    public partial class EventGridClient : ServiceClient<EventGridClient>, IEventGridClient, IAzureClient
 30    {
 31        /// <summary>
 32        /// The base URI of the service.
 33        /// </summary>
 434        internal string BaseUri {get; set;}
 35
 36        /// <summary>
 37        /// Gets or sets json serialization settings.
 38        /// </summary>
 639        public JsonSerializerSettings SerializationSettings { get; private set; }
 40
 41        /// <summary>
 42        /// Gets or sets json deserialization settings.
 43        /// </summary>
 644        public JsonSerializerSettings DeserializationSettings { get; private set; }
 45
 46        /// <summary>
 47        /// Credentials needed for the client to connect to Azure.
 48        /// </summary>
 1049        public ServiceClientCredentials Credentials { get; private set; }
 50
 51        /// <summary>
 52        /// Version of the API to be used with the client request.
 53        /// </summary>
 054        public string ApiVersion { get; private set; }
 55
 56        /// <summary>
 57        /// The preferred language for the response.
 58        /// </summary>
 659        public string AcceptLanguage { get; set; }
 60
 61        /// <summary>
 62        /// The retry timeout in seconds for Long Running Operations. Default value is
 63        /// 30.
 64        /// </summary>
 065        public int? LongRunningOperationRetryTimeout { get; set; }
 66
 67        /// <summary>
 68        /// Whether a unique x-ms-client-request-id should be generated. When set to
 69        /// true a unique x-ms-client-request-id value is generated and included in
 70        /// each request. Default is true.
 71        /// </summary>
 672        public bool? GenerateClientRequestId { get; set; }
 73
 74        /// <summary>
 75        /// Initializes a new instance of the EventGridClient class.
 76        /// </summary>
 77        /// <param name='httpClient'>
 78        /// HttpClient to be used
 79        /// </param>
 80        /// <param name='disposeHttpClient'>
 81        /// True: will dispose the provided httpClient on calling EventGridClient.Dispose(). False: will not dispose pro
 082        protected EventGridClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
 83        {
 084            Initialize();
 085        }
 86
 87        /// <summary>
 88        /// Initializes a new instance of the EventGridClient class.
 89        /// </summary>
 90        /// <param name='handlers'>
 91        /// Optional. The delegating handlers to add to the http client pipeline.
 92        /// </param>
 293        protected EventGridClient(params DelegatingHandler[] handlers) : base(handlers)
 94        {
 295            Initialize();
 296        }
 97
 98        /// <summary>
 99        /// Initializes a new instance of the EventGridClient class.
 100        /// </summary>
 101        /// <param name='rootHandler'>
 102        /// Optional. The http client handler used to handle http transport.
 103        /// </param>
 104        /// <param name='handlers'>
 105        /// Optional. The delegating handlers to add to the http client pipeline.
 106        /// </param>
 0107        protected EventGridClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler
 108        {
 0109            Initialize();
 0110        }
 111
 112        /// <summary>
 113        /// Initializes a new instance of the EventGridClient class.
 114        /// </summary>
 115        /// <param name='credentials'>
 116        /// Required. Credentials needed for the client to connect to Azure.
 117        /// </param>
 118        /// <param name='handlers'>
 119        /// Optional. The delegating handlers to add to the http client pipeline.
 120        /// </param>
 121        /// <exception cref="System.ArgumentNullException">
 122        /// Thrown when a required parameter is null
 123        /// </exception>
 2124        public EventGridClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handler
 125        {
 2126            if (credentials == null)
 127            {
 0128                throw new System.ArgumentNullException("credentials");
 129            }
 2130            Credentials = credentials;
 2131            if (Credentials != null)
 132            {
 2133                Credentials.InitializeServiceClient(this);
 134            }
 2135        }
 136
 137        /// <summary>
 138        /// Initializes a new instance of the EventGridClient class.
 139        /// </summary>
 140        /// <param name='credentials'>
 141        /// Required. Credentials needed for the client to connect to Azure.
 142        /// </param>
 143        /// <param name='httpClient'>
 144        /// HttpClient to be used
 145        /// </param>
 146        /// <param name='disposeHttpClient'>
 147        /// True: will dispose the provided httpClient on calling EventGridClient.Dispose(). False: will not dispose pro
 148        /// <exception cref="System.ArgumentNullException">
 149        /// Thrown when a required parameter is null
 150        /// </exception>
 0151        public EventGridClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : th
 152        {
 0153            if (credentials == null)
 154            {
 0155                throw new System.ArgumentNullException("credentials");
 156            }
 0157            Credentials = credentials;
 0158            if (Credentials != null)
 159            {
 0160                Credentials.InitializeServiceClient(this);
 161            }
 0162        }
 163
 164        /// <summary>
 165        /// Initializes a new instance of the EventGridClient class.
 166        /// </summary>
 167        /// <param name='credentials'>
 168        /// Required. Credentials needed for the client to connect to Azure.
 169        /// </param>
 170        /// <param name='rootHandler'>
 171        /// Optional. The http client handler used to handle http transport.
 172        /// </param>
 173        /// <param name='handlers'>
 174        /// Optional. The delegating handlers to add to the http client pipeline.
 175        /// </param>
 176        /// <exception cref="System.ArgumentNullException">
 177        /// Thrown when a required parameter is null
 178        /// </exception>
 0179        public EventGridClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHan
 180        {
 0181            if (credentials == null)
 182            {
 0183                throw new System.ArgumentNullException("credentials");
 184            }
 0185            Credentials = credentials;
 0186            if (Credentials != null)
 187            {
 0188                Credentials.InitializeServiceClient(this);
 189            }
 0190        }
 191
 192        /// <summary>
 193        /// An optional partial-method to perform custom initialization.
 194        /// </summary>
 195        partial void CustomInitialize();
 196        /// <summary>
 197        /// Initializes client properties.
 198        /// </summary>
 199        private void Initialize()
 200        {
 2201            BaseUri = "https://{topicHostname}";
 2202            ApiVersion = "2018-01-01";
 2203            AcceptLanguage = "en-US";
 2204            LongRunningOperationRetryTimeout = 30;
 2205            GenerateClientRequestId = true;
 2206            SerializationSettings = new JsonSerializerSettings
 2207            {
 2208                Formatting = Newtonsoft.Json.Formatting.Indented,
 2209                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 2210                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 2211                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 2212                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 2213                ContractResolver = new ReadOnlyJsonContractResolver(),
 2214                Converters = new List<JsonConverter>
 2215                    {
 2216                        new Iso8601TimeSpanConverter()
 2217                    }
 2218            };
 2219            DeserializationSettings = new JsonSerializerSettings
 2220            {
 2221                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
 2222                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
 2223                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
 2224                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
 2225                ContractResolver = new ReadOnlyJsonContractResolver(),
 2226                Converters = new List<JsonConverter>
 2227                    {
 2228                        new Iso8601TimeSpanConverter()
 2229                    }
 2230            };
 2231            SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<MediaJobOutput>("@odata.type"));
 2232            DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<MediaJobOutput>("@odata.type"
 233            CustomInitialize();
 2234            DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
 2235        }
 236        /// <summary>
 237        /// Publishes a batch of events to an Azure Event Grid topic.
 238        /// </summary>
 239        /// <param name='topicHostname'>
 240        /// The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net
 241        /// </param>
 242        /// <param name='events'>
 243        /// An array of events to be published to Event Grid.
 244        /// </param>
 245        /// <param name='customHeaders'>
 246        /// Headers that will be added to request.
 247        /// </param>
 248        /// <param name='cancellationToken'>
 249        /// The cancellation token.
 250        /// </param>
 251        /// <exception cref="CloudException">
 252        /// Thrown when the operation returned an invalid status code
 253        /// </exception>
 254        /// <exception cref="ValidationException">
 255        /// Thrown when a required parameter is null
 256        /// </exception>
 257        /// <exception cref="System.ArgumentNullException">
 258        /// Thrown when a required parameter is null
 259        /// </exception>
 260        /// <return>
 261        /// A response object containing the response body and response headers.
 262        /// </return>
 263        public async Task<AzureOperationResponse> PublishEventsWithHttpMessagesAsync(string topicHostname, IList<EventGr
 264        {
 2265            if (topicHostname == null)
 266            {
 0267                throw new ValidationException(ValidationRules.CannotBeNull, "topicHostname");
 268            }
 2269            if (events == null)
 270            {
 0271                throw new ValidationException(ValidationRules.CannotBeNull, "events");
 272            }
 2273            if (events != null)
 274            {
 44275                foreach (var element in events)
 276                {
 20277                    if (element != null)
 278                    {
 20279                        element.Validate();
 280                    }
 281                }
 282            }
 2283            string apiVersion = "2018-01-01";
 284            // Tracing
 2285            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 2286            string _invocationId = null;
 2287            if (_shouldTrace)
 288            {
 0289                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 0290                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 0291                tracingParameters.Add("topicHostname", topicHostname);
 0292                tracingParameters.Add("events", events);
 0293                tracingParameters.Add("apiVersion", apiVersion);
 0294                tracingParameters.Add("cancellationToken", cancellationToken);
 0295                ServiceClientTracing.Enter(_invocationId, this, "PublishEvents", tracingParameters);
 296            }
 297            // Construct URL
 2298            var _baseUrl = BaseUri;
 2299            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "api/events";
 2300            _url = _url.Replace("{topicHostname}", topicHostname);
 2301            List<string> _queryParameters = new List<string>();
 2302            if (apiVersion != null)
 303            {
 2304                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
 305            }
 2306            if (_queryParameters.Count > 0)
 307            {
 2308                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
 309            }
 310            // Create HTTP transport objects
 2311            var _httpRequest = new HttpRequestMessage();
 2312            HttpResponseMessage _httpResponse = null;
 2313            _httpRequest.Method = new HttpMethod("POST");
 2314            _httpRequest.RequestUri = new System.Uri(_url);
 315            // Set Headers
 2316            if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
 317            {
 2318                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString())
 319            }
 2320            if (AcceptLanguage != null)
 321            {
 2322                if (_httpRequest.Headers.Contains("accept-language"))
 323                {
 0324                    _httpRequest.Headers.Remove("accept-language");
 325                }
 2326                _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
 327            }
 328
 329
 2330            if (customHeaders != null)
 331            {
 0332                foreach(var _header in customHeaders)
 333                {
 0334                    if (_httpRequest.Headers.Contains(_header.Key))
 335                    {
 0336                        _httpRequest.Headers.Remove(_header.Key);
 337                    }
 0338                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 339                }
 340            }
 341
 342            // Serialize Request
 2343            string _requestContent = null;
 2344            if(events != null)
 345            {
 2346                _requestContent = SafeJsonConvert.SerializeObject(events, SerializationSettings);
 2347                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
 2348                _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("applicatio
 349            }
 350            // Set Credentials
 2351            if (Credentials != null)
 352            {
 2353                cancellationToken.ThrowIfCancellationRequested();
 2354                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 355            }
 356            // Send Request
 2357            if (_shouldTrace)
 358            {
 0359                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 360            }
 2361            cancellationToken.ThrowIfCancellationRequested();
 2362            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 2363            if (_shouldTrace)
 364            {
 0365                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 366            }
 2367            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 2368            cancellationToken.ThrowIfCancellationRequested();
 2369            string _responseContent = null;
 2370            if ((int)_statusCode != 200)
 371            {
 0372                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode
 373                try
 374                {
 0375                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 0376                    CloudError _errorBody =  SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Deserializa
 0377                    if (_errorBody != null)
 378                    {
 0379                        ex = new CloudException(_errorBody.Message);
 0380                        ex.Body = _errorBody;
 381                    }
 0382                }
 0383                catch (JsonException)
 384                {
 385                    // Ignore the exception
 0386                }
 0387                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 0388                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 0389                if (_httpResponse.Headers.Contains("x-ms-request-id"))
 390                {
 0391                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
 392                }
 0393                if (_shouldTrace)
 394                {
 0395                    ServiceClientTracing.Error(_invocationId, ex);
 396                }
 0397                _httpRequest.Dispose();
 0398                if (_httpResponse != null)
 399                {
 0400                    _httpResponse.Dispose();
 401                }
 0402                throw ex;
 403            }
 404            // Create Result
 2405            var _result = new AzureOperationResponse();
 2406            _result.Request = _httpRequest;
 2407            _result.Response = _httpResponse;
 2408            if (_httpResponse.Headers.Contains("x-ms-request-id"))
 409            {
 2410                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
 411            }
 2412            if (_shouldTrace)
 413            {
 0414                ServiceClientTracing.Exit(_invocationId, _result);
 415            }
 2416            return _result;
 2417        }
 418
 419    }
 420}