From 3090ae959089bf8608237cf5063cb53331e9658b Mon Sep 17 00:00:00 2001 From: filipe Date: Wed, 12 Jun 2024 20:56:05 +0100 Subject: [PATCH 1/8] improved apiclient.mustache to keep it dry, sharing a single exec with Action<> delegate. --- .../main/resources/csharp/ApiClient.mustache | 427 ++++++++---------- 1 file changed, 186 insertions(+), 241 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index ee908eb89942..2ba1fd000d91 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -14,9 +14,9 @@ using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -{{^netStandard}} +{{^net60OrLater}} using System.Web; -{{/netStandard}} +{{/net60OrLater}} using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -28,6 +28,7 @@ using Polly; {{#hasOAuthMethods}} using {{packageName}}.Client.Auth; {{/hasOAuthMethods}} +using {{packageName}}.{{modelPackage}}; namespace {{packageName}}.Client { @@ -68,10 +69,10 @@ namespace {{packageName}}.Client /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -127,7 +128,7 @@ namespace {{packageName}}.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -149,13 +150,13 @@ namespace {{packageName}}.Client public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +204,7 @@ namespace {{packageName}}.Client /// public ApiClient() { - _baseUrl = {{packageName}}.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +376,7 @@ namespace {{packageName}}.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,236 +430,180 @@ namespace {{packageName}}.Client return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + {{#hasOAuthMethods}} + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + {{/hasOAuthMethods}} + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - {{#hasOAuthMethods}} - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - {{/hasOAuthMethods}} - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } {{#supportsAsync}} - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - {{#hasOAuthMethods}} - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - {{/hasOAuthMethods}} - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - {{#supportsRetry}} - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - {{/supportsRetry}} - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - {{#supportsRetry}} - } - {{/supportsRetry}} - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + {{/supportsRetry}} + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -670,7 +615,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -685,7 +630,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -700,7 +645,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -715,7 +660,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -730,7 +675,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -745,7 +690,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -760,7 +705,7 @@ namespace {{packageName}}.Client /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); From d59a1e90f9a3db4f07b7652880b00df5b0f32599 Mon Sep 17 00:00:00 2001 From: filipe Date: Wed, 12 Jun 2024 21:06:14 +0100 Subject: [PATCH 2/8] updated samples and test --- .../CSharpClientDeepObjectTest.java | 2 +- .../src/Org.OpenAPITools/Client/ApiClient.cs | 370 +++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 370 +++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 412 ++++++++---------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 411 ++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 411 ++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 370 +++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 412 ++++++++---------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 412 ++++++++---------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 370 +++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 412 ++++++++---------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 412 ++++++++---------- 12 files changed, 1918 insertions(+), 2446 deletions(-) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java index 06ad440844f4..d17d17155088 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java @@ -67,6 +67,6 @@ public void deepObject() throws IOException { "inputOptions[a]", "inputOptions[b]", "inputOptions[c]"); String content = new String(Files.readAllBytes(Paths.get(outputPath + "/src/Org.OpenAPITools/Api/DefaultApi.cs")), StandardCharsets.UTF_8); int counter = StringUtils.countMatches(content,"inputOptions[a]"); - assertEquals(2, counter); + assertEquals(1, counter); } } diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index c569deebc531..e445c9a310e3 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -23,13 +23,13 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -70,10 +70,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -129,7 +129,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -151,13 +151,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -204,7 +204,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -376,7 +376,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -430,199 +430,159 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -634,7 +594,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -649,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -664,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -679,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -694,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -709,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -724,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index a5389ded4f2e..60876fb5da05 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,12 +22,14 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; +using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -68,10 +70,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -127,7 +129,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -149,13 +151,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -202,7 +204,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -374,7 +376,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -428,199 +430,159 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -632,7 +594,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -647,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -662,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -677,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -692,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -707,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -722,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs index 4482bbdbfbc8..3dcc1757d849 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,6 +22,7 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; +using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -29,6 +30,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -69,10 +71,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -128,7 +130,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -150,13 +152,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +205,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +377,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,227 +431,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -661,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -676,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -691,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -706,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -721,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -736,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -751,7 +699,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index b10e49166a65..4f76dc30cbf0 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -30,6 +30,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -70,10 +71,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -129,7 +130,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -151,13 +152,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -204,7 +205,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -376,7 +377,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -430,227 +431,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -662,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -677,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -692,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -707,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -722,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -737,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -752,7 +699,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index b10e49166a65..4f76dc30cbf0 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -30,6 +30,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -70,10 +71,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -129,7 +130,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -151,13 +152,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -204,7 +205,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -376,7 +377,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -430,227 +431,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -662,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -677,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -692,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -707,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -722,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -737,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -752,7 +699,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 6c224944b4c7..53ef5cff0179 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,13 +22,13 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -69,10 +69,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -128,7 +128,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -150,13 +150,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +203,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +375,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,199 +429,159 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -633,7 +593,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -648,7 +608,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -663,7 +623,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -678,7 +638,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -693,7 +653,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -708,7 +668,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -723,7 +683,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs index b10e49166a65..40bf6495253d 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,7 +22,6 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -30,6 +29,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -70,10 +70,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -129,7 +129,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -151,13 +151,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -204,7 +204,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -376,7 +376,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -430,227 +430,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -662,7 +608,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -677,7 +623,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -692,7 +638,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -707,7 +653,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -722,7 +668,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -737,7 +683,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -752,7 +698,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index b10e49166a65..40bf6495253d 100644 --- a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,7 +22,6 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -30,6 +29,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -70,10 +70,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -129,7 +129,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -151,13 +151,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -204,7 +204,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -376,7 +376,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -430,227 +430,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -662,7 +608,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -677,7 +623,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -692,7 +638,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -707,7 +653,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -722,7 +668,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -737,7 +683,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -752,7 +698,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs index 594bf890cb88..9e0df358aa91 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,13 +22,13 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -69,10 +69,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -128,7 +128,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -150,13 +150,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +203,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +375,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,199 +429,159 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -633,7 +593,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -648,7 +608,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -663,7 +623,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -678,7 +638,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -693,7 +653,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -708,7 +668,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -723,7 +683,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index 3c0762f55399..4f76dc30cbf0 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,6 +22,7 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; +using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -29,6 +30,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -69,10 +71,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -128,7 +130,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -150,13 +152,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +205,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +377,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,227 +431,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -661,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -676,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -691,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -706,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -721,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -736,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -751,7 +699,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 3c0762f55399..4f76dc30cbf0 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -22,6 +22,7 @@ using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; +using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using RestSharp; @@ -29,6 +30,7 @@ using RestSharpMethod = RestSharp.Method; using Polly; using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Client { @@ -69,10 +71,10 @@ public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfi /// A JSON string. public string Serialize(object obj) { - if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + if (obj != null && obj is AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema - return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + return ((AbstractOpenAPISchema)obj).ToJson(); } else { @@ -128,7 +130,7 @@ internal object Deserialize(RestResponse response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content, null, DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type @@ -150,13 +152,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + public string[] AcceptedContentTypes => ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + public ContentType ContentType { get; set; } = ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -203,7 +205,7 @@ public partial class ApiClient : ISynchronousClient, IAsynchronousClient /// public ApiClient() { - _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + _baseUrl = GlobalConfiguration.Instance.BasePath; } /// @@ -375,7 +377,7 @@ private RestRequest NewRequest( var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + request.AddFile(fileParam.Key, bytes, Path.GetFileName(fileStream.Name)); else request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } @@ -429,227 +431,173 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + clientOptions.Authenticator = new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - CookieContainer = cookies, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(request); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { - clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + RestResponse response = null; + Action action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; + action(); + return response; + }; + + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// @@ -661,7 +609,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); @@ -676,7 +624,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); @@ -691,7 +639,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); @@ -706,7 +654,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); @@ -721,7 +669,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); @@ -736,7 +684,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); @@ -751,7 +699,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea /// GlobalConfiguration has been done before calling this method. /// Token that enables callers to cancel the request. /// A Task containing ApiResponse - public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, CancellationToken cancellationToken = default) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); From 82715f174509b432896ee0fa06c8c1ba4caa6bb9 Mon Sep 17 00:00:00 2001 From: filipe Date: Thu, 13 Jun 2024 10:48:10 +0100 Subject: [PATCH 3/8] Removed async from ApiClient.mustache Updated samples --- .../src/main/resources/csharp/ApiClient.mustache | 2 +- .../csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 2ba1fd000d91..2f3dec3641fe 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -568,7 +568,7 @@ namespace {{packageName}}.Client } {{#supportsAsync}} - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index e445c9a310e3..df1d157283af 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -551,7 +551,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index 60876fb5da05..e1182b36af32 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -551,7 +551,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs index 3dcc1757d849..17a716e0350d 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs @@ -566,7 +566,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 4f76dc30cbf0..04aacc26771d 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -566,7 +566,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 4f76dc30cbf0..04aacc26771d 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -566,7 +566,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 53ef5cff0179..5f092d463d57 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -550,7 +550,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 40bf6495253d..d8ddf611e7c9 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -565,7 +565,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 40bf6495253d..d8ddf611e7c9 100644 --- a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -565,7 +565,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs index 9e0df358aa91..f5244b56e0ba 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -550,7 +550,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index 4f76dc30cbf0..04aacc26771d 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -566,7 +566,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 4f76dc30cbf0..04aacc26771d 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -566,7 +566,7 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea return ExecClient(getResponse, setOptions, request, options, configuration); } - private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) + private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { Action setOptions = (clientOptions) => { From f829f1f885ba972f3fd24d8e1985e7528dcdc950 Mon Sep 17 00:00:00 2001 From: filipe Date: Thu, 13 Jun 2024 11:07:18 +0100 Subject: [PATCH 4/8] Revert change to CSharpClientDeepObjectTest.java --- .../codegen/csharpnetcore/CSharpClientDeepObjectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java index d17d17155088..06ad440844f4 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientDeepObjectTest.java @@ -67,6 +67,6 @@ public void deepObject() throws IOException { "inputOptions[a]", "inputOptions[b]", "inputOptions[c]"); String content = new String(Files.readAllBytes(Paths.get(outputPath + "/src/Org.OpenAPITools/Api/DefaultApi.cs")), StandardCharsets.UTF_8); int counter = StringUtils.countMatches(content,"inputOptions[a]"); - assertEquals(1, counter); + assertEquals(2, counter); } } From 96ddbf02c8a48862f9360b3bfa33269f7b57060e Mon Sep 17 00:00:00 2001 From: filipe Date: Thu, 13 Jun 2024 11:55:47 +0100 Subject: [PATCH 5/8] Fix async await (it was not waiting creating a null exception) Updated samples --- .../main/resources/csharp/ApiClient.mustache | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 23 +++++++++++-------- 12 files changed, 168 insertions(+), 108 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 2f3dec3641fe..3f0108395f44 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -577,29 +577,34 @@ namespace {{packageName}}.Client Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { {{#supportsRetry}} if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { {{/supportsRetry}} - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); {{#supportsRetry}} } {{/supportsRetry}} }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index df1d157283af..e6b46a9a48f3 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -560,25 +560,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index e1182b36af32..1d4be5b18bcc 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -560,25 +560,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs index 17a716e0350d..07db6b746fe5 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs @@ -575,25 +575,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 04aacc26771d..814037ba91ea 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -575,25 +575,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 04aacc26771d..814037ba91ea 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -575,25 +575,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 5f092d463d57..27c64eb40330 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -559,25 +559,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs index d8ddf611e7c9..43cbd121dd96 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -574,25 +574,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index d8ddf611e7c9..43cbd121dd96 100644 --- a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -574,25 +574,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs index f5244b56e0ba..626fb567c69d 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -559,25 +559,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index 04aacc26771d..814037ba91ea 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -575,25 +575,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 04aacc26771d..814037ba91ea 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -575,25 +575,30 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea Func> getResponse = (client) => { - RestResponse response = null; - Action action = async () => + Func>> action = async () => { if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } } else { - response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } }; - action(); - return response; + return action().Result; }; return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); From 0352a4b07d93211edd6f7ec6b21b05ba0c02b09d Mon Sep 17 00:00:00 2001 From: filipe Date: Thu, 13 Jun 2024 12:02:51 +0100 Subject: [PATCH 6/8] Fix File IO namespace with using directive --- .../src/main/resources/csharp/ApiClient.mustache | 3 ++- .../csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- .../Petstore/src/Org.OpenAPITools/Client/ApiClient.cs | 3 ++- 12 files changed, 24 insertions(+), 12 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 3f0108395f44..5f3b0564cef9 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -22,6 +22,7 @@ using Newtonsoft.Json.Serialization; using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; {{#supportsRetry}} using Polly; {{/supportsRetry}} @@ -117,7 +118,7 @@ namespace {{packageName}}.Client if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index e6b46a9a48f3..8781ccda0500 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Model; @@ -118,7 +119,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index 1d4be5b18bcc..c275af5399d7 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Model; @@ -118,7 +119,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs index 07db6b746fe5..fad187913960 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -119,7 +120,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 814037ba91ea..682e7e433956 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -119,7 +120,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 814037ba91ea..682e7e433956 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -119,7 +120,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 27c64eb40330..554753e31a80 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -27,6 +27,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Model; @@ -117,7 +118,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 43cbd121dd96..5710aa120093 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -27,6 +27,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -118,7 +119,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 43cbd121dd96..5710aa120093 100644 --- a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -27,6 +27,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -118,7 +119,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs index 626fb567c69d..e0f33c43aef4 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -27,6 +27,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Model; @@ -117,7 +118,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index 814037ba91ea..682e7e433956 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -119,7 +120,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 814037ba91ea..682e7e433956 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -28,6 +28,7 @@ using RestSharp; using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; +using FileIO = System.IO.File; using Polly; using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; @@ -119,7 +120,7 @@ internal object Deserialize(RestResponse response, Type type) if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); - File.WriteAllBytes(fileName, bytes); + FileIO.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } From 33ad4f73438d84bcf27201673d022360410c4975 Mon Sep 17 00:00:00 2001 From: filipe Date: Fri, 14 Jun 2024 13:07:31 +0100 Subject: [PATCH 7/8] Improved comments on new methods Added new DRY method DeserializeRestResponseFromPolicy --- .../main/resources/csharp/ApiClient.mustache | 367 +++++++++--------- 1 file changed, 194 insertions(+), 173 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 5f3b0564cef9..53f2c1d99da2 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -262,14 +262,14 @@ namespace {{packageName}}.Client /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -387,6 +387,13 @@ namespace {{packageName}}.Client return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -431,185 +438,199 @@ namespace {{packageName}}.Client return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - {{#hasOAuthMethods}} - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + {{#hasOAuthMethods}} + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - {{/hasOAuthMethods}} - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + {{/hasOAuthMethods}} + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } {{#supportsAsync}} private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - {{#supportsRetry}} - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - {{/supportsRetry}} - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - {{#supportsRetry}} - } - {{/supportsRetry}} - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(policyResult); + } + else + { + {{/supportsRetry}} + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// From 0639c25fe8affd4c6ad8ea3d26711cc0f83a7bf1 Mon Sep 17 00:00:00 2001 From: filipe Date: Fri, 14 Jun 2024 13:10:57 +0100 Subject: [PATCH 8/8] Fix comments and parameters for new method DeserializeRestResponseFromPolicy Updated samples --- .../main/resources/csharp/ApiClient.mustache | 13 +- .../src/Org.OpenAPITools/Client/ApiClient.cs | 328 ++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 328 ++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 328 ++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 328 ++++++++-------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- .../src/Org.OpenAPITools/Client/ApiClient.cs | 354 +++++++++--------- 12 files changed, 2011 insertions(+), 1792 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 53f2c1d99da2..eb5be40d3ae2 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -388,12 +388,12 @@ namespace {{packageName}}.Client } /// - /// Transforms a RestResponse instance into a new ApiResponse instance. + /// Transforms a RestResponse instance into a new ApiResponse instance. /// At this point, we have a concrete http response from the service. /// Here, it is simply mapped into the [public] ApiResponse object. /// /// The RestSharp response object - /// A new ApiResponse instance. + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -442,14 +442,13 @@ namespace {{packageName}}.Client /// Executes the HTTP request for the current service. /// Based on functions received it can be async or sync. /// - /// /// Local function that executes http request and returns http response. /// Local function to specify options for the service. /// The RestSharp request object /// The RestSharp options object /// A per-request configuration object. /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. - /// A new ApiResponse instance. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; @@ -551,7 +550,7 @@ namespace {{packageName}}.Client } } - private RestResponse DeserializeRestResponseFromPolicy(PolicyResult policyResult) + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) { if (policyResult.Outcome == OutcomeType.Successful) { @@ -588,7 +587,7 @@ namespace {{packageName}}.Client { var policy = RetryConfiguration.RetryPolicy; var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return DeserializeRestResponseFromPolicy(policyResult); + return DeserializeRestResponseFromPolicy(client, request, policyResult); } else { @@ -616,7 +615,7 @@ namespace {{packageName}}.Client { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - return DeserializeRestResponseFromPolicy(policyResult); + return DeserializeRestResponseFromPolicy(client, request, policyResult); } else { diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index 8781ccda0500..1f3056ed28e2 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -262,14 +262,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -387,6 +387,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -431,164 +438,177 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index c275af5399d7..789c14ac264c 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -262,14 +262,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -387,6 +387,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -431,164 +438,177 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs index fad187913960..7f9fc8d8a175 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/MultipleFrameworks/src/Org.OpenAPITools/Client/ApiClient.cs @@ -263,14 +263,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -388,6 +388,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -432,178 +439,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 682e7e433956..0ad9a7e2d52c 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -263,14 +263,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -388,6 +388,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -432,178 +439,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 682e7e433956..0ad9a7e2d52c 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -263,14 +263,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -388,6 +388,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -432,178 +439,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 554753e31a80..fe40f39ad5b3 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -261,14 +261,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -386,6 +386,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -430,164 +437,177 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs index 5710aa120093..69279ed569c7 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -262,14 +262,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -387,6 +387,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -431,178 +438,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 5710aa120093..69279ed569c7 100644 --- a/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -262,14 +262,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -387,6 +387,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -431,178 +438,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs index e0f33c43aef4..9190dbea600a 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -261,14 +261,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -386,6 +386,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -430,164 +437,177 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index 682e7e433956..0ad9a7e2d52c 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -263,14 +263,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -388,6 +388,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -432,178 +439,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient /// diff --git a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs index 682e7e433956..0ad9a7e2d52c 100644 --- a/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/restsharp/standard2.0/Petstore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -263,14 +263,14 @@ private RestSharpMethod Method(HttpMethod method) /// /// Provides all logic for constructing a new RestSharp . - /// At this point, all information for querying the service is known. Here, it is simply - /// mapped into the RestSharp request. + /// At this point, all information for querying the service is known. + /// Here, it is simply mapped into the RestSharp request. /// /// The http verb. /// The target path (or resource). /// The additional request options. - /// A per-request configuration object. It is assumed that any merge with - /// GlobalConfiguration has been done before calling this method. + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. /// [private] A new RestRequest instance. /// private RestRequest NewRequest( @@ -388,6 +388,13 @@ private RestRequest NewRequest( return request; } + /// + /// Transforms a RestResponse instance into a new ApiResponse instance. + /// At this point, we have a concrete http response from the service. + /// Here, it is simply mapped into the [public] ApiResponse object. + /// + /// The RestSharp response object + /// A new ApiResponse instance. private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; @@ -432,178 +439,191 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } + /// + /// Executes the HTTP request for the current service. + /// Based on functions received it can be async or sync. + /// + /// Local function that executes http request and returns http response. + /// Local function to specify options for the service. + /// The RestSharp request object + /// The RestSharp options object + /// A per-request configuration object. + /// It is assumed that any merge with GlobalConfiguration has been done before calling this method. + /// A new ApiResponse instance. private ApiResponse ExecClient(Func> getResponse, Action setOptions, RestRequest request, RequestOptions options, IReadableConfiguration configuration) - { - var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - - var clientOptions = new RestClientOptions(baseUrl) - { - ClientCertificates = configuration.ClientCertificates, - MaxTimeout = configuration.Timeout, - Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials, - RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback - }; - setOptions(clientOptions); - - if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && - !string.IsNullOrEmpty(configuration.OAuthClientId) && - !string.IsNullOrEmpty(configuration.OAuthClientSecret) && - configuration.OAuthFlow != null) - { + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + setOptions(clientOptions); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { clientOptions.Authenticator = new OAuthAuthenticator( - configuration.OAuthTokenUrl, - configuration.OAuthClientId, - configuration.OAuthClientSecret, - configuration.OAuthFlow, - SerializerSettings, - configuration); - } - - using (RestClient client = new RestClient(clientOptions, - configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) - { - InterceptRequest(request); - - RestResponse response = getResponse(client); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try - { - response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - catch (Exception ex) - { - throw ex.InnerException != null ? ex.InnerException : ex; - } - } - else if (typeof(T).Name == "Stream") // for binary response - { - response.Data = (T)(object)new MemoryStream(response.RawBytes); - } - else if (typeof(T).Name == "Byte[]") // for byte response - { - response.Data = (T)(object)response.RawBytes; - } - else if (typeof(T).Name == "String") // for string response - { - response.Data = (T)(object)response.Content; - } - - InterceptResponse(request, response); - - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } - - if (response.Cookies != null && response.Cookies.Count > 0) - { - if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies.Cast()) - { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) - { - Comment = restResponseCookie.Comment, - CommentUri = restResponseCookie.CommentUri, - Discard = restResponseCookie.Discard, - Expired = restResponseCookie.Expired, - Expires = restResponseCookie.Expires, - HttpOnly = restResponseCookie.HttpOnly, - Port = restResponseCookie.Port, - Secure = restResponseCookie.Secure, - Version = restResponseCookie.Version - }; - - result.Cookies.Add(cookie); - } - } - return result; - } - } - + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration); + } + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response = getResponse(client); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private RestResponse DeserializeRestResponseFromPolicy(RestClient client, RestRequest request, PolicyResult policyResult) + { + if (policyResult.Outcome == OutcomeType.Successful) + { + return client.Deserialize(policyResult.Result); + } + else + { + return new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + } + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { - Action setOptions = (clientOptions) => - { - var cookies = new CookieContainer(); - - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - cookies.Add(new Cookie(cookie.Name, cookie.Value)); - } - } - clientOptions.CookieContainer = cookies; - }; - - Func> getResponse = (client) => - { - if (RetryConfiguration.RetryPolicy != null) - { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); - return (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - else - { - return client.Execute(request); - } - }; - - return ExecClient(getResponse, setOptions, request, options, configuration); - } + Action setOptions = (clientOptions) => + { + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + clientOptions.CookieContainer = cookies; + }; + + Func> getResponse = (client) => + { + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return client.Execute(request); + } + }; + + return ExecClient(getResponse, setOptions, request, options, configuration); + } private Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken)) { - Action setOptions = (clientOptions) => - { - //no extra options - }; - - Func> getResponse = (client) => - { - Func>> action = async () => - { - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); - if (policyResult.Outcome == OutcomeType.Successful) - { - return client.Deserialize(policyResult.Result); - } - else - { - return new RestResponse(request) - { - ErrorException = policyResult.FinalException - }; - } - } - else - { - return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - } - }; + Action setOptions = (clientOptions) => + { + //no extra options + }; + + Func> getResponse = (client) => + { + Func>> action = async () => + { + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + return DeserializeRestResponseFromPolicy(client, request, policyResult); + } + else + { + return await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + }; return action().Result; - }; + }; - return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); - } + return Task.FromResult>(ExecClient(getResponse, setOptions, request, options, configuration)); + } #region IAsynchronousClient ///