Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C# API Client CancellationToken, Base Validation and Nullable/Required #13049

Merged
merged 6 commits into from
Aug 6, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -448,84 +448,101 @@ namespace {{packageName}}.Client
IReadableConfiguration configuration,
System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
IDisposable timeoutTokenSource = null;
IDisposable finalTokenSource = null;
var deserializer = new CustomJsonCodec(SerializerSettings, configuration);

var finalToken = cancellationToken;

if (configuration.Timeout > 0)
try
{
var tokenSource = new CancellationTokenSource(configuration.Timeout);
finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token;
}
if (configuration.Timeout > 0)
{
timeoutTokenSource = new CancellationTokenSource(configuration.Timeout);
finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token);
finalToken = finalTokenSource.Token;
}

if (configuration.Proxy != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.Proxy = configuration.Proxy;
}
if (configuration.Proxy != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.Proxy = configuration.Proxy;
}

if (configuration.ClientCertificates != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
}
if (configuration.ClientCertificates != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
}

var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List<Cookie> : null;
var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List<Cookie> : null;

if (cookieContainer != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
foreach (var cookie in cookieContainer)
if (cookieContainer != null)
{
_httpClientHandler.CookieContainer.Add(cookie);
if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
foreach (var cookie in cookieContainer)
{
_httpClientHandler.CookieContainer.Add(cookie);
}
}
}

InterceptRequest(req);
InterceptRequest(req);

HttpResponseMessage response;
{{#supportsRetry}}
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy
.ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken))
.ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ?
policyResult.Result : new HttpResponseMessage()
{
ReasonPhrase = policyResult.FinalException.ToString(),
RequestMessage = req
};
}
else
{
{{/supportsRetry}}
response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false);
{{#supportsRetry}}
}
{{/supportsRetry}}
HttpResponseMessage response;
{{#supportsRetry}}
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy
.ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken))
.ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ?
policyResult.Result : new HttpResponseMessage()
{
ReasonPhrase = policyResult.FinalException.ToString(),
RequestMessage = req
};
}
else
{
{{/supportsRetry}}
response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false);
{{#supportsRetry}}
}
{{/supportsRetry}}

if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default(T), req.RequestUri);
}

object responseData = await deserializer.Deserialize<T>(response);
if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default(T), req.RequestUri);
}

// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
object responseData = await deserializer.Deserialize<T>(response);

// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
responseData = (T) (object) await response.Content.ReadAsStreamAsync();
}

InterceptResponse(req, response);

return await ToApiResponse<T>(response, responseData, req.RequestUri);
}
else if (typeof(T).Name == "Stream") // for binary response
finally
{
responseData = (T) (object) await response.Content.ReadAsStreamAsync();
}

InterceptResponse(req, response);
if (timeoutTokenSource != null)
{
timeoutTokenSource.Dispose();
}

return await ToApiResponse<T>(response, responseData, req.RequestUri);
if (finalTokenSource != null)
{
finalTokenSource.Dispose();
}
}
}

{{#supportsAsync}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@
{{#parent}}
{{^isArray}}
{{^isMap}}
foreach(var x in BaseValidate(validationContext)) yield return x;
foreach(var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext)) yield return x;
{{/isMap}}
{{/isArray}}
{{/parent}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -450,84 +450,101 @@ namespace {{packageName}}.Client
IReadableConfiguration configuration,
System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
IDisposable timeoutTokenSource = null;
IDisposable finalTokenSource = null;
var deserializer = new CustomJsonCodec(SerializerSettings, configuration);

var finalToken = cancellationToken;

if (configuration.Timeout > 0)
try
{
var tokenSource = new CancellationTokenSource(configuration.Timeout);
finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token;
}
if (configuration.Timeout > 0)
{
timeoutTokenSource = new CancellationTokenSource(configuration.Timeout);
finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token);
finalToken = finalTokenSource.Token;
}

if (configuration.Proxy != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.Proxy = configuration.Proxy;
}
if (configuration.Proxy != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.Proxy = configuration.Proxy;
}

if (configuration.ClientCertificates != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
}
if (configuration.ClientCertificates != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
_httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
}

var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List<Cookie> : null;
var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List<Cookie> : null;

if (cookieContainer != null)
{
if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
foreach (var cookie in cookieContainer)
if (cookieContainer != null)
{
_httpClientHandler.CookieContainer.Add(cookie);
if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
foreach (var cookie in cookieContainer)
{
_httpClientHandler.CookieContainer.Add(cookie);
}
}
}

InterceptRequest(req);
InterceptRequest(req);

HttpResponseMessage response;
{{#supportsRetry}}
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy
.ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken))
.ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ?
policyResult.Result : new HttpResponseMessage()
{
ReasonPhrase = policyResult.FinalException.ToString(),
RequestMessage = req
};
}
else
{
{{/supportsRetry}}
response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false);
{{#supportsRetry}}
}
{{/supportsRetry}}
HttpResponseMessage response;
{{#supportsRetry}}
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy
.ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken))
.ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ?
policyResult.Result : new HttpResponseMessage()
{
ReasonPhrase = policyResult.FinalException.ToString(),
RequestMessage = req
};
}
else
{
{{/supportsRetry}}
response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false);
{{#supportsRetry}}
}
{{/supportsRetry}}

if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default(T), req.RequestUri);
}
if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default(T), req.RequestUri);
}

object responseData = await deserializer.Deserialize<T>(response);
object responseData = await deserializer.Deserialize<T>(response);

// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
responseData = (T) (object) await response.Content.ReadAsStreamAsync();
}

InterceptResponse(req, response);

return await ToApiResponse<T>(response, responseData, req.RequestUri);
}
else if (typeof(T).Name == "Stream") // for binary response
finally
{
responseData = (T) (object) await response.Content.ReadAsStreamAsync();
}

InterceptResponse(req, response);
if (timeoutTokenSource != null)
{
timeoutTokenSource.Dispose();
}

return await ToApiResponse<T>(response, responseData, req.RequestUri);
if (finalTokenSource != null)
{
finalTokenSource.Dispose();
}
}
}

{{#supportsAsync}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
{{#parent}}
{{^isArray}}
{{^isMap}}
foreach (var x in BaseValidate(validationContext))
foreach (var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext))
{
yield return x;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public override int GetHashCode()
/// <returns>Validation Result</returns>
protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
{
foreach (var x in BaseValidate(validationContext))
foreach (var x in base.BaseValidate(validationContext))
{
yield return x;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public override int GetHashCode()
/// <returns>Validation Result</returns>
protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
{
foreach (var x in BaseValidate(validationContext))
foreach (var x in base.BaseValidate(validationContext))
{
yield return x;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public override int GetHashCode()
/// <returns>Validation Result</returns>
protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
{
foreach (var x in BaseValidate(validationContext))
foreach (var x in base.BaseValidate(validationContext))
{
yield return x;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public override int GetHashCode()
/// <returns>Validation Result</returns>
protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
{
foreach (var x in BaseValidate(validationContext))
foreach (var x in base.BaseValidate(validationContext))
{
yield return x;
}
Expand Down
Loading