diff --git a/AutoRest/AutoRest.Core/Settings.cs b/AutoRest/AutoRest.Core/Settings.cs index df99585e02..94c9fb7f52 100644 --- a/AutoRest/AutoRest.Core/Settings.cs +++ b/AutoRest/AutoRest.Core/Settings.cs @@ -309,6 +309,10 @@ public static void PopulateSettings(object entityToPopulate, IDictionary + /// Test Infrastructure for AutoRest + /// + public partial class AutoRestDurationTestService : ServiceClient, IAutoRestDurationTestService, IAzureClient + { + /// + /// The base URI of the service. + /// + public Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Gets Azure subscription credentials. + /// + public ServiceClientCredentials Credentials { get; private set; } + + /// + /// Gets or sets the preferred language for the response. + /// + public string AcceptLanguage { get; set; } + + /// + /// Gets or sets the retry timeout in seconds for Long Running Operations. + /// Default value is 30. + /// + public int? LongRunningOperationRetryTimeout { get; set; } + + /// + /// When set to true a unique x-ms-client-request-id value is generated and + /// included in each request. Default is true. + /// + public bool? GenerateClientRequestId { get; set; } + + /// + /// Gets the IDurationOperations. + /// + public virtual IDurationOperations Duration { get; private set; } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.BaseUri = baseUri; + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.BaseUri = baseUri; + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.Duration = new DurationOperations(this); + this.BaseUri = new Uri("https://localhost"); + this.AcceptLanguage = "en-US"; + this.LongRunningOperationRetryTimeout = 30; + this.GenerateClientRequestId = true; + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); + } + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperations.cs new file mode 100644 index 0000000000..81ec07668d --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperations.cs @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Microsoft.Rest.Azure; + using Models; + + /// + /// DurationOperations operations. + /// + internal partial class DurationOperations : IServiceOperations, IDurationOperations + { + /// + /// Initializes a new instance of the DurationOperations class. + /// + /// + /// Reference to the service client. + /// + internal DurationOperations(AutoRestDurationTestService client) + { + if (client == null) + { + throw new ArgumentNullException("client"); + } + this.Client = client; + } + + /// + /// Gets a reference to the AutoRestDurationTestService + /// + public AutoRestDurationTestService Client { get; private set; } + + /// + /// Get null duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put a positive duration value + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("durationBody", durationBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get a positive duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetPositiveDurationWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get an invalid duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperationsExtensions.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperationsExtensions.cs new file mode 100644 index 0000000000..6a135327c6 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/DurationOperationsExtensions.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// Extension methods for DurationOperations. + /// + public static partial class DurationOperationsExtensions + { + /// + /// Get null duration value + /// + /// + /// The operations group for this extension method. + /// + public static TimeSpan? GetNull(this IDurationOperations operations) + { + return Task.Factory.StartNew(s => ((IDurationOperations)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get null duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// Headers that will be added to request. + /// + public static AzureOperationResponse GetNullWithHttpMessages(this IDurationOperations operations, Dictionary> customHeaders = null) + { + return operations.GetNullWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Put a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutPositiveDuration(this IDurationOperations operations, TimeSpan durationBody) + { + Task.Factory.StartNew(s => ((IDurationOperations)s).PutPositiveDurationAsync(durationBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutPositiveDurationAsync(this IDurationOperations operations, TimeSpan durationBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutPositiveDurationWithHttpMessagesAsync(durationBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Put a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// Headers that will be added to request. + /// + public static AzureOperationResponse PutPositiveDurationWithHttpMessages(this IDurationOperations operations, TimeSpan durationBody, Dictionary> customHeaders = null) + { + return operations.PutPositiveDurationWithHttpMessagesAsync(durationBody, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Get a positive duration value + /// + /// + /// The operations group for this extension method. + /// + public static TimeSpan? GetPositiveDuration(this IDurationOperations operations) + { + return Task.Factory.StartNew(s => ((IDurationOperations)s).GetPositiveDurationAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetPositiveDurationAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetPositiveDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// Headers that will be added to request. + /// + public static AzureOperationResponse GetPositiveDurationWithHttpMessages(this IDurationOperations operations, Dictionary> customHeaders = null) + { + return operations.GetPositiveDurationWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Get an invalid duration value + /// + /// + /// The operations group for this extension method. + /// + public static TimeSpan? GetInvalid(this IDurationOperations operations) + { + return Task.Factory.StartNew(s => ((IDurationOperations)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get an invalid duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get an invalid duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// Headers that will be added to request. + /// + public static AzureOperationResponse GetInvalidWithHttpMessages(this IDurationOperations operations, Dictionary> customHeaders = null) + { + return operations.GetInvalidWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IAutoRestDurationTestService.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IAutoRestDurationTestService.cs new file mode 100644 index 0000000000..827a67fffa --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IAutoRestDurationTestService.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial interface IAutoRestDurationTestService : IDisposable + { + /// + /// The base URI of the service. + /// + Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// Gets Azure subscription credentials. + /// + ServiceClientCredentials Credentials { get; } + + /// + /// Gets or sets the preferred language for the response. + /// + string AcceptLanguage { get; set; } + + /// + /// Gets or sets the retry timeout in seconds for Long Running + /// Operations. Default value is 30. + /// + int? LongRunningOperationRetryTimeout { get; set; } + + /// + /// When set to true a unique x-ms-client-request-id value is + /// generated and included in each request. Default is true. + /// + bool? GenerateClientRequestId { get; set; } + + + /// + /// Gets the IDurationOperations. + /// + IDurationOperations Duration { get; } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IDurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IDurationOperations.cs new file mode 100644 index 0000000000..08caf84df0 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/IDurationOperations.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// DurationOperations operations. + /// + public partial interface IDurationOperations + { + /// + /// Get null duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put a positive duration value + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get a positive duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetPositiveDurationWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get an invalid duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/Error.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/Error.cs new file mode 100644 index 0000000000..5a2d8bfa1c --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/Error.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Microsoft.Rest.Azure; + + public partial class Error + { + /// + /// Initializes a new instance of the Error class. + /// + public Error() { } + + /// + /// Initializes a new instance of the Error class. + /// + public Error(int? status = default(int?), string message = default(string)) + { + Status = status; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "status")] + public int? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/ErrorException.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/ErrorException.cs new file mode 100644 index 0000000000..8b02d920b4 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationAllSync/Models/ErrorException.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync.Models +{ + using Microsoft.Rest; + using System; + using System.Net.Http; + using System.Runtime.Serialization; +#if !PORTABLE + using System.Security.Permissions; +#endif + + /// + /// Exception thrown for an invalid response with Error information. + /// +#if !PORTABLE + [Serializable] +#endif + public class ErrorException : RestException + { + /// + /// Gets information about the associated HTTP request. + /// + public HttpRequestMessageWrapper Request { get; set; } + + /// + /// Gets information about the associated HTTP response. + /// + public HttpResponseMessageWrapper Response { get; set; } + + /// + /// Gets or sets the body object. + /// + public Error Body { get; set; } + + /// + /// Initializes a new instance of the ErrorException class. + /// + public ErrorException() + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + public ErrorException(string message) + : this(message, null) + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + /// Inner exception. + public ErrorException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !PORTABLE + /// + /// Initializes a new instance of the ErrorException class. + /// + /// Serialization info. + /// Streaming context. + protected ErrorException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + + /// + /// Serializes content of the exception. + /// + /// Serialization info. + /// Streaming context. + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue("Request", Request); + info.AddValue("Response", Response); + info.AddValue("Body", Body); + } +#endif + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/AutoRestDurationTestService.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/AutoRestDurationTestService.cs new file mode 100644 index 0000000000..8adef14be4 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/AutoRestDurationTestService.cs @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Microsoft.Rest.Azure; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial class AutoRestDurationTestService : ServiceClient, IAutoRestDurationTestService, IAzureClient + { + /// + /// The base URI of the service. + /// + public Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Gets Azure subscription credentials. + /// + public ServiceClientCredentials Credentials { get; private set; } + + /// + /// Gets or sets the preferred language for the response. + /// + public string AcceptLanguage { get; set; } + + /// + /// Gets or sets the retry timeout in seconds for Long Running Operations. + /// Default value is 30. + /// + public int? LongRunningOperationRetryTimeout { get; set; } + + /// + /// When set to true a unique x-ms-client-request-id value is generated and + /// included in each request. Default is true. + /// + public bool? GenerateClientRequestId { get; set; } + + /// + /// Gets the IDurationOperations. + /// + public virtual IDurationOperations Duration { get; private set; } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.BaseUri = baseUri; + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the AutoRestDurationTestService class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Gets Azure subscription credentials. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this.BaseUri = baseUri; + this.Credentials = credentials; + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.Duration = new DurationOperations(this); + this.BaseUri = new Uri("https://localhost"); + this.AcceptLanguage = "en-US"; + this.LongRunningOperationRetryTimeout = 30; + this.GenerateClientRequestId = true; + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); + } + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperations.cs new file mode 100644 index 0000000000..44b091050b --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperations.cs @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Microsoft.Rest.Azure; + using Models; + + /// + /// DurationOperations operations. + /// + internal partial class DurationOperations : IServiceOperations, IDurationOperations + { + /// + /// Initializes a new instance of the DurationOperations class. + /// + /// + /// Reference to the service client. + /// + internal DurationOperations(AutoRestDurationTestService client) + { + if (client == null) + { + throw new ArgumentNullException("client"); + } + this.Client = client; + } + + /// + /// Gets a reference to the AutoRestDurationTestService + /// + public AutoRestDurationTestService Client { get; private set; } + + /// + /// Get null duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put a positive duration value + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("durationBody", durationBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get a positive duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetPositiveDurationWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get an invalid duration value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperationsExtensions.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperationsExtensions.cs new file mode 100644 index 0000000000..d71b17b831 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/DurationOperationsExtensions.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// Extension methods for DurationOperations. + /// + public static partial class DurationOperationsExtensions + { + /// + /// Get null duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutPositiveDurationAsync(this IDurationOperations operations, TimeSpan durationBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutPositiveDurationWithHttpMessagesAsync(durationBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a positive duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetPositiveDurationAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetPositiveDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get an invalid duration value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidAsync(this IDurationOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IAutoRestDurationTestService.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IAutoRestDurationTestService.cs new file mode 100644 index 0000000000..fa77d214b3 --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IAutoRestDurationTestService.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial interface IAutoRestDurationTestService : IDisposable + { + /// + /// The base URI of the service. + /// + Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// Gets Azure subscription credentials. + /// + ServiceClientCredentials Credentials { get; } + + /// + /// Gets or sets the preferred language for the response. + /// + string AcceptLanguage { get; set; } + + /// + /// Gets or sets the retry timeout in seconds for Long Running + /// Operations. Default value is 30. + /// + int? LongRunningOperationRetryTimeout { get; set; } + + /// + /// When set to true a unique x-ms-client-request-id value is + /// generated and included in each request. Default is true. + /// + bool? GenerateClientRequestId { get; set; } + + + /// + /// Gets the IDurationOperations. + /// + IDurationOperations Duration { get; } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IDurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IDurationOperations.cs new file mode 100644 index 0000000000..128a7a4cea --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/IDurationOperations.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Azure; + using Models; + + /// + /// DurationOperations operations. + /// + public partial interface IDurationOperations + { + /// + /// Get null duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put a positive duration value + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutPositiveDurationWithHttpMessagesAsync(TimeSpan durationBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get a positive duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetPositiveDurationWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get an invalid duration value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/Error.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/Error.cs new file mode 100644 index 0000000000..6a0e0f606f --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/Error.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Microsoft.Rest.Azure; + + public partial class Error + { + /// + /// Initializes a new instance of the Error class. + /// + public Error() { } + + /// + /// Initializes a new instance of the Error class. + /// + public Error(int? status = default(int?), string message = default(string)) + { + Status = status; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "status")] + public int? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/ErrorException.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/ErrorException.cs new file mode 100644 index 0000000000..1902b5496c --- /dev/null +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDurationNoSync/Models/ErrorException.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync.Models +{ + using Microsoft.Rest; + using System; + using System.Net.Http; + using System.Runtime.Serialization; +#if !PORTABLE + using System.Security.Permissions; +#endif + + /// + /// Exception thrown for an invalid response with Error information. + /// +#if !PORTABLE + [Serializable] +#endif + public class ErrorException : RestException + { + /// + /// Gets information about the associated HTTP request. + /// + public HttpRequestMessageWrapper Request { get; set; } + + /// + /// Gets information about the associated HTTP response. + /// + public HttpResponseMessageWrapper Response { get; set; } + + /// + /// Gets or sets the body object. + /// + public Error Body { get; set; } + + /// + /// Initializes a new instance of the ErrorException class. + /// + public ErrorException() + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + public ErrorException(string message) + : this(message, null) + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + /// Inner exception. + public ErrorException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !PORTABLE + /// + /// Initializes a new instance of the ErrorException class. + /// + /// Serialization info. + /// Streaming context. + protected ErrorException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + + /// + /// Serializes content of the exception. + /// + /// Serialization info. + /// Streaming context. + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue("Request", Request); + info.AddValue("Response", Response); + info.AddValue("Body", Body); + } +#endif + } +} diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs index 85f9fe326a..c2fa13de5c 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs @@ -99,7 +99,7 @@ public override async Task Generate(ServiceClient serviceClient) { var extensionsTemplate = new ExtensionsTemplate { - Model = new AzureExtensionsTemplateModel(serviceClient, null, SyncWrappers), + Model = new AzureExtensionsTemplateModel(serviceClient, null, SyncMethods), }; await Write(extensionsTemplate, serviceClient.Name + "Extensions.cs"); } @@ -124,7 +124,7 @@ public override async Task Generate(ServiceClient serviceClient) // Service client extensions var operationExtensionsTemplate = new ExtensionsTemplate { - Model = new AzureExtensionsTemplateModel(serviceClient, group, SyncWrappers), + Model = new AzureExtensionsTemplateModel(serviceClient, group, SyncMethods), }; await Write(operationExtensionsTemplate, operationExtensionsTemplate.Model.ExtensionName + "Extensions.cs"); diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureExtensionsTemplateModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureExtensionsTemplateModel.cs index 8dcb1228f5..75bb66b25e 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureExtensionsTemplateModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureExtensionsTemplateModel.cs @@ -12,7 +12,7 @@ namespace Microsoft.Rest.Generator.CSharp.Azure { public class AzureExtensionsTemplateModel : ExtensionsTemplateModel { - public AzureExtensionsTemplateModel(ServiceClient serviceClient, string operationName, SyncWrapperGenerationMode syncWrappers) + public AzureExtensionsTemplateModel(ServiceClient serviceClient, string operationName, SyncMethodsGenerationMode syncWrappers) : base(serviceClient, operationName, syncWrappers) { MethodTemplateModels.Clear(); diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodGroupTemplateModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodGroupTemplateModel.cs index ecadbc1708..adc17c0dfa 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodGroupTemplateModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodGroupTemplateModel.cs @@ -20,7 +20,7 @@ public AzureMethodGroupTemplateModel(ServiceClient serviceClient, string methodG // AzureMethodTemplateModel MethodTemplateModels.Clear(); Methods.Where(m => m.Group == methodGroupName) - .ForEach(m => MethodTemplateModels.Add(new AzureMethodTemplateModel(m, serviceClient, SyncWrapperGenerationMode.None))); + .ForEach(m => MethodTemplateModels.Add(new AzureMethodTemplateModel(m, serviceClient, SyncMethodsGenerationMode.None))); } /// diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodTemplateModel.cs index e393a7d502..4fdb8272d7 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureMethodTemplateModel.cs @@ -15,7 +15,7 @@ namespace Microsoft.Rest.Generator.CSharp.Azure { public class AzureMethodTemplateModel : MethodTemplateModel { - public AzureMethodTemplateModel(Method source, ServiceClient serviceClient, SyncWrapperGenerationMode syncWrappers) + public AzureMethodTemplateModel(Method source, ServiceClient serviceClient, SyncMethodsGenerationMode syncWrappers) : base(source, serviceClient, syncWrappers) { if (source == null) @@ -54,7 +54,7 @@ public AzureMethodTemplateModel GetMethod Resources.InvalidLongRunningOperationForCreateOrUpdate, Name, Group)); } - return new AzureMethodTemplateModel(getMethod, ServiceClient, SyncWrappers); + return new AzureMethodTemplateModel(getMethod, ServiceClient, SyncMethods); } } diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureServiceClientTemplateModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureServiceClientTemplateModel.cs index a790ba0367..f48e88336a 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureServiceClientTemplateModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/TemplateModels/AzureServiceClientTemplateModel.cs @@ -18,7 +18,7 @@ public AzureServiceClientTemplateModel(ServiceClient serviceClient, bool interna // TODO: Initialized in the base constructor. Why Clear it? MethodTemplateModels.Clear(); Methods.Where(m => m.Group == null) - .ForEach(m => MethodTemplateModels.Add(new AzureMethodTemplateModel(m, serviceClient, SyncWrapperGenerationMode.None))); + .ForEach(m => MethodTemplateModels.Add(new AzureMethodTemplateModel(m, serviceClient, SyncMethodsGenerationMode.None))); } /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index a2d0b461e7..06eb37287f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -2262,6 +2262,22 @@ public void ModelFlatteningWithGroupingTest() } } + [Fact] + public void SyncMethodsValidation() + { + Type petstoreWithAllSyncMethods = typeof(Fixtures.PetstoreV2AllSync.SwaggerPetstoreV2Extensions); + Assert.NotNull(petstoreWithAllSyncMethods.GetMethod("AddPet")); + Assert.NotNull(petstoreWithAllSyncMethods.GetMethod("AddPetWithHttpMessages")); + + Type petstoreWithNoSyncMethods = typeof(Fixtures.PetstoreV2NoSync.SwaggerPetstoreV2Extensions); + Assert.Null(petstoreWithNoSyncMethods.GetMethod("AddPet")); + Assert.Null(petstoreWithNoSyncMethods.GetMethod("AddPetWithHttpMessages")); + + Type petstoreWithEssentialSyncMethods = typeof(Fixtures.PetstoreV2.SwaggerPetstoreV2Extensions); + Assert.NotNull(petstoreWithEssentialSyncMethods.GetMethod("AddPet")); + Assert.Null(petstoreWithEssentialSyncMethods.GetMethod("AddPetWithHttpMessages")); + } + public void EnsureTestCoverage() { SwaggerSpecRunner.RunTests( diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/ISwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/ISwaggerPetstoreV2.cs new file mode 100644 index 0000000000..05eddda353 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/ISwaggerPetstoreV2.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Models; + + /// + /// This is a sample server Petstore server. You can find out more about + /// Swagger at <a + /// href="http://swagger.io">http://swagger.io</a> or on + /// irc.freenode.net, #swagger. For this sample, you can use the api key + /// "special-key" to test the authorization filters + /// + public partial interface ISwaggerPetstoreV2 : IDisposable + { + /// + /// The base URI of the service. + /// + Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + + /// + /// Add a new pet to the store + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> AddPetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Update an existing pet + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdatePetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> FindPetsByStatusWithHttpMessagesAsync(IList status, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use + /// tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> FindPetsByTagsWithHttpMessagesAsync(IList tags, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// Id of pet to return + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Updates a pet in the store with form data + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Deletes a pet + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetInventoryWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Place an order for a pet + /// + /// + /// order placed for purchasing the pet + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. + /// Other values will generated exceptions + /// + /// Id of pet that needs to be fetched + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything + /// above 1000 or nonintegers will generate API errors + /// + /// Id of the order that needs to be deleted + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUserWithHttpMessagesAsync(User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUsersWithArrayInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUsersWithListInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Logs user into the system + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Logs out current logged in user session + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task LogoutUserWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Get user by user name + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUserByNameWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeleteUserWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/ApiResponse.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/ApiResponse.cs new file mode 100644 index 0000000000..3db78b2246 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/ApiResponse.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class ApiResponse + { + /// + /// Initializes a new instance of the ApiResponse class. + /// + public ApiResponse() { } + + /// + /// Initializes a new instance of the ApiResponse class. + /// + public ApiResponse(int? code = default(int?), string type = default(string), string message = default(string)) + { + Code = code; + Type = type; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "code")] + public int? Code { get; set; } + + /// + /// + [JsonProperty(PropertyName = "type")] + public string Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Category.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Category.cs new file mode 100644 index 0000000000..afce154a08 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Category.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Category + { + /// + /// Initializes a new instance of the Category class. + /// + public Category() { } + + /// + /// Initializes a new instance of the Category class. + /// + public Category(long? id = default(long?), string name = default(string)) + { + Id = id; + Name = name; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/LoginUserHeaders.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/LoginUserHeaders.cs new file mode 100644 index 0000000000..adb1cbec27 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/LoginUserHeaders.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + /// + /// Defines headers for loginUser operation. + /// + public partial class LoginUserHeaders + { + /// + /// Initializes a new instance of the LoginUserHeaders class. + /// + public LoginUserHeaders() { } + + /// + /// Initializes a new instance of the LoginUserHeaders class. + /// + public LoginUserHeaders(int? xRateLimit = default(int?), DateTime? xExpiresAfter = default(DateTime?)) + { + XRateLimit = xRateLimit; + XExpiresAfter = xExpiresAfter; + } + + /// + /// Gets or sets calls per hour allowed by the user + /// + [JsonProperty(PropertyName = "X-Rate-Limit")] + public int? XRateLimit { get; set; } + + /// + /// Gets or sets date in UTC when toekn expires + /// + [JsonProperty(PropertyName = "X-Expires-After")] + public DateTime? XExpiresAfter { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Order.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Order.cs new file mode 100644 index 0000000000..301590aa5c --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Order.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Order + { + /// + /// Initializes a new instance of the Order class. + /// + public Order() { } + + /// + /// Initializes a new instance of the Order class. + /// + public Order(long? id = default(long?), long? petId = default(long?), int? quantity = default(int?), DateTime? shipDate = default(DateTime?), string status = default(string), bool? complete = default(bool?)) + { + Id = id; + PetId = petId; + Quantity = quantity; + ShipDate = shipDate; + Status = status; + Complete = complete; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "petId")] + public long? PetId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "quantity")] + public int? Quantity { get; set; } + + /// + /// + [JsonProperty(PropertyName = "shipDate")] + public DateTime? ShipDate { get; set; } + + /// + /// Gets or sets order Status. Possible values include: 'placed', + /// 'approved', 'delivered' + /// + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "complete")] + public bool? Complete { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Pet.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Pet.cs new file mode 100644 index 0000000000..006deb06f4 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Pet.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Pet + { + /// + /// Initializes a new instance of the Pet class. + /// + public Pet() { } + + /// + /// Initializes a new instance of the Pet class. + /// + public Pet(string name, IList photoUrls, long? id = default(long?), Category category = default(Category), IList tags = default(IList), byte[] sByteProperty = default(byte[]), DateTime? birthday = default(DateTime?), IDictionary dictionary = default(IDictionary), string status = default(string)) + { + Id = id; + Category = category; + Name = name; + PhotoUrls = photoUrls; + Tags = tags; + SByteProperty = sByteProperty; + Birthday = birthday; + Dictionary = dictionary; + Status = status; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "category")] + public Category Category { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "photoUrls")] + public IList PhotoUrls { get; set; } + + /// + /// + [JsonProperty(PropertyName = "tags")] + public IList Tags { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sByte")] + public byte[] SByteProperty { get; set; } + + /// + /// + [JsonProperty(PropertyName = "birthday")] + public DateTime? Birthday { get; set; } + + /// + /// + [JsonProperty(PropertyName = "dictionary")] + public IDictionary Dictionary { get; set; } + + /// + /// Gets or sets pet status in the store. Possible values include: + /// 'available', 'pending', 'sold' + /// + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + /// + /// Validate the object. Throws ValidationException if validation fails. + /// + public virtual void Validate() + { + if (Name == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "Name"); + } + if (PhotoUrls == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); + } + } + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Tag.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Tag.cs new file mode 100644 index 0000000000..d9e9a413c3 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/Tag.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Tag + { + /// + /// Initializes a new instance of the Tag class. + /// + public Tag() { } + + /// + /// Initializes a new instance of the Tag class. + /// + public Tag(long? id = default(long?), string name = default(string)) + { + Id = id; + Name = name; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/User.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/User.cs new file mode 100644 index 0000000000..215ab2c2f6 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/Models/User.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class User + { + /// + /// Initializes a new instance of the User class. + /// + public User() { } + + /// + /// Initializes a new instance of the User class. + /// + public User(long? id = default(long?), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int? userStatus = default(int?)) + { + Id = id; + Username = username; + FirstName = firstName; + LastName = lastName; + Email = email; + Password = password; + Phone = phone; + UserStatus = userStatus; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "username")] + public string Username { get; set; } + + /// + /// + [JsonProperty(PropertyName = "firstName")] + public string FirstName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "lastName")] + public string LastName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "email")] + public string Email { get; set; } + + /// + /// + [JsonProperty(PropertyName = "password")] + public string Password { get; set; } + + /// + /// + [JsonProperty(PropertyName = "phone")] + public string Phone { get; set; } + + /// + /// Gets or sets user Status + /// + [JsonProperty(PropertyName = "userStatus")] + public int? UserStatus { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2.cs new file mode 100644 index 0000000000..2d744c04bc --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2.cs @@ -0,0 +1,2331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// This is a sample server Petstore server. You can find out more about + /// Swagger at <a + /// href="http://swagger.io">http://swagger.io</a> or on + /// irc.freenode.net, #swagger. For this sample, you can use the api key + /// "special-key" to test the authorization filters + /// + public partial class SwaggerPetstoreV2 : ServiceClient, ISwaggerPetstoreV2 + { + /// + /// The base URI of the service. + /// + public Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.BaseUri = new Uri("http://petstore.swagger.io/v2"); + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + /// + /// Add a new pet to the store + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> AddPetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + if (body != null) + { + body.Validate(); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 405 && (int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Update an existing pet + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdatePetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + if (body != null) + { + body.Validate(); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdatePet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 405) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> FindPetsByStatusWithHttpMessagesAsync(IList status, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (status == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "status"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("status", status); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "FindPetsByStatus", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByStatus").ToString(); + List _queryParameters = new List(); + if (status != null) + { + _queryParameters.Add(string.Format("status={0}", Uri.EscapeDataString(string.Join(",", status)))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// Tags to filter by + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> FindPetsByTagsWithHttpMessagesAsync(IList tags, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (tags == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "tags"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("tags", tags); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "FindPetsByTags", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByTags").ToString(); + List _queryParameters = new List(); + if (tags != null) + { + _queryParameters.Add(string.Format("tags={0}", Uri.EscapeDataString(string.Join(",", tags)))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// Id of pet to return + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("petId", petId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetPetById", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (fileContent == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "fileContent"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("petId", petId); + tracingParameters.Add("fileContent", fileContent); + tracingParameters.Add("fileName", fileName); + tracingParameters.Add("status", status); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdatePetWithForm", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); + if (fileContent != null) + { + StreamContent _fileContent = new StreamContent(fileContent); + _fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream; + if (_fileContentAsFileStream != null) + { + ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); + _contentDispositionHeaderValue.Name = "fileContent"; + _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name; + _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue; + } + _multiPartContent.Add(_fileContent, "fileContent"); + } + if (fileName != null) + { + StringContent _fileName = new StringContent(fileName, Encoding.UTF8); + _multiPartContent.Add(_fileName, "fileName"); + } + if (status != null) + { + StringContent _status = new StringContent(status, Encoding.UTF8); + _multiPartContent.Add(_status, "status"); + } + _httpRequest.Content = _multiPartContent; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 405) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Deletes a pet + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("apiKey", apiKey); + tracingParameters.Add("petId", petId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeletePet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (apiKey != null) + { + if (_httpRequest.Headers.Contains("api_key")) + { + _httpRequest.Headers.Remove("api_key"); + } + _httpRequest.Headers.TryAddWithoutValidation("api_key", apiKey); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetInventoryWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInventory", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/inventory").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Place an order for a pet + /// + /// + /// order placed for purchasing the pet + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PlaceOrder", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// Id of pet that needs to be fetched + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (orderId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "orderId"); + } + if (orderId != null) + { + if (orderId.Length > 5) + { + throw new ValidationException(ValidationRules.MaxLength, "orderId", 5); + } + if (orderId.Length < 1) + { + throw new ValidationException(ValidationRules.MinLength, "orderId", 1); + } + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("orderId", orderId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetOrderById", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString(); + _url = _url.Replace("{orderId}", Uri.EscapeDataString(orderId)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// Id of the order that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (orderId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "orderId"); + } + if (orderId != null) + { + if (orderId.Length < 1) + { + throw new ValidationException(ValidationRules.MinLength, "orderId", 1); + } + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("orderId", orderId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeleteOrder", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString(); + _url = _url.Replace("{orderId}", Uri.EscapeDataString(orderId)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUserWithHttpMessagesAsync(User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUsersWithArrayInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithArrayInput", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithArray").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUsersWithListInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithListInput", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithList").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Logs user into the system + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + if (password == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "password"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("password", password); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "LoginUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/login").ToString(); + List _queryParameters = new List(); + if (username != null) + { + _queryParameters.Add(string.Format("username={0}", Uri.EscapeDataString(username))); + } + if (password != null) + { + _queryParameters.Add(string.Format("password={0}", Uri.EscapeDataString(password))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + try + { + _result.Headers = _httpResponse.GetHeadersAsJson().ToObject(JsonSerializer.Create(this.DeserializationSettings)); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Logs out current logged in user session + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task LogoutUserWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "LogoutUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/logout").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get user by user name + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUserByNameWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUserByName", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdateUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeleteUserWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeleteUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2Extensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2Extensions.cs new file mode 100644 index 0000000000..7632b1ccaf --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2AllSync/SwaggerPetstoreV2Extensions.cs @@ -0,0 +1,1033 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2AllSync +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Extension methods for SwaggerPetstoreV2. + /// + public static partial class SwaggerPetstoreV2Extensions + { + /// + /// Add a new pet to the store + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Add a new pet to the store + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The cancellation token. + /// + public static async Task AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Add a new pet to the store + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary> customHeaders = null) + { + return operations.AddPetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Update an existing pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Update an existing pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The cancellation token. + /// + public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Update an existing pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary> customHeaders = null) + { + return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// The operations group for this extension method. + /// + /// + /// Status values that need to be considered for filter + /// + public static IList FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList status) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// The operations group for this extension method. + /// + /// + /// Status values that need to be considered for filter + /// + /// + /// The cancellation token. + /// + public static async Task> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList status, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// The operations group for this extension method. + /// + /// + /// Status values that need to be considered for filter + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, IList status, Dictionary> customHeaders = null) + { + return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// The operations group for this extension method. + /// + /// + /// Tags to filter by + /// + public static IList FindPetsByTags(this ISwaggerPetstoreV2 operations, IList tags) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// The operations group for this extension method. + /// + /// + /// Tags to filter by + /// + /// + /// The cancellation token. + /// + public static async Task> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList tags, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// The operations group for this extension method. + /// + /// + /// Tags to filter by + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, IList tags, Dictionary> customHeaders = null) + { + return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet to return + /// + public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet to return + /// + /// + /// The cancellation token. + /// + public static async Task GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet to return + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Dictionary> customHeaders = null) + { + return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string)) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// The cancellation token. + /// + public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary> customHeaders = null) + { + return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Deletes a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet id to delete + /// + /// + /// + public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "") + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Deletes a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", Dictionary> customHeaders = null) + { + return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The operations group for this extension method. + /// + public static IDictionary GetInventory(this ISwaggerPetstoreV2 operations) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The operations group for this extension method. + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary> customHeaders = null) + { + return operations.GetInventoryWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Place an order for a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// order placed for purchasing the pet + /// + public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Place an order for a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// order placed for purchasing the pet + /// + /// + /// The cancellation token. + /// + public static async Task PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Place an order for a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// order placed for purchasing the pet + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, Dictionary> customHeaders = null) + { + return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be fetched + /// + public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be fetched + /// + /// + /// The cancellation token. + /// + public static async Task GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be fetched + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary> customHeaders = null) + { + return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// The operations group for this extension method. + /// + /// + /// Id of the order that needs to be deleted + /// + public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// The operations group for this extension method. + /// + /// + /// Id of the order that needs to be deleted + /// + /// + /// The cancellation token. + /// + public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// The operations group for this extension method. + /// + /// + /// Id of the order that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary> customHeaders = null) + { + return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// Created user object + /// + public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// Created user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// Created user object + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, Dictionary> customHeaders = null) + { + return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList body) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList body, Dictionary> customHeaders = null) + { + return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList body) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList body, Dictionary> customHeaders = null) + { + return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Logs user into the system + /// + /// + /// The operations group for this extension method. + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Logs user into the system + /// + /// + /// The operations group for this extension method. + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// The cancellation token. + /// + public static async Task LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Logs user into the system + /// + /// + /// The operations group for this extension method. + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, Dictionary> customHeaders = null) + { + return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Logs out current logged in user session + /// + /// + /// The operations group for this extension method. + /// + public static void LogoutUser(this ISwaggerPetstoreV2 operations) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Logs out current logged in user session + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Logs out current logged in user session + /// + /// + /// The operations group for this extension method. + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary> customHeaders = null) + { + return operations.LogoutUserWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Get user by user name + /// + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) + { + return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get user by user name + /// + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// The cancellation token. + /// + public static async Task GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get user by user name + /// + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary> customHeaders = null) + { + return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// The cancellation token. + /// + public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, Dictionary> customHeaders = null) + { + return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be deleted + /// + public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) + { + Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be deleted + /// + /// + /// The cancellation token. + /// + public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + public static HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary> customHeaders = null) + { + return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/ISwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/ISwaggerPetstoreV2.cs new file mode 100644 index 0000000000..2e7c79b71f --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/ISwaggerPetstoreV2.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Models; + + /// + /// This is a sample server Petstore server. You can find out more about + /// Swagger at <a + /// href="http://swagger.io">http://swagger.io</a> or on + /// irc.freenode.net, #swagger. For this sample, you can use the api key + /// "special-key" to test the authorization filters + /// + public partial interface ISwaggerPetstoreV2 : IDisposable + { + /// + /// The base URI of the service. + /// + Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + + /// + /// Add a new pet to the store + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> AddPetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Update an existing pet + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdatePetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> FindPetsByStatusWithHttpMessagesAsync(IList status, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use + /// tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> FindPetsByTagsWithHttpMessagesAsync(IList tags, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// Id of pet to return + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Updates a pet in the store with form data + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Deletes a pet + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetInventoryWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Place an order for a pet + /// + /// + /// order placed for purchasing the pet + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. + /// Other values will generated exceptions + /// + /// Id of pet that needs to be fetched + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything + /// above 1000 or nonintegers will generate API errors + /// + /// Id of the order that needs to be deleted + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUserWithHttpMessagesAsync(User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUsersWithArrayInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task CreateUsersWithListInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Logs user into the system + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Logs out current logged in user session + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task LogoutUserWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Get user by user name + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUserByNameWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task DeleteUserWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/ApiResponse.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/ApiResponse.cs new file mode 100644 index 0000000000..94f2d00e08 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/ApiResponse.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class ApiResponse + { + /// + /// Initializes a new instance of the ApiResponse class. + /// + public ApiResponse() { } + + /// + /// Initializes a new instance of the ApiResponse class. + /// + public ApiResponse(int? code = default(int?), string type = default(string), string message = default(string)) + { + Code = code; + Type = type; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "code")] + public int? Code { get; set; } + + /// + /// + [JsonProperty(PropertyName = "type")] + public string Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Category.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Category.cs new file mode 100644 index 0000000000..f284e6abd4 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Category.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Category + { + /// + /// Initializes a new instance of the Category class. + /// + public Category() { } + + /// + /// Initializes a new instance of the Category class. + /// + public Category(long? id = default(long?), string name = default(string)) + { + Id = id; + Name = name; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/LoginUserHeaders.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/LoginUserHeaders.cs new file mode 100644 index 0000000000..f39e029d64 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/LoginUserHeaders.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + /// + /// Defines headers for loginUser operation. + /// + public partial class LoginUserHeaders + { + /// + /// Initializes a new instance of the LoginUserHeaders class. + /// + public LoginUserHeaders() { } + + /// + /// Initializes a new instance of the LoginUserHeaders class. + /// + public LoginUserHeaders(int? xRateLimit = default(int?), DateTime? xExpiresAfter = default(DateTime?)) + { + XRateLimit = xRateLimit; + XExpiresAfter = xExpiresAfter; + } + + /// + /// Gets or sets calls per hour allowed by the user + /// + [JsonProperty(PropertyName = "X-Rate-Limit")] + public int? XRateLimit { get; set; } + + /// + /// Gets or sets date in UTC when toekn expires + /// + [JsonProperty(PropertyName = "X-Expires-After")] + public DateTime? XExpiresAfter { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Order.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Order.cs new file mode 100644 index 0000000000..417f442a64 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Order.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Order + { + /// + /// Initializes a new instance of the Order class. + /// + public Order() { } + + /// + /// Initializes a new instance of the Order class. + /// + public Order(long? id = default(long?), long? petId = default(long?), int? quantity = default(int?), DateTime? shipDate = default(DateTime?), string status = default(string), bool? complete = default(bool?)) + { + Id = id; + PetId = petId; + Quantity = quantity; + ShipDate = shipDate; + Status = status; + Complete = complete; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "petId")] + public long? PetId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "quantity")] + public int? Quantity { get; set; } + + /// + /// + [JsonProperty(PropertyName = "shipDate")] + public DateTime? ShipDate { get; set; } + + /// + /// Gets or sets order Status. Possible values include: 'placed', + /// 'approved', 'delivered' + /// + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "complete")] + public bool? Complete { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Pet.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Pet.cs new file mode 100644 index 0000000000..b49d6ed7ed --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Pet.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Pet + { + /// + /// Initializes a new instance of the Pet class. + /// + public Pet() { } + + /// + /// Initializes a new instance of the Pet class. + /// + public Pet(string name, IList photoUrls, long? id = default(long?), Category category = default(Category), IList tags = default(IList), byte[] sByteProperty = default(byte[]), DateTime? birthday = default(DateTime?), IDictionary dictionary = default(IDictionary), string status = default(string)) + { + Id = id; + Category = category; + Name = name; + PhotoUrls = photoUrls; + Tags = tags; + SByteProperty = sByteProperty; + Birthday = birthday; + Dictionary = dictionary; + Status = status; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "category")] + public Category Category { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "photoUrls")] + public IList PhotoUrls { get; set; } + + /// + /// + [JsonProperty(PropertyName = "tags")] + public IList Tags { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sByte")] + public byte[] SByteProperty { get; set; } + + /// + /// + [JsonProperty(PropertyName = "birthday")] + public DateTime? Birthday { get; set; } + + /// + /// + [JsonProperty(PropertyName = "dictionary")] + public IDictionary Dictionary { get; set; } + + /// + /// Gets or sets pet status in the store. Possible values include: + /// 'available', 'pending', 'sold' + /// + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + /// + /// Validate the object. Throws ValidationException if validation fails. + /// + public virtual void Validate() + { + if (Name == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "Name"); + } + if (PhotoUrls == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); + } + } + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Tag.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Tag.cs new file mode 100644 index 0000000000..1d662dfcb8 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/Tag.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Tag + { + /// + /// Initializes a new instance of the Tag class. + /// + public Tag() { } + + /// + /// Initializes a new instance of the Tag class. + /// + public Tag(long? id = default(long?), string name = default(string)) + { + Id = id; + Name = name; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/User.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/User.cs new file mode 100644 index 0000000000..293823aaf3 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/Models/User.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class User + { + /// + /// Initializes a new instance of the User class. + /// + public User() { } + + /// + /// Initializes a new instance of the User class. + /// + public User(long? id = default(long?), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int? userStatus = default(int?)) + { + Id = id; + Username = username; + FirstName = firstName; + LastName = lastName; + Email = email; + Password = password; + Phone = phone; + UserStatus = userStatus; + } + + /// + /// + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "username")] + public string Username { get; set; } + + /// + /// + [JsonProperty(PropertyName = "firstName")] + public string FirstName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "lastName")] + public string LastName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "email")] + public string Email { get; set; } + + /// + /// + [JsonProperty(PropertyName = "password")] + public string Password { get; set; } + + /// + /// + [JsonProperty(PropertyName = "phone")] + public string Phone { get; set; } + + /// + /// Gets or sets user Status + /// + [JsonProperty(PropertyName = "userStatus")] + public int? UserStatus { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2.cs new file mode 100644 index 0000000000..4a0b55bf23 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2.cs @@ -0,0 +1,2331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// This is a sample server Petstore server. You can find out more about + /// Swagger at <a + /// href="http://swagger.io">http://swagger.io</a> or on + /// irc.freenode.net, #swagger. For this sample, you can use the api key + /// "special-key" to test the authorization filters + /// + public partial class SwaggerPetstoreV2 : ServiceClient, ISwaggerPetstoreV2 + { + /// + /// The base URI of the service. + /// + public Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the SwaggerPetstoreV2 class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public SwaggerPetstoreV2(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this.BaseUri = baseUri; + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.BaseUri = new Uri("http://petstore.swagger.io/v2"); + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + /// + /// Add a new pet to the store + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> AddPetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + if (body != null) + { + body.Validate(); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 405 && (int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Update an existing pet + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdatePetWithHttpMessagesAsync(Pet body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + if (body != null) + { + body.Validate(); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdatePet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 405) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> FindPetsByStatusWithHttpMessagesAsync(IList status, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (status == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "status"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("status", status); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "FindPetsByStatus", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByStatus").ToString(); + List _queryParameters = new List(); + if (status != null) + { + _queryParameters.Add(string.Format("status={0}", Uri.EscapeDataString(string.Join(",", status)))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// Tags to filter by + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> FindPetsByTagsWithHttpMessagesAsync(IList tags, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (tags == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "tags"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("tags", tags); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "FindPetsByTags", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/findByTags").ToString(); + List _queryParameters = new List(); + if (tags != null) + { + _queryParameters.Add(string.Format("tags={0}", Uri.EscapeDataString(string.Join(",", tags)))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// Id of pet to return + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("petId", petId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetPetById", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (fileContent == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "fileContent"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("petId", petId); + tracingParameters.Add("fileContent", fileContent); + tracingParameters.Add("fileName", fileName); + tracingParameters.Add("status", status); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdatePetWithForm", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); + if (fileContent != null) + { + StreamContent _fileContent = new StreamContent(fileContent); + _fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream; + if (_fileContentAsFileStream != null) + { + ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); + _contentDispositionHeaderValue.Name = "fileContent"; + _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name; + _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue; + } + _multiPartContent.Add(_fileContent, "fileContent"); + } + if (fileName != null) + { + StringContent _fileName = new StringContent(fileName, Encoding.UTF8); + _multiPartContent.Add(_fileName, "fileName"); + } + if (status != null) + { + StringContent _status = new StringContent(status, Encoding.UTF8); + _multiPartContent.Add(_status, "status"); + } + _httpRequest.Content = _multiPartContent; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 405) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Deletes a pet + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("apiKey", apiKey); + tracingParameters.Add("petId", petId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeletePet", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pet/{petId}").ToString(); + _url = _url.Replace("{petId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(petId, this.SerializationSettings).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (apiKey != null) + { + if (_httpRequest.Headers.Contains("api_key")) + { + _httpRequest.Headers.Remove("api_key"); + } + _httpRequest.Headers.TryAddWithoutValidation("api_key", apiKey); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetInventoryWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInventory", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/inventory").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Place an order for a pet + /// + /// + /// order placed for purchasing the pet + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PlaceOrder", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// Id of pet that needs to be fetched + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (orderId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "orderId"); + } + if (orderId != null) + { + if (orderId.Length > 5) + { + throw new ValidationException(ValidationRules.MaxLength, "orderId", 5); + } + if (orderId.Length < 1) + { + throw new ValidationException(ValidationRules.MinLength, "orderId", 1); + } + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("orderId", orderId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetOrderById", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString(); + _url = _url.Replace("{orderId}", Uri.EscapeDataString(orderId)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// Id of the order that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (orderId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "orderId"); + } + if (orderId != null) + { + if (orderId.Length < 1) + { + throw new ValidationException(ValidationRules.MinLength, "orderId", 1); + } + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("orderId", orderId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeleteOrder", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "store/order/{orderId}").ToString(); + _url = _url.Replace("{orderId}", Uri.EscapeDataString(orderId)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUserWithHttpMessagesAsync(User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUsersWithArrayInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithArrayInput", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithArray").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Creates list of users with given input array + /// + /// + /// List of user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task CreateUsersWithListInputWithHttpMessagesAsync(IList body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "CreateUsersWithListInput", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/createWithList").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Logs user into the system + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + if (password == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "password"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("password", password); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "LoginUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/login").ToString(); + List _queryParameters = new List(); + if (username != null) + { + _queryParameters.Add(string.Format("username={0}", Uri.EscapeDataString(username))); + } + if (password != null) + { + _queryParameters.Add(string.Format("password={0}", Uri.EscapeDataString(password))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + try + { + _result.Headers = _httpResponse.GetHeadersAsJson().ToObject(JsonSerializer.Create(this.DeserializationSettings)); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Logs out current logged in user session + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task LogoutUserWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "LogoutUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/logout").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if (!_httpResponse.IsSuccessStatusCode) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get user by user name + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUserByNameWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUserByName", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + if (body == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "body"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UpdateUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeleteUserWithHttpMessagesAsync(string username, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (username == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "username"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("username", username); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeleteUser", tracingParameters); + } + // Construct URL + var _baseUrl = this.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "user/{username}").ToString(); + _url = _url.Replace("{username}", Uri.EscapeDataString(username)); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 400 && (int)_statusCode != 404) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2Extensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2Extensions.cs new file mode 100644 index 0000000000..6f86040771 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2NoSync/SwaggerPetstoreV2Extensions.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.PetstoreV2NoSync +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Extension methods for SwaggerPetstoreV2. + /// + public static partial class SwaggerPetstoreV2Extensions + { + /// + /// Add a new pet to the store + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The cancellation token. + /// + public static async Task AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Update an existing pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet object that needs to be added to the store + /// + /// + /// The cancellation token. + /// + public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// The operations group for this extension method. + /// + /// + /// Status values that need to be considered for filter + /// + /// + /// The cancellation token. + /// + public static async Task> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList status, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, + /// tag3 for testing. + /// + /// The operations group for this extension method. + /// + /// + /// Tags to filter by + /// + /// + /// The cancellation token. + /// + public static async Task> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList tags, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Find pet by Id + /// + /// Returns a single pet + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet to return + /// + /// + /// The cancellation token. + /// + public static async Task GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Updates a pet in the store with form data + /// + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be updated + /// + /// + /// File to upload. + /// + /// + /// Updated name of the pet + /// + /// + /// Updated status of the pet + /// + /// + /// The cancellation token. + /// + public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// Pet id to delete + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Place an order for a pet + /// + /// + /// The operations group for this extension method. + /// + /// + /// order placed for purchasing the pet + /// + /// + /// The cancellation token. + /// + public static async Task PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Find purchase order by Id + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other + /// values will generated exceptions + /// + /// The operations group for this extension method. + /// + /// + /// Id of pet that needs to be fetched + /// + /// + /// The cancellation token. + /// + public static async Task GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Delete purchase order by Id + /// + /// For valid response try integer IDs with value < 1000. Anything above + /// 1000 or nonintegers will generate API errors + /// + /// The operations group for this extension method. + /// + /// + /// Id of the order that needs to be deleted + /// + /// + /// The cancellation token. + /// + public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// Created user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// + /// The operations group for this extension method. + /// + /// + /// List of user object + /// + /// + /// The cancellation token. + /// + public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Logs user into the system + /// + /// + /// The operations group for this extension method. + /// + /// + /// The user name for login + /// + /// + /// The password for login in clear text + /// + /// + /// The cancellation token. + /// + public static async Task LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Logs out current logged in user session + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get user by user name + /// + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + /// + /// The cancellation token. + /// + public static async Task GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// name that need to be deleted + /// + /// + /// Updated user object + /// + /// + /// The cancellation token. + /// + public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// + /// The operations group for this extension method. + /// + /// + /// The name that needs to be deleted + /// + /// + /// The cancellation token. + /// + public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp/AutoRest.Generator.CSharp.csproj b/AutoRest/Generators/CSharp/CSharp/AutoRest.Generator.CSharp.csproj index 4885670c6b..544e2165a1 100644 --- a/AutoRest/Generators/CSharp/CSharp/AutoRest.Generator.CSharp.csproj +++ b/AutoRest/Generators/CSharp/CSharp/AutoRest.Generator.CSharp.csproj @@ -36,7 +36,7 @@ True Resources.resx - + diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs index 8655910279..5b3ba7981e 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs @@ -33,7 +33,8 @@ public CSharpCodeGenerator(Settings settings) : base(settings) /// Specifies mode for generating sync wrappers. /// [SettingsInfo("Specifies mode for generating sync wrappers.")] - public SyncWrapperGenerationMode SyncWrappers { get; set; } + [SettingsAlias("syncMethods")] + public SyncMethodsGenerationMode SyncMethods { get; set; } public override string Name { @@ -112,7 +113,7 @@ public override async Task Generate(ServiceClient serviceClient) { var extensionsTemplate = new ExtensionsTemplate { - Model = new ExtensionsTemplateModel(serviceClient, null, SyncWrappers), + Model = new ExtensionsTemplateModel(serviceClient, null, SyncMethods), }; await Write(extensionsTemplate, serviceClient.Name + "Extensions.cs"); } @@ -137,7 +138,7 @@ public override async Task Generate(ServiceClient serviceClient) // Service client extensions var operationExtensionsTemplate = new ExtensionsTemplate { - Model = new ExtensionsTemplateModel(serviceClient, group, SyncWrappers), + Model = new ExtensionsTemplateModel(serviceClient, group, SyncMethods), }; await Write(operationExtensionsTemplate, group + "Extensions.cs"); diff --git a/AutoRest/Generators/CSharp/CSharp/SyncWrapperGenerationMode.cs b/AutoRest/Generators/CSharp/CSharp/SyncMethodsGenerationMode.cs similarity index 89% rename from AutoRest/Generators/CSharp/CSharp/SyncWrapperGenerationMode.cs rename to AutoRest/Generators/CSharp/CSharp/SyncMethodsGenerationMode.cs index 72e4088bb8..f8e3f62082 100644 --- a/AutoRest/Generators/CSharp/CSharp/SyncWrapperGenerationMode.cs +++ b/AutoRest/Generators/CSharp/CSharp/SyncMethodsGenerationMode.cs @@ -7,7 +7,7 @@ namespace Microsoft.Rest.Generator.CSharp /// /// Defines supported modes for sync wrapper generation /// - public enum SyncWrapperGenerationMode + public enum SyncMethodsGenerationMode { Essential, All, diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/ExtensionsTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/ExtensionsTemplateModel.cs index 287311fe27..596d49f15a 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/ExtensionsTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/ExtensionsTemplateModel.cs @@ -10,7 +10,7 @@ namespace Microsoft.Rest.Generator.CSharp { public class ExtensionsTemplateModel : ServiceClient { - public ExtensionsTemplateModel(ServiceClient serviceClient, string operationName, SyncWrapperGenerationMode syncWrappers) + public ExtensionsTemplateModel(ServiceClient serviceClient, string operationName, SyncMethodsGenerationMode syncWrappers) { this.LoadFrom(serviceClient); MethodTemplateModels = new List(); diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodGroupTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodGroupTemplateModel.cs index 9c4c3ebcc3..6a70892f72 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodGroupTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodGroupTemplateModel.cs @@ -19,7 +19,7 @@ public MethodGroupTemplateModel(ServiceClient serviceClient, string methodGroupN MethodGroupName = methodGroupName; MethodGroupType = methodGroupName; Methods.Where(m => m.Group == MethodGroupName) - .ForEach(m => MethodTemplateModels.Add(new MethodTemplateModel(m, serviceClient, SyncWrapperGenerationMode.None))); + .ForEach(m => MethodTemplateModels.Add(new MethodTemplateModel(m, serviceClient, SyncMethodsGenerationMode.None))); } public List MethodTemplateModels { get; private set; } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index a5bfcd56b3..0ba0a8d759 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -14,10 +14,10 @@ namespace Microsoft.Rest.Generator.CSharp { public class MethodTemplateModel : Method { - public MethodTemplateModel(Method source, ServiceClient serviceClient, SyncWrapperGenerationMode syncWrappers) + public MethodTemplateModel(Method source, ServiceClient serviceClient, SyncMethodsGenerationMode syncWrappers) { this.LoadFrom(source); - SyncWrappers = syncWrappers; + SyncMethods = syncWrappers; ParameterTemplateModels = new List(); LogicalParameterTemplateModels = new List(); source.Parameters.ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p))); @@ -31,7 +31,7 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient, SyncWrapp public bool IsCustomBaseUri { get; private set; } - public SyncWrapperGenerationMode SyncWrappers { get; private set; } + public SyncMethodsGenerationMode SyncMethods { get; private set; } public ServiceClient ServiceClient { get; set; } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/ServiceClientTemplateModel.cs index b38f1db38b..9bd149a4da 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/ServiceClientTemplateModel.cs @@ -16,7 +16,7 @@ public ServiceClientTemplateModel(ServiceClient serviceClient, bool internalCons this.LoadFrom(serviceClient); MethodTemplateModels = new List(); Methods.Where(m => m.Group == null) - .ForEach(m => MethodTemplateModels.Add(new MethodTemplateModel(m, serviceClient, SyncWrapperGenerationMode.None))); + .ForEach(m => MethodTemplateModels.Add(new MethodTemplateModel(m, serviceClient, SyncMethodsGenerationMode.None))); ConstructorVisibility = internalConstructors ? "internal" : "public"; this.IsCustomBaseUri = serviceClient.Extensions.ContainsKey(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension); } diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/ExtensionMethodTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/ExtensionMethodTemplate.cshtml index d2531c48e3..3a964744a4 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/ExtensionMethodTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/ExtensionMethodTemplate.cshtml @@ -6,10 +6,10 @@ @using Microsoft.Rest.Generator.Utilities @inherits Microsoft.Rest.Generator.Template @{ -if (Model.SyncWrappers == SyncWrapperGenerationMode.All || Model.SyncWrappers == SyncWrapperGenerationMode.Essential) -{ - if (!String.IsNullOrEmpty(Model.Description) || !String.IsNullOrEmpty(Model.Summary)) + if (Model.SyncMethods == SyncMethodsGenerationMode.All || Model.SyncMethods == SyncMethodsGenerationMode.Essential) { + if (!String.IsNullOrEmpty(Model.Description) || !String.IsNullOrEmpty(Model.Summary)) + { @:/// @:@WrapComment("/// ", String.IsNullOrEmpty(Model.Summary) ? Model.Description.EscapeXmlComment() : Model.Summary.EscapeXmlComment()) @:/// @@ -98,8 +98,8 @@ foreach (var parameter in Model.LocalParameters) } @:} -if (Model.SyncWrappers == SyncWrapperGenerationMode.All) -{ + if (Model.SyncMethods == SyncMethodsGenerationMode.All) + { @EmptyLine if (!String.IsNullOrEmpty(Model.Description) || !String.IsNullOrEmpty(Model.Summary)) { diff --git a/Tools/gulp/gulp-regenerate-expected.js b/Tools/gulp/gulp-regenerate-expected.js index 077960363b..8f2bece72e 100644 --- a/Tools/gulp/gulp-regenerate-expected.js +++ b/Tools/gulp/gulp-regenerate-expected.js @@ -63,12 +63,17 @@ function gulpRegenerateExpected(options, done) { '-PayloadFlatteningThreshold', opts.flatteningThreshold, '-OutputDirectory', path.join(opts.outputDir, key), '-Input', (!!opts.inputBaseDir ? path.join(opts.inputBaseDir, mappingBaseDir) : mappingBaseDir), - '-Header', (!!opts.header ? opts.header : 'MICROSOFT_MIT_NO_VERSION') + '-Header', (!!opts.header ? opts.header : 'MICROSOFT_MIT_NO_VERSION') ]; if (opts.addCredentials) { args.push('-AddCredentials'); } + + if (opts.syncMethods) { + args.push('-SyncMethods'); + args.push(opts.syncMethods); + } if (!!opts.nsPrefix) { args.push('-Namespace'); diff --git a/gulpfile.js b/gulpfile.js index 85ef29e5d1..22cc61f881 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -296,7 +296,7 @@ gulp.task('regenerate:expected:java', function(cb){ }, cb); }) -gulp.task('regenerate:expected:csazure', ['regenerate:expected:csazurecomposite'], function (cb) { +gulp.task('regenerate:expected:csazure', ['regenerate:expected:csazurecomposite','regenerate:expected:csazureallsync', 'regenerate:expected:csazurenosync'], function (cb) { mappings = mergeOptions({ 'AcceptanceTests/AzureBodyDuration': '../../../TestServer/swagger/body-duration.json' }, defaultAzureMappings); @@ -312,7 +312,7 @@ gulp.task('regenerate:expected:csazure', ['regenerate:expected:csazurecomposite' }, cb); }); -gulp.task('regenerate:expected:cs', ['regenerate:expected:cswithcreds', 'regenerate:expected:cscomposite'], function (cb) { +gulp.task('regenerate:expected:cs', ['regenerate:expected:cswithcreds', 'regenerate:expected:cscomposite', 'regenerate:expected:csallsync', 'regenerate:expected:csnosync'], function (cb) { mappings = mergeOptions({ 'Mirror.RecursiveTypes': 'Swagger/swagger-mirror-recursive-type.json', 'Mirror.Primitives': 'Swagger/swagger-mirror-primitives.json', @@ -351,6 +351,78 @@ gulp.task('regenerate:expected:cswithcreds', function(cb){ }, cb); }); +gulp.task('regenerate:expected:csallsync', function(cb){ + mappings = mergeOptions( + { + 'PetstoreV2AllSync': 'Swagger/swagger.2.0.example.v2.json', + }); + + regenExpected({ + 'outputBaseDir': 'AutoRest/Generators/CSharp/CSharp.Tests', + 'inputBaseDir': 'AutoRest/Generators/CSharp/CSharp.Tests', + 'mappings': mappings, + 'outputDir': 'Expected', + 'codeGenerator': 'CSharp', + 'nsPrefix': 'Fixtures', + 'flatteningThreshold': '1', + 'syncMethods': 'all' + }, cb); +}); + +gulp.task('regenerate:expected:csnosync', function(cb){ + mappings = mergeOptions( + { + 'PetstoreV2NoSync': 'Swagger/swagger.2.0.example.v2.json', + }); + + regenExpected({ + 'outputBaseDir': 'AutoRest/Generators/CSharp/CSharp.Tests', + 'inputBaseDir': 'AutoRest/Generators/CSharp/CSharp.Tests', + 'mappings': mappings, + 'outputDir': 'Expected', + 'codeGenerator': 'CSharp', + 'nsPrefix': 'Fixtures', + 'flatteningThreshold': '1', + 'syncMethods': 'none' + }, cb); +}); + +gulp.task('regenerate:expected:csazureallsync', function(cb){ + mappings = mergeOptions( + { + 'AcceptanceTests/AzureBodyDurationAllSync': '../../../TestServer/swagger/body-duration.json' + }); + + regenExpected({ + 'outputBaseDir': 'AutoRest/Generators/CSharp/Azure.CSharp.Tests', + 'inputBaseDir': 'AutoRest/Generators/CSharp/Azure.CSharp.Tests', + 'mappings': mappings, + 'outputDir': 'Expected', + 'codeGenerator': 'Azure.CSharp', + 'nsPrefix': 'Fixtures', + 'flatteningThreshold': '1', + 'syncMethods': 'all' + }, cb); +}); + +gulp.task('regenerate:expected:csazurenosync', function(cb){ + mappings = mergeOptions( + { + 'AcceptanceTests/AzureBodyDurationNoSync': '../../../TestServer/swagger/body-duration.json' + }); + + regenExpected({ + 'outputBaseDir': 'AutoRest/Generators/CSharp/Azure.CSharp.Tests', + 'inputBaseDir': 'AutoRest/Generators/CSharp/Azure.CSharp.Tests', + 'mappings': mappings, + 'outputDir': 'Expected', + 'codeGenerator': 'Azure.CSharp', + 'nsPrefix': 'Fixtures', + 'flatteningThreshold': '1', + 'syncMethods': 'none' + }, cb); +}); + gulp.task('regenerate:expected:cscomposite', function (cb) { regenExpected({ 'outputBaseDir': 'AutoRest/Generators/CSharp/CSharp.Tests',