Skip to content

Commit

Permalink
chore: enable C#10/latest and use newer lang
Browse files Browse the repository at this point in the history
  • Loading branch information
skwasjer committed Jul 10, 2022
1 parent 41d1bed commit 31eaaa8
Show file tree
Hide file tree
Showing 16 changed files with 48 additions and 51 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<LangVersion>8.0</LangVersion>
<LangVersion>latest</LangVersion>
<DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder>
<WarnOnPackingNonPackableProject>false</WarnOnPackingNonPackableProject>
</PropertyGroup>
Expand Down
2 changes: 0 additions & 2 deletions src/Correlate.Abstractions/IActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ public interface IActivity
/// <summary>
/// Signals the activity is complete.
/// </summary>
#pragma warning disable CA1716
void Stop();
#pragma warning restore CA1716
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ public class CorrelateOptions
/// <remarks>
/// The first matching header will be used.
/// </remarks>
#pragma warning disable CA1819 // TODO: in next major release change to IEnumerable<>/ICollection<>.
public string[] RequestHeaders { get; set; } = {
CorrelationHttpHeaders.CorrelationId
};
#pragma warning restore CA1819

/// <summary>
/// Gets or sets whether to include the correlation id in the response.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,26 @@ internal HttpRequestActivity(ILogger logger, HttpContext httpContext, string? re

public void Start(CorrelationContext? correlationContext)
{
if (_includeInResponse && correlationContext != null)
if (_includeInResponse && correlationContext is not null)
{
_httpContext.Response.OnStarting(() =>
{
// If already set, ignore.
if (!_httpContext.Response.Headers.ContainsKey(_responseHeaderName!))
if (_httpContext.Response.Headers.ContainsKey(_responseHeaderName!))
{
_logger.LogTrace("Setting response header '{HeaderName}' to correlation id '{CorrelationId}'.", _responseHeaderName, correlationContext.CorrelationId);
_httpContext.Response.Headers.Add(_responseHeaderName!, correlationContext.CorrelationId);
return Task.CompletedTask;
}

_logger.LogTrace("Setting response header '{HeaderName}' to correlation id '{CorrelationId}'.", _responseHeaderName, correlationContext.CorrelationId);
_httpContext.Response.Headers.Add(_responseHeaderName!, correlationContext.CorrelationId);

return Task.CompletedTask;
});
}
}

#pragma warning disable CA1822
// ReSharper disable once MemberCanBeMadeStatic.Global
public void Stop()
#pragma warning restore CA1822
{
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Correlate.Core/CorrelationContextAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Correlate
/// </summary>
public class CorrelationContextAccessor : ICorrelationContextAccessor
{
private static readonly AsyncLocal<CorrelationContextHolder> CurrentContext = new AsyncLocal<CorrelationContextHolder>();
private static readonly AsyncLocal<CorrelationContextHolder> CurrentContext = new();

/// <inheritdoc />
public CorrelationContext? CorrelationContext
Expand Down
4 changes: 2 additions & 2 deletions src/Correlate.Core/CorrelationContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public CorrelationContextFactory(ICorrelationContextAccessor correlationContextA
CorrelationContext ICorrelationContextFactory.Create(string correlationId)
{
CorrelationContext correlationContext = Create(correlationId);
if (_correlationContextAccessor != null)
if (_correlationContextAccessor is not null)
{
_correlationContextAccessor.CorrelationContext = correlationContext;
}
Expand All @@ -54,7 +54,7 @@ public virtual CorrelationContext Create(string correlationId)
/// <inheritdoc />
public void Dispose()
{
if (_correlationContextAccessor != null)
if (_correlationContextAccessor is not null)
{
_correlationContextAccessor.CorrelationContext = null;
}
Expand Down
16 changes: 8 additions & 8 deletions src/Correlate.Core/CorrelationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ private Void()
{
}

public static readonly Void Null = new Void();
public static readonly Void Null = new();
}

/// <summary>
Expand Down Expand Up @@ -77,7 +77,7 @@ DiagnosticListener diagnosticListener
/// </remarks>
public Task CorrelateAsync(string? correlationId, Func<Task> correlatedTask, OnException? onException)
{
if (correlatedTask == null)
if (correlatedTask is null)
{
throw new ArgumentNullException(nameof(correlatedTask));
}
Expand Down Expand Up @@ -106,15 +106,15 @@ public Task CorrelateAsync(string? correlationId, Func<Task> correlatedTask, OnE
/// </remarks>
public Task<T> CorrelateAsync<T>(string? correlationId, Func<Task<T>> correlatedTask, OnException<T>? onException)
{
if (correlatedTask == null)
if (correlatedTask is null)
{
throw new ArgumentNullException(nameof(correlatedTask));
}

return ExecuteAsync(
correlationId,
correlatedTask,
onException == null ? (OnException?)null : context => onException!((ExceptionContext<T>)context)
onException is null ? null : context => onException((ExceptionContext<T>)context)
);
}

Expand Down Expand Up @@ -148,7 +148,7 @@ private async Task<T> ExecuteAsync<T>(string? correlationId, Func<Task<T>> corre
/// </remarks>
public void Correlate(string? correlationId, Action correlatedAction, OnException? onException)
{
if (correlatedAction == null)
if (correlatedAction is null)
{
throw new ArgumentNullException(nameof(correlatedAction));
}
Expand All @@ -175,15 +175,15 @@ public void Correlate(string? correlationId, Action correlatedAction, OnExceptio
/// </remarks>
public T Correlate<T>(string? correlationId, Func<T> correlatedFunc, OnException<T>? onException)
{
if (correlatedFunc == null)
if (correlatedFunc is null)
{
throw new ArgumentNullException(nameof(correlatedFunc));
}

return Execute(
correlationId,
correlatedFunc,
onException == null ? (OnException?)null : context => onException!((ExceptionContext<T>)context)
onException is null ? null : context => onException((ExceptionContext<T>)context)
);
}

Expand Down Expand Up @@ -223,7 +223,7 @@ private static bool HandlesException<T>(OnException? onException, CorrelationCon
ex.Data.Add(CorrelateConstants.CorrelationIdKey, correlationContext.CorrelationId);
}

if (onException != null)
if (onException is not null)
{
bool hasResultValue = typeof(T) != typeof(Void);

Expand Down
8 changes: 3 additions & 5 deletions src/Correlate.Core/Http/CorrelatingHttpMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public class CorrelatingHttpMessageHandler : DelegatingHandler
/// <param name="correlationContextAccessor">The correlation context accessor.</param>
/// <param name="options">The client correlation options.</param>
public CorrelatingHttpMessageHandler(ICorrelationContextAccessor correlationContextAccessor, IOptions<CorrelateClientOptions> options)
: base()
{
_correlationContextAccessor = correlationContextAccessor;
_options = options?.Value ?? new CorrelateClientOptions();
Expand All @@ -33,10 +32,9 @@ public CorrelatingHttpMessageHandler(ICorrelationContextAccessor correlationCont
/// <param name="options">The client correlation options.</param>
/// <param name="innerHandler">The inner handler.</param>
public CorrelatingHttpMessageHandler(ICorrelationContextAccessor correlationContextAccessor, IOptions<CorrelateClientOptions> options, HttpMessageHandler innerHandler)
: base(innerHandler)
: this(correlationContextAccessor, options)
{
_correlationContextAccessor = correlationContextAccessor;
_options = options?.Value ?? new CorrelateClientOptions();
InnerHandler = innerHandler;
}

/// <inheritdoc />
Expand All @@ -48,7 +46,7 @@ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage reques
}

string? correlationId = _correlationContextAccessor?.CorrelationContext?.CorrelationId;
if (correlationId != null && !request.Headers.Contains(_options.RequestHeader))
if (correlationId is not null && !request.Headers.Contains(_options.RequestHeader))
{
request.Headers.TryAddWithoutValidation(_options.RequestHeader, correlationId);
}
Expand Down
18 changes: 10 additions & 8 deletions src/Correlate.Core/Http/Extensions/HeaderDictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ internal static class HeaderDictionaryExtensions
{
internal static KeyValuePair<string, string?> GetCorrelationIdHeader(this IDictionary<string, StringValues> httpHeaders, ICollection<string> acceptedHeaders)
{
if (acceptedHeaders == null)
if (acceptedHeaders is null)
{
throw new ArgumentNullException(nameof(acceptedHeaders));
}
Expand All @@ -24,14 +24,16 @@ internal static class HeaderDictionaryExtensions

foreach (string requestHeaderName in acceptedHeaders)
{
if (httpHeaders.TryGetValue(requestHeaderName, out StringValues value))
if (!httpHeaders.TryGetValue(requestHeaderName, out StringValues value))
{
headerName = requestHeaderName;
correlationId = value.LastOrDefault();
if (!string.IsNullOrWhiteSpace(correlationId))
{
break;
}
continue;
}

headerName = requestHeaderName;
correlationId = value.LastOrDefault();
if (!string.IsNullOrWhiteSpace(correlationId))
{
break;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Correlate.Core/RootActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public RootActivity(
/// <returns>The created correlation context (also accessible via <see cref="ICorrelationContextAccessor"/>), or null if diagnostics and logging is disabled.</returns>
public CorrelationContext Start(string correlationId)
{
if (correlationId == null)
if (correlationId is null)
{
throw new ArgumentNullException(nameof(correlationId));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ public static IHttpClientBuilder CorrelateRequests(this IHttpClientBuilder build
builder.Services.Configure(builder.Name, configureOptions);
builder.AddHttpMessageHandler(s =>
{
var allClientOptions = s.GetRequiredService<IOptionsSnapshot<CorrelateClientOptions>>();
var thisClientOptions = new OptionsWrapper<CorrelateClientOptions>(allClientOptions.Get(builder.Name));
IOptionsSnapshot<CorrelateClientOptions> allClientOptions = s.GetRequiredService<IOptionsSnapshot<CorrelateClientOptions>>();
IOptions<CorrelateClientOptions> thisClientOptions = Options.Create(allClientOptions.Get(builder.Name));

return ActivatorUtilities.CreateInstance<CorrelatingHttpMessageHandler>(
s,
(IOptions<CorrelateClientOptions>)thisClientOptions
thisClientOptions
);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public TestController(ILogger<TestController> logger, ICorrelationContextAccesso
[HttpGet]
public IActionResult Get()
{
_logger.LogInformation($"controller action: ok - {_correlationContextAccessor.CorrelationContext.CorrelationId}");
_logger.LogInformation("controller action: ok - {Id}", _correlationContextAccessor.CorrelationContext.CorrelationId);

return Ok("ok");
}
Expand All @@ -37,11 +37,11 @@ public IActionResult Get()
[HttpGet("correlate_client_request")]
public async Task<IActionResult> CorrelateClientRequest()
{
_logger.LogInformation($"controller action: ok - {_correlationContextAccessor.CorrelationContext.CorrelationId}");
_logger.LogInformation("controller action: ok - {Id}", _correlationContextAccessor.CorrelationContext.CorrelationId);

HttpResponseMessage response = await _httpClient.GetAsync("correlated_external_call");

return StatusCode((int)response.StatusCode, response.ReasonPhrase);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal class TestResponseFeature : IHttpResponseFeature
{
private Func<Task> _responseStartingAsync = () => Task.FromResult(true);
private Func<Task> _responseCompletedAsync = () => Task.FromResult(true);
private HeaderDictionary _headers = new HeaderDictionary();
private readonly HeaderDictionary _headers = new();
private int _statusCode;
private string _reasonPhrase;

Expand Down Expand Up @@ -72,7 +72,7 @@ public void OnStarting(Func<object, Task> callback, object state)
throw new InvalidOperationException();
}

var prior = _responseStartingAsync;
Func<Task> prior = _responseStartingAsync;
_responseStartingAsync = async () =>
{
await callback(state);
Expand All @@ -82,7 +82,7 @@ public void OnStarting(Func<object, Task> callback, object state)

public void OnCompleted(Func<object, Task> callback, object state)
{
var prior = _responseCompletedAsync;
Func<Task> prior = _responseCompletedAsync;
_responseCompletedAsync = async () =>
{
try
Expand All @@ -108,4 +108,4 @@ public Task FireOnResponseCompletedAsync()
return _responseCompletedAsync();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public sealed class CorrelatingMessageHandlerTests : IDisposable
private readonly CorrelatingHttpMessageHandler _sut;
private readonly HttpClient _httpClient;
private readonly MockHttpHandler _mockHttp;
private readonly CorrelateClientOptions _correlateClientOptions = new CorrelateClientOptions();
private readonly CorrelateClientOptions _correlateClientOptions = new();

private static readonly Uri BaseUri = new Uri("http://0.0.0.0/");
private static readonly Uri BaseUri = new("http://0.0.0.0/");

public CorrelatingMessageHandlerTests()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void When_using_empty_accepted_headers_should_throw()
var expectedHeader = new KeyValuePair<string, string>(CorrelationHttpHeaders.CorrelationId, null);

// Act
KeyValuePair<string, string> header = _sut.GetCorrelationIdHeader(new string[0]);
KeyValuePair<string, string> header = _sut.GetCorrelationIdHeader(Array.Empty<string>());

// Assert
header.Should().BeEquivalentTo(expectedHeader, "it should not take correlation id from header dictionary but still return header key");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ public AndConstraint<ServiceProviderAssertions> Resolve(Type serviceType, string
return ex;
}
})
.ForCondition(value => !(value is Exception))
.ForCondition(value => value is not Exception)
.FailWith("but threw with {0}.", ex => ex)
.Then
.ForCondition(value => value != null)
.ForCondition(value => value is not null)
.FailWith("but failed.")
;

Expand Down

0 comments on commit 31eaaa8

Please sign in to comment.