Skip to content

Commit

Permalink
Fixes from Code Analysis, latest C# language features
Browse files Browse the repository at this point in the history
  • Loading branch information
axunonb committed Apr 10, 2022
1 parent ba92932 commit e7bcab7
Show file tree
Hide file tree
Showing 156 changed files with 848 additions and 802 deletions.
13 changes: 10 additions & 3 deletions Axuno.BackgroundTask.Test/NUnitLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ protected NUnitLogger(string category)
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
}

/// <summary>
Expand Down Expand Up @@ -87,14 +88,20 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
/// </summary>
/// <param name="logLevel"></param>
/// <returns>Returns <see langword="true"/> if the log <see cref="LogLevel"/> parameter is greater or equal than the minimum <see cref="LogLevel"/>, else false.</returns>
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel;
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= LogLevel;
}

/// <summary>
/// Gets the instance of this logger as a logical operation scope.
/// </summary>
/// <typeparam name="TState"></typeparam>
/// <param name="state"></param>
/// <returns>Returns the instance of this logger.</returns>
public IDisposable BeginScope<TState>(TState state) => this;
public IDisposable BeginScope<TState>(TState state)
{
return this;
}
}
}
}
46 changes: 21 additions & 25 deletions Axuno.BackgroundTask/BackgroundQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ public class BackgroundQueue : IBackgroundQueue
{
private readonly Action<Exception> _onException;
private readonly ILogger<BackgroundQueue> _logger;
internal readonly ConcurrentQueue<IBackgroundTask> TaskItems =
new ConcurrentQueue<IBackgroundTask>();

internal readonly ConcurrentQueue<IBackgroundTask> TaskItems = new();
private readonly SemaphoreSlim _signal;

/// <summary>
Expand Down Expand Up @@ -48,7 +46,7 @@ public void QueueTask(IBackgroundTask taskItem)

TaskItems.Enqueue(taskItem);
_signal.Release(); // increase the semaphore count for each item
_logger.LogTrace($"Number of queued TaskItems is {_signal.CurrentCount}");
_logger.LogTrace("Number of queued TaskItems is {taskItemCount}", _signal.CurrentCount);
}

/// <summary>
Expand Down Expand Up @@ -118,29 +116,27 @@ public async Task RunTaskAsync(IBackgroundTask backgroundTask, CancellationToken
/// <param name="cancellationToken">The <see cref="CancellationToken"/></param>
/// <returns>Returns the completed original task or throws a <see cref="TimeoutException"/></returns>
/// <exception cref="TimeoutException"></exception>
private async Task CancelAfterAsync(Func<CancellationToken, Task> startTask, TimeSpan timeout, CancellationToken cancellationToken)
private static async Task CancelAfterAsync(Func<CancellationToken, Task> startTask, TimeSpan timeout, CancellationToken cancellationToken)
{
using (var timeoutCancellation = new CancellationTokenSource())
using (var combinedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
using var timeoutCancellation = new CancellationTokenSource();
using var combinedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token);
var originalTask = startTask(combinedCancellation.Token);
var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
var completedTask = await Task.WhenAny(originalTask, delayTask);
// Cancel timeout to stop either task:
// - Either the original task completed, so we need to cancel the delay task.
// - Or the timeout expired, so we need to cancel the original task.
// Canceling will not affect a task, that is already completed.
timeoutCancellation.Cancel();
if (completedTask == originalTask)
{
// original task completed
await originalTask;
}
else
{
var originalTask = startTask(combinedCancellation.Token);
var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
var completedTask = await Task.WhenAny(originalTask, delayTask);
// Cancel timeout to stop either task:
// - Either the original task completed, so we need to cancel the delay task.
// - Or the timeout expired, so we need to cancel the original task.
// Canceling will not affect a task, that is already completed.
timeoutCancellation.Cancel();
if (completedTask == originalTask)
{
// original task completed
await originalTask;
}
else
{
// timeout
throw new TimeoutException();
}
// timeout
throw new TimeoutException();
}
}
}
Expand Down
11 changes: 9 additions & 2 deletions Axuno.BackgroundTask/BackgroundQueueServiceConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,15 @@ public class BackgroundQueueServiceConfig
/// </summary>
public TimeSpan PollQueueDelay
{
get => _pollQueueDelay;
set => _pollQueueDelay = value == default ? TimeSpan.FromMilliseconds(100) : value;
get
{
return _pollQueueDelay;
}

set
{
_pollQueueDelay = value == default ? TimeSpan.FromMilliseconds(100) : value;
}
}
}
}
6 changes: 3 additions & 3 deletions Axuno.BackgroundTask/ConcurrentBackgroundQueueService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace Axuno.BackgroundTask
public class ConcurrentBackgroundQueueService : BackgroundService
{
private readonly ILogger<ConcurrentBackgroundQueueService> _logger;
private readonly ManualResetEvent _resetEvent = new ManualResetEvent(true);
private readonly object _locker = new object();
private readonly ManualResetEvent _resetEvent = new(true);
private readonly object _locker = new();
private int _concurrentTaskCount;

public ConcurrentBackgroundQueueService(IBackgroundQueue taskQueue,
Expand Down Expand Up @@ -53,7 +53,7 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
if (_concurrentTaskCount < Config.MaxConcurrentCount && TaskQueue.Count > 0)
{
Interlocked.Increment(ref _concurrentTaskCount);
_logger.LogTrace($"Num of tasks: {_concurrentTaskCount}");
_logger.LogTrace("Num of tasks: {concurrentTaskCount}", _concurrentTaskCount);
taskListReference.Enqueue(TaskQueue.DequeueTask());
}
else
Expand Down
22 changes: 18 additions & 4 deletions Axuno.BackgroundTask/ConcurrentBackgroundQueueServiceConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,31 @@ public class ConcurrentBackgroundQueueServiceConfig
/// </summary>
public int MaxConcurrentCount
{
get => _maxConcurrentCount;
set => _maxConcurrentCount = value > 0 ? value : 5;
get
{
return _maxConcurrentCount;
}

set
{
_maxConcurrentCount = value > 0 ? value : 5;
}
}
/// <summary>
/// The time to wait until the <see cref="IBackgroundQueue"/> is checked for new entries.
/// Defaults to 100 milliseconds.
/// </summary>
public TimeSpan PollQueueDelay
{
get => _pollQueueDelay;
set => _pollQueueDelay = value == default ? TimeSpan.FromMilliseconds(100) : value;
get
{
return _pollQueueDelay;
}

set
{
_pollQueueDelay = value == default ? TimeSpan.FromMilliseconds(100) : value;
}
}
}
}
14 changes: 6 additions & 8 deletions Axuno.BackgroundTask/ConsumeScopedServiceHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,12 @@ private async Task DoWork(CancellationToken stoppingToken)
_logger.LogInformation(
"Consume Scoped Service Hosted Service is working.");

using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();

await scopedProcessingService.DoWork(stoppingToken);
}
using var scope = Services.CreateScope();
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();

await scopedProcessingService.DoWork(stoppingToken);
}

public override async Task StopAsync(CancellationToken stoppingToken)
Expand Down
1 change: 1 addition & 0 deletions Axuno.BackgroundTask/CronJobService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public virtual async Task StopAsync(CancellationToken cancellationToken)
public virtual void Dispose()
{
_timer?.Dispose();
GC.SuppressFinalize(this);
}
}
}
20 changes: 6 additions & 14 deletions Axuno.Tools/DateAndTime/TimeZoneConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,19 +136,11 @@ public DateTime ToUtc(DateTime zoneDateTime, string timeZoneId)
{
if (!dateTimeOfAnyKind.HasValue) return null;

DateTime utcDateTime;
switch (dateTimeOfAnyKind.Value.Kind)
{
case DateTimeKind.Utc:
utcDateTime = dateTimeOfAnyKind.Value;
break;
case DateTimeKind.Local:
utcDateTime = dateTimeOfAnyKind.Value.ToUniversalTime();
break;
default: //DateTimeKind.Unspecified
utcDateTime = DateTime.SpecifyKind(dateTimeOfAnyKind.Value, DateTimeKind.Utc);
break;
}
var utcDateTime = dateTimeOfAnyKind.Value.Kind switch {
DateTimeKind.Utc => dateTimeOfAnyKind.Value,
DateTimeKind.Local => dateTimeOfAnyKind.Value.ToUniversalTime(),
_ => DateTime.SpecifyKind(dateTimeOfAnyKind.Value, DateTimeKind.Utc)
};

return ToZonedTime(new DateTimeOffset(utcDateTime), timeZoneId, cultureInfo, timeZoneProvider);
}
Expand Down Expand Up @@ -289,7 +281,7 @@ public static DateTime ToUtc(DateTime zoneDateTime, string timeZoneId,
/// <returns>Returns <c>true</c> if the <see cref="TimeZoneInfo"/> can be mapped to a IANA timezone, otherwise <c>false</c>.</returns>
public static bool CanMapToIanaTimeZone(TimeZoneInfo timeZoneInfo)
{
return TzConverter.TZConvert.TryWindowsToIana(timeZoneInfo.Id, out var ianaTimeZoneName);
return TzConverter.TZConvert.TryWindowsToIana(timeZoneInfo.Id, out _);
}

/// <summary>
Expand Down
58 changes: 33 additions & 25 deletions Axuno.Tools/ExpiringTripleDES.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,32 +116,40 @@ private void GenerateKeyAndIV()
/// Gets or set the System.Security.Cryptography.SymmetricAlgorithm.Key (UTF8 is used. Characters exceeding 24 bytes are truncated, less will be filled.)
/// </summary>
public string Key
{
get { return _utf8Encoding.GetString(_tripleDES.Key); }
set
{
_tripleDES.Key = _utf8Encoding.GetBytes(value + _charsToUse).TakeWhile((b, index) => index < 24).ToArray();
}
}
{
get
{
return _utf8Encoding.GetString(_tripleDES.Key);
}

/// <summary>
/// Gets or set the System.Security.Cryptography.SymmetricAlgorithm.IV initalization vector (UTF8 is used. Characters exceeding 8 bytes are truncated, less will be filled.)
/// </summary>
public string IV
{
get { return _utf8Encoding.GetString(_tripleDES.IV); }
set
{
_tripleDES.IV = _utf8Encoding.GetBytes(value + _charsToUse).TakeWhile((b, index) => index < 8).ToArray();
}
}
set
{
_tripleDES.Key = _utf8Encoding.GetBytes(value + _charsToUse).TakeWhile((b, index) => index < 24).ToArray();
}
}

/// <summary>
/// Function delegate for converting the fields and properties of the container object
/// into a text string which shall be encrypted
/// </summary>
/// <returns>Returns a string with container fields and properties</returns>
public Func<T, string> ToText { get; set; }
/// <summary>
/// Gets or set the System.Security.Cryptography.SymmetricAlgorithm.IV initalization vector (UTF8 is used. Characters exceeding 8 bytes are truncated, less will be filled.)
/// </summary>
public string IV
{
get
{
return _utf8Encoding.GetString(_tripleDES.IV);
}

set
{
_tripleDES.IV = _utf8Encoding.GetBytes(value + _charsToUse).TakeWhile((b, index) => index < 8).ToArray();
}
}

/// <summary>
/// Function delegate for converting the fields and properties of the container object
/// into a text string which shall be encrypted
/// </summary>
/// <returns>Returns a string with container fields and properties</returns>
public Func<T, string> ToText { get; set; }

/// <summary>
/// Function delegate for converting a decrypted string back into fields and properties
Expand Down Expand Up @@ -257,4 +265,4 @@ private static byte[] Transform(byte[] input, ICryptoTransform CryptoTransform)
return result;
}
}
}
}
2 changes: 1 addition & 1 deletion Axuno.Tools/GeoSpatial/Angle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ internal static Tuple<string, int> ParseFormatString(string format)

return int.TryParse(format[index..], NumberStyles.None, CultureInfo.InvariantCulture,
out var precision)
? Tuple.Create(format.Substring(0, index), precision)
? Tuple.Create(format[..index], precision)
: Tuple.Create(format, -1);
}

Expand Down
2 changes: 1 addition & 1 deletion Axuno.Tools/GeoSpatial/GoogleGeo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class GeoResponse
/// <summary>
/// Gets or sets the <see cref="GeoLocation"/>.
/// </summary>
public GeoLocation GeoLocation { get; set; } = new GeoLocation();
public GeoLocation GeoLocation { get; set; } = new();
/// <summary>
/// Gets or sets the status text returned from the server API.
/// </summary>
Expand Down
10 changes: 5 additions & 5 deletions Axuno.Tools/GeoSpatial/Latitude.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ private Latitude(double radians)
/// <exception cref="ArgumentOutOfRangeException">
/// degrees is greater than 90 or less than -90.
/// </exception>
public new static Latitude FromDegrees(double degrees)
public static new Latitude FromDegrees(double degrees)
{
ValidateRange("degrees", degrees, -90, 90);
return new Latitude(Angle.FromDegrees(degrees).Radians);
Expand All @@ -57,7 +57,7 @@ private Latitude(double radians)
/// The specified angle (degrees + minutes) is greater than 90 or less
/// than -90.
/// </exception>
public new static Latitude FromDegrees(double degrees, double minutes)
public static new Latitude FromDegrees(double degrees, double minutes)
{
var angle = Angle.FromDegrees(degrees, minutes);
ValidateRange("angle", angle.TotalDegrees, -90, 90);
Expand All @@ -76,7 +76,7 @@ private Latitude(double radians)
/// The specified angle (degrees + minutes + seconds) is greater than
/// 90 or less than -90.
/// </exception>
public new static Latitude FromDegrees(double degrees, double minutes, double seconds)
public static new Latitude FromDegrees(double degrees, double minutes, double seconds)
{
var angle = Angle.FromDegrees(degrees, minutes, seconds);
ValidateRange("angle", angle.TotalDegrees, -90, 90);
Expand All @@ -90,7 +90,7 @@ private Latitude(double radians)
/// <exception cref="ArgumentOutOfRangeException">
/// radians is greater than PI/2 or less than -PI/2.
/// </exception>
public new static Latitude FromRadians(double radians)
public static new Latitude FromRadians(double radians)
{
ValidateRange("radians", radians, -Math.PI / 2.0, Math.PI / 2.0);
return new Latitude(radians);
Expand Down Expand Up @@ -128,7 +128,7 @@ public override string ToString(string format, IFormatProvider formatProvider)
Math.Abs(Seconds));
}

string formatted = base.ToString(format, formatProvider);
var formatted = base.ToString(format, formatProvider);
if (Radians < 0)
{
// We're going to remove the negative sign, but find out what a
Expand Down
Loading

0 comments on commit e7bcab7

Please sign in to comment.