From 4f6a74cf6af8e3bf6462cc5da9df48125bd6b61b Mon Sep 17 00:00:00 2001 From: javiertuya <10879637+javiertuya@users.noreply.github.com> Date: Fri, 22 Sep 2023 12:04:41 +0200 Subject: [PATCH] Generate net client with v7, fix #46 --- .github/dependabot.yml | 3 - net/OpenApiPostprocess/Program.cs | 3 + .../Giis.Tdrules.Openapi/Client/ApiClient.cs | 279 +++++++++--------- .../Client/Configuration.cs | 29 +- .../Client/IReadableConfiguration.cs | 12 + .../Giis.Tdrules.Openapi.csproj | 36 --- .../Giis.Tdrules.Openapi/Model/TdRules.cs | 26 +- net/TdRules/TdRules.csproj | 2 +- net/build.xml | 11 +- 9 files changed, 201 insertions(+), 200 deletions(-) delete mode 100644 net/TdRules/Giis.Tdrules.Openapi/Giis.Tdrules.Openapi.csproj diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8c82547..6474936 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -16,10 +16,7 @@ updates: - package-ecosystem: nuget directory: "/net" - #avoids updates that cause not compilable code ignore: - - dependency-name: "RestSharp" - update-types: ["version-update:semver-major"] - dependency-name: "Microsoft.Data.SQLite" schedule: interval: weekly diff --git a/net/OpenApiPostprocess/Program.cs b/net/OpenApiPostprocess/Program.cs index 12f208c..e799842 100644 --- a/net/OpenApiPostprocess/Program.cs +++ b/net/OpenApiPostprocess/Program.cs @@ -89,6 +89,9 @@ private string SetterName(string name) //las palabras reservadas originan propiedades con _ delante, quita este del nombre cuando genera setters y getters if (name.StartsWith("_")) name = name.Substring(1, name.Length-1); + //as of generator v7 some properties get the prefix Var, only for Version at the moment + else if (name == "VarVersion") + name = "Version"; return name; } // Ensures line endings compatible with generated code diff --git a/net/TdRules/Giis.Tdrules.Openapi/Client/ApiClient.cs b/net/TdRules/Giis.Tdrules.Openapi/Client/ApiClient.cs index 3857574..cea5d3e 100644 --- a/net/TdRules/Giis.Tdrules.Openapi/Client/ApiClient.cs +++ b/net/TdRules/Giis.Tdrules.Openapi/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; @@ -37,7 +38,6 @@ namespace Giis.Tdrules.Openapi.Client internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; - private static readonly string _contentType = "application/json"; private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. @@ -150,17 +150,13 @@ internal object Deserialize(RestResponse response, Type type) public ISerializer Serializer => this; public IDeserializer Deserializer => this; - public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; public SupportsContentType SupportsContentType => contentType => - contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || - contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); + contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); - public string ContentType - { - get { return _contentType; } - set { throw new InvalidOperationException("Not allowed to set content type."); } - } + public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; public DataFormat DataFormat => DataFormat.Json; } @@ -433,7 +429,7 @@ private ApiResponse ToApiResponse(RestResponse response) return transformed; } - private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; @@ -453,93 +449,95 @@ private ApiResponse Exec(RestRequest req, RequestOptions options, IReadabl CookieContainer = cookies, MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; - RestClient client = new RestClient(clientOptions) - .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - - InterceptRequest(req); - - RestResponse response; - if (RetryConfiguration.RetryPolicy != null) + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) { - var policy = RetryConfiguration.RetryPolicy; - var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + InterceptRequest(request); + + RestResponse response; + if (RetryConfiguration.RetryPolicy != null) { - Request = req, - ErrorException = policyResult.FinalException - }; - } - else - { - response = client.Execute(req); - } + 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(Giis.Tdrules.Openapi.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - try + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Giis.Tdrules.Openapi.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { - response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + try + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } } - catch (Exception ex) + else if (typeof(T).Name == "Stream") // for binary response { - throw ex.InnerException != null ? ex.InnerException : ex; + 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; } - } - 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(req, response); + InterceptResponse(request, response); - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } + 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()) + if (response.Cookies != null && response.Cookies.Count > 0) { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) { - 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); + 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; } - return result; } - private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; @@ -548,79 +546,80 @@ private ApiResponse Exec(RestRequest req, RequestOptions options, IReadabl ClientCertificates = configuration.ClientCertificates, MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, - UserAgent = configuration.UserAgent + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials }; - RestClient client = new RestClient(clientOptions) - .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - - InterceptRequest(req); - - RestResponse response; - if (RetryConfiguration.AsyncRetryPolicy != null) + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + InterceptRequest(request); + + RestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) { - Request = req, - ErrorException = policyResult.FinalException - }; - } - else - { - response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); - } + 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(Giis.Tdrules.Openapi.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; - } + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Giis.Tdrules.Openapi.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(req, response); + InterceptResponse(request, response); - var result = ToApiResponse(response); - if (response.ErrorMessage != null) - { - result.ErrorText = response.ErrorMessage; - } + 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()) + if (response.Cookies != null && response.Cookies.Count > 0) { - var cookie = new Cookie( - restResponseCookie.Name, - restResponseCookie.Value, - restResponseCookie.Path, - restResponseCookie.Domain - ) + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) { - 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); + 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; } - return result; } #region IAsynchronousClient diff --git a/net/TdRules/Giis.Tdrules.Openapi/Client/Configuration.cs b/net/TdRules/Giis.Tdrules.Openapi/Client/Configuration.cs index 29f6353..8e1f924 100644 --- a/net/TdRules/Giis.Tdrules.Openapi/Client/Configuration.cs +++ b/net/TdRules/Giis.Tdrules.Openapi/Client/Configuration.cs @@ -18,6 +18,7 @@ using System.Security.Cryptography.X509Certificates; using System.Text; using System.Net.Http; +using System.Net.Security; namespace Giis.Tdrules.Openapi.Client { @@ -57,6 +58,11 @@ public class Configuration : IReadableConfiguration string.Format("Error calling {0}: {1}", methodName, response.RawContent), response.RawContent, response.Headers); } + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } return null; }; @@ -70,6 +76,8 @@ public class Configuration : IReadableConfiguration /// private string _basePath; + private bool _useDefaultCredentials = false; + /// /// Gets or sets the API key based on the authentication name. /// This is the key and value comprising the "secret" for accessing an API. @@ -175,11 +183,21 @@ public Configuration( /// /// Gets or sets the base path for API access. /// - public virtual string BasePath { + public virtual string BasePath + { get { return _basePath; } set { _basePath = value; } } + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + public virtual bool UseDefaultCredentials + { + get { return _useDefaultCredentials; } + set { _useDefaultCredentials = value; } + } + /// /// Gets or sets the default header. /// @@ -444,7 +462,7 @@ public string GetOperationServerUrl(string operation, int index) /// The operation server URL. public string GetOperationServerUrl(string operation, int index, Dictionary inputVariables) { - if (OperationServers.TryGetValue(operation, out var operationServer)) + if (operation != null && OperationServers.TryGetValue(operation, out var operationServer)) { return GetServerUrl(operationServer, index, inputVariables); } @@ -503,6 +521,11 @@ private string GetServerUrl(IList> servers, return url; } + + /// + /// Gets and Sets the RemoteCertificateValidationCallback + /// + public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } #endregion Properties @@ -579,6 +602,8 @@ public static IReadableConfiguration MergeConfigurations(IReadableConfiguration TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, + UseDefaultCredentials = second.UseDefaultCredentials, + RemoteCertificateValidationCallback = second.RemoteCertificateValidationCallback ?? first.RemoteCertificateValidationCallback, }; return config; } diff --git a/net/TdRules/Giis.Tdrules.Openapi/Client/IReadableConfiguration.cs b/net/TdRules/Giis.Tdrules.Openapi/Client/IReadableConfiguration.cs index 614af29..6c22930 100644 --- a/net/TdRules/Giis.Tdrules.Openapi/Client/IReadableConfiguration.cs +++ b/net/TdRules/Giis.Tdrules.Openapi/Client/IReadableConfiguration.cs @@ -11,6 +11,7 @@ using System; using System.Collections.Generic; using System.Net; +using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace Giis.Tdrules.Openapi.Client @@ -99,6 +100,11 @@ public interface IReadableConfiguration /// Password. string Password { get; } + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + bool UseDefaultCredentials { get; } + /// /// Get the servers associated with the operation. /// @@ -125,5 +131,11 @@ public interface IReadableConfiguration /// /// X509 Certificate collection. X509CertificateCollection ClientCertificates { get; } + + /// + /// Callback function for handling the validation of remote certificates. Useful for certificate pinning and + /// overriding certificate errors in the scope of a request. + /// + RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; } } } diff --git a/net/TdRules/Giis.Tdrules.Openapi/Giis.Tdrules.Openapi.csproj b/net/TdRules/Giis.Tdrules.Openapi/Giis.Tdrules.Openapi.csproj deleted file mode 100644 index e4dae59..0000000 --- a/net/TdRules/Giis.Tdrules.Openapi/Giis.Tdrules.Openapi.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - false - netstandard2.0 - Giis.Tdrules.Openapi - Giis.Tdrules.Openapi - Library - OpenAPI - OpenAPI - OpenAPI Library - A library generated from a OpenAPI doc - No Copyright - Giis.Tdrules.Openapi - 1.0.0 - bin\$(Configuration)\$(TargetFramework)\Giis.Tdrules.Openapi.xml - https://github.com/GIT_USER_ID/GIT_REPO_ID.git - git - Minor update - - - - - - - - - - - - - - - - - diff --git a/net/TdRules/Giis.Tdrules.Openapi/Model/TdRules.cs b/net/TdRules/Giis.Tdrules.Openapi/Model/TdRules.cs index 4e6e67b..04f9047 100644 --- a/net/TdRules/Giis.Tdrules.Openapi/Model/TdRules.cs +++ b/net/TdRules/Giis.Tdrules.Openapi/Model/TdRules.cs @@ -35,18 +35,18 @@ public partial class TdRules : IEquatable, IValidatableObject /// Initializes a new instance of the class. /// /// The class of the rules generated (`fpc` or `mutation`). - /// The version number of the service that generates this rule (default to ""). + /// The version number of the service that generates this rule (default to ""). /// The environment of the service that generates this rule (e.g. development, production) (default to ""). /// A map of additional properties to store information about the results of the evaluation of the coverage or other application specific properties. /// The query expression that generated the rules (default to ""). /// The query after being parsed (only if specified by the `options` used when calling the service) (default to ""). /// If empty, the service successfully obtained the rules, if not, indicates the error occurred, eg. the query is not syntactically correct. This field can be used to store runtime errors when executing generating the rules or executing the query (default to ""). /// The set of rules generated. - public TdRules(string rulesClass = default(string), string version = @"", string environment = @"", Dictionary summary = default(Dictionary), string query = @"", string parsedquery = @"", string error = @"", List rules = default(List)) + public TdRules(string rulesClass = default(string), string varVersion = @"", string environment = @"", Dictionary summary = default(Dictionary), string query = @"", string parsedquery = @"", string error = @"", List rules = default(List)) { this.RulesClass = rulesClass; - // use default value if no "version" provided - this._Version = version ?? @""; + // use default value if no "varVersion" provided + this.VarVersion = varVersion ?? @""; // use default value if no "environment" provided this.Environment = environment ?? @""; this.Summary = summary; @@ -73,9 +73,9 @@ public partial class TdRules : IEquatable, IValidatableObject /// /// The version number of the service that generates this rule [DataMember(Name = "version", EmitDefaultValue = false)] - public string _Version { get; set; } - public string GetVersion() { return _Version; } - public void SetVersion(string value) { _Version=value; } + public string VarVersion { get; set; } + public string GetVersion() { return VarVersion; } + public void SetVersion(string value) { VarVersion=value; } /// /// The environment of the service that generates this rule (e.g. development, production) @@ -142,7 +142,7 @@ public override string ToString() StringBuilder sb = new StringBuilder(); sb.Append("class TdRules {\n"); sb.Append(" RulesClass: ").Append(RulesClass).Append("\n"); - sb.Append(" _Version: ").Append(_Version).Append("\n"); + sb.Append(" VarVersion: ").Append(VarVersion).Append("\n"); sb.Append(" Environment: ").Append(Environment).Append("\n"); sb.Append(" Summary: ").Append(Summary).Append("\n"); sb.Append(" Query: ").Append(Query).Append("\n"); @@ -190,9 +190,9 @@ public bool Equals(TdRules input) this.RulesClass.Equals(input.RulesClass)) ) && ( - this._Version == input._Version || - (this._Version != null && - this._Version.Equals(input._Version)) + this.VarVersion == input.VarVersion || + (this.VarVersion != null && + this.VarVersion.Equals(input.VarVersion)) ) && ( this.Environment == input.Environment || @@ -241,9 +241,9 @@ public override int GetHashCode() { hashCode = (hashCode * 59) + this.RulesClass.GetHashCode(); } - if (this._Version != null) + if (this.VarVersion != null) { - hashCode = (hashCode * 59) + this._Version.GetHashCode(); + hashCode = (hashCode * 59) + this.VarVersion.GetHashCode(); } if (this.Environment != null) { diff --git a/net/TdRules/TdRules.csproj b/net/TdRules/TdRules.csproj index 5d0167b..87e646e 100644 --- a/net/TdRules/TdRules.csproj +++ b/net/TdRules/TdRules.csproj @@ -51,7 +51,7 @@ - + diff --git a/net/build.xml b/net/build.xml index aba614a..10d7f47 100644 --- a/net/build.xml +++ b/net/build.xml @@ -264,10 +264,7 @@ - - Using openapi generator version ${OAG_VERSION} @@ -283,7 +280,9 @@ - + + + @@ -291,7 +290,9 @@ - + + +