Skip to content

Commit

Permalink
chore - apply SonarCloud code recommendations (#156)
Browse files Browse the repository at this point in the history
No changes in logic
  • Loading branch information
axunonb authored Apr 11, 2024
1 parent b7e9e7e commit 4fa64ea
Show file tree
Hide file tree
Showing 35 changed files with 570 additions and 5,929 deletions.
10 changes: 5 additions & 5 deletions Axuno.BackgroundTask/BackgroundQueueService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ public BackgroundQueueService(IBackgroundQueue taskQueue,
/// </summary>
public IBackgroundQueue TaskQueue { get; }

protected override async Task ExecuteAsync(CancellationToken cancellationToken)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!cancellationToken.IsCancellationRequested)
while (!stoppingToken.IsCancellationRequested)
{
try
{
await Task.Delay(Config.PollQueueDelay, cancellationToken);
await Task.Delay(Config.PollQueueDelay, stoppingToken);
_logger.LogDebug($"TaskItem dequeuing.");
var taskItemReference = TaskQueue.DequeueTask();
_logger.LogDebug($"TaskItem start executing.");
await TaskQueue.RunTaskAsync(taskItemReference, cancellationToken);
await TaskQueue.RunTaskAsync(taskItemReference, stoppingToken);
_logger.LogDebug($"TaskItem completed.");
}
catch (Exception e) when (e is TaskCanceledException || e is OperationCanceledException)
Expand All @@ -63,4 +63,4 @@ public override async Task StopAsync(CancellationToken cancellationToken)
await base.StopAsync(cancellationToken);
_logger.LogDebug($"{nameof(BackgroundQueueService)} stopped.");
}
}
}
20 changes: 10 additions & 10 deletions Axuno.BackgroundTask/ConcurrentBackgroundQueueService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ public ConcurrentBackgroundQueueService(IBackgroundQueue taskQueue,
/// <summary>
/// Execute queued tasks.
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="stoppingToken"></param>
/// <returns>A <see cref="Task"/>.</returns>
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
lock (_locker)
{
Expand All @@ -54,10 +54,10 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)

try
{
while (!cancellationToken.IsCancellationRequested)
while (!stoppingToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(Config.PollQueueDelay, cancellationToken);
stoppingToken.ThrowIfCancellationRequested();
await Task.Delay(Config.PollQueueDelay, stoppingToken);

if (_concurrentTaskCount < Config.MaxConcurrentCount && TaskQueue?.Count > 0)
{
Expand All @@ -72,12 +72,12 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
stoppingToken.ThrowIfCancellationRequested();

// The service shall only be cancelled when the app shuts down
using (var taskCancellation = new CancellationTokenSource())
using (var combinedCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
CancellationTokenSource.CreateLinkedTokenSource(stoppingToken,
taskCancellation.Token))
{
var t = TaskQueue?.RunTaskAsync(taskListReference.Dequeue(),
Expand All @@ -88,7 +88,7 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
taskChunk.Add(t);
}

cancellationToken.ThrowIfCancellationRequested();
stoppingToken.ThrowIfCancellationRequested();
}
catch (Exception e)
{
Expand All @@ -111,7 +111,7 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
allTasks = Task.WhenAll(taskChunk);
// re-throws an AggregateException if one exists
// after waiting for the tasks to complete
await allTasks.WaitAsync(cancellationToken);
await allTasks.WaitAsync(stoppingToken);
}
catch (Exception e)
{
Expand Down Expand Up @@ -158,4 +158,4 @@ public override async Task StopAsync(CancellationToken cancellationToken)
await base.StopAsync(cancellationToken);
_logger.LogDebug($"{nameof(ConcurrentBackgroundQueueService)} stopped.");
}
}
}
4 changes: 2 additions & 2 deletions Axuno.BackgroundTask/ConsumeScopedServiceHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ private async Task DoWork(CancellationToken stoppingToken)
await scopedProcessingService.DoWork(stoppingToken);
}

public override async Task StopAsync(CancellationToken stoppingToken)
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is stopping.");

await Task.CompletedTask;
}
}
}
8 changes: 4 additions & 4 deletions Axuno.Tools/GeoSpatial/Location.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ private static double MakeSameSign(double source, double value)
return value;
}

private static Location? Parse(string input, IFormatProvider? provider, Regex regex)
private static Location? ParseLocation(string input, IFormatProvider? provider, Regex regex)
{
var match = regex.Match(input.Replace(", ", " "));
if (!match.Success) return null;
Expand Down Expand Up @@ -195,7 +195,7 @@ private static double MakeSameSign(double source, double value)
internal static Location? ParseDegrees(string value, IFormatProvider? provider)
{
if (string.IsNullOrWhiteSpace(value)) return null;
return Parse(value, provider, DegreeRegex);
return ParseLocation(value, provider, DegreeRegex);
}

/// <summary>
Expand All @@ -212,7 +212,7 @@ private static double MakeSameSign(double source, double value)
internal static Location? ParseDegreesMinutes(string value, IFormatProvider? provider)
{
if (string.IsNullOrWhiteSpace(value)) return null;
return Parse(value, provider, DegreeMinuteRegex);
return ParseLocation(value, provider, DegreeMinuteRegex);
}

/// <summary>
Expand All @@ -229,7 +229,7 @@ private static double MakeSameSign(double source, double value)
internal static Location? ParseDegreesMinutesSeconds(string value, IFormatProvider? provider)
{
if (string.IsNullOrWhiteSpace(value)) return null;
return Parse(value, provider, DegreeMinuteSecondRegex);
return ParseLocation(value, provider, DegreeMinuteSecondRegex);
}

/// <summary>
Expand Down
4 changes: 1 addition & 3 deletions League.Demo/Controllers/Home.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ namespace League.WebApp.Controllers;
public class Home : League.Controllers.AbstractController
{
private readonly TenantStore _tenantStore;
private readonly ILogger<Home> _logger;

public Home(TenantStore tenantStore, ILogger<Home> logger)
public Home(TenantStore tenantStore)
{
_tenantStore = tenantStore;
_logger = logger;
}

[Route("")]
Expand Down
6 changes: 3 additions & 3 deletions League.Tests/Identity/RoleStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ public void RoleConstants()
Assert.That(Constants.RoleName.GetTeamRelatedRoles(), Does.Contain(Constants.RoleName.TeamManager));
Assert.That(Constants.RoleName.GetTeamRelatedRoles(), Does.Contain(Constants.RoleName.Player));
Assert.That(Constants.RoleName.GetAllValues<string>().Any(rn => rn == Constants.RoleName.TournamentManager), Is.True);
Assert.That(Constants.RoleName.GetAllValues<string>().Any(rn => rn == Constants.RoleName.SystemManager), Is.True);
Assert.That(Constants.RoleName.GetAllNames(), Does.Contain(nameof(Constants.RoleName.TournamentManager)));
Assert.That(Constants.RoleName.GetAllRoleValues<string>().Any(rn => rn == Constants.RoleName.TournamentManager), Is.True);
Assert.That(Constants.RoleName.GetAllRoleValues<string>().Any(rn => rn == Constants.RoleName.SystemManager), Is.True);
Assert.That(Constants.RoleName.GetAllRoleNames(), Does.Contain(nameof(Constants.RoleName.TournamentManager)));
});
}

Expand Down
12 changes: 6 additions & 6 deletions League.Tests/Identity/UserClaimStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ public void ClaimConstants()
Assert.That(Constants.ClaimType.GetTeamRelatedClaimTypes(), Does.Contain(Constants.ClaimType.PlaysInTeam));
Assert.That(Constants.ClaimType.GetProgrammaticClaimTypes(), Does.Contain(Constants.ClaimType.ImpersonatedByUser));
Assert.That(Constants.ClaimType.GetAllValues<string>().Any(cn => cn == Constants.ClaimType.ManagesTeam), Is.True);
Assert.That(Constants.ClaimType.GetAllValues<string>().Any(cn => cn == Constants.ClaimType.PlaysInTeam), Is.True);
Assert.That(Constants.ClaimType.GetAllValues<string>().Any(cn => cn == Constants.ClaimType.ImpersonatedByUser), Is.True);
Assert.That(Constants.ClaimType.GetAllClaimTypeValues<string>().Any(cn => cn == Constants.ClaimType.ManagesTeam), Is.True);
Assert.That(Constants.ClaimType.GetAllClaimTypeValues<string>().Any(cn => cn == Constants.ClaimType.PlaysInTeam), Is.True);
Assert.That(Constants.ClaimType.GetAllClaimTypeValues<string>().Any(cn => cn == Constants.ClaimType.ImpersonatedByUser), Is.True);
Assert.That(Constants.ClaimType.GetAllNames(), Does.Contain(nameof(Constants.ClaimType.ManagesTeam)));
Assert.That(Constants.ClaimType.GetAllNames(), Does.Contain(nameof(Constants.ClaimType.PlaysInTeam)));
Assert.That(Constants.ClaimType.GetAllNames(), Does.Contain(nameof(Constants.ClaimType.ImpersonatedByUser)));
Assert.That(Constants.ClaimType.GetAllClaimTypeNames(), Does.Contain(nameof(Constants.ClaimType.ManagesTeam)));
Assert.That(Constants.ClaimType.GetAllClaimTypeNames(), Does.Contain(nameof(Constants.ClaimType.PlaysInTeam)));
Assert.That(Constants.ClaimType.GetAllClaimTypeNames(), Does.Contain(nameof(Constants.ClaimType.ImpersonatedByUser)));
});
}

Expand Down
2 changes: 1 addition & 1 deletion League.Tests/Identity/UserRoleStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public async Task OneTimeSetup()
await _appDb.GenericRepository.DeleteEntitiesUsingConstraintAsync<TeamEntity>(new PredicateExpression(), CancellationToken.None);

var roles = new EntityCollection<IdentityRoleEntity>();
foreach (var roleName in Constants.RoleName.GetAllValues<string>())
foreach (var roleName in Constants.RoleName.GetAllRoleValues<string>())
{
roles.Add(new IdentityRoleEntity { Name = roleName });
}
Expand Down
3 changes: 2 additions & 1 deletion League.Tests/IntegrationTests/BasicIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)

// Act
var response = await client.GetAsync(url);

// Assert
response.EnsureSuccessStatusCode(); // Status Code 200-299
Assert.That(response.IsSuccessStatusCode, Is.True);
}
}
2 changes: 0 additions & 2 deletions League/Components/RoundSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ namespace League.Components;

public class RoundSelector : ViewComponent
{
private readonly ITenantContext _tenantContext;
private readonly IAppDb _appDb;
private readonly ILogger<RoundSelector> _logger;

public RoundSelector(ITenantContext tenantContext, ILogger<RoundSelector> logger)
{
_tenantContext = tenantContext;
_appDb = tenantContext.DbContext.AppDb;
_logger = logger;
}
Expand Down
2 changes: 1 addition & 1 deletion League/Components/VenueSelectorComponentModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public enum Criteria
/// <summary>
/// Show all venues.
/// </summary>
AllVenues = 0,
None = 0,
/// <summary>
/// Show a selectable row for "venue not specified".
/// </summary>
Expand Down
12 changes: 6 additions & 6 deletions League/ControllerAttributes/TeamApplicationAllowedAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ namespace League.ControllerAttributes;

public class TeamApplicationAllowedAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
public override void OnActionExecuting(ActionExecutingContext context)
{
if (filterContext.HttpContext.RequestServices.GetService(typeof(ITenantContext)) is
if (context.HttpContext.RequestServices.GetService(typeof(ITenantContext)) is
ITenantContext tenantContext &&
(!tenantContext.TournamentContext.ApplicationAllowed && ((filterContext.RouteData.Values["controller"]?.ToString() ?? string.Empty)
(!tenantContext.TournamentContext.ApplicationAllowed && ((context.RouteData.Values["controller"]?.ToString() ?? string.Empty)
.Equals(nameof(League.Controllers.TeamApplication),
StringComparison.OrdinalIgnoreCase) &&
!(filterContext.RouteData.Values["action"]?.ToString() ?? string.Empty)
!(context.RouteData.Values["action"]?.ToString() ?? string.Empty)
.Equals(nameof(League.Controllers.TeamApplication.List),
StringComparison.OrdinalIgnoreCase)
)))
{
var tenantLink = filterContext.HttpContext.RequestServices.GetRequiredService<TenantLink>();
filterContext.Result = new RedirectResult(tenantLink.Action(nameof(Controllers.TeamApplication.List),
var tenantLink = context.HttpContext.RequestServices.GetRequiredService<TenantLink>();
context.Result = new RedirectResult(tenantLink.Action(nameof(Controllers.TeamApplication.List),
nameof(Controllers.TeamApplication))!);
}
}
Expand Down
8 changes: 1 addition & 7 deletions League/Controllers/Contact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,15 @@ namespace League.Controllers;

public class Contact : AbstractController
{
#pragma warning disable IDE0052 // Remove unread private members
private readonly IAppDb _appDb;
private readonly TenantStore _tenantStore;
#pragma warning restore IDE0052 // Remove unread private members
private readonly ITenantContext _tenantContext;
private readonly IStringLocalizer<Account> _localizer;
private readonly Axuno.BackgroundTask.IBackgroundQueue _queue;
private readonly SendEmailTask _sendEmailTask;
private readonly ILogger<Contact> _logger;

public Contact(ITenantContext tenantContext, TenantStore tenantStore, Axuno.BackgroundTask.IBackgroundQueue queue, SendEmailTask sendEmailTask, ILogger<Contact> logger, IStringLocalizer<Account> localizer)
public Contact(ITenantContext tenantContext, Axuno.BackgroundTask.IBackgroundQueue queue, SendEmailTask sendEmailTask, ILogger<Contact> logger, IStringLocalizer<Account> localizer)
{
_tenantContext = tenantContext;
_tenantStore = tenantStore;
_appDb = _tenantContext.DbContext.AppDb;
_queue = queue;
_sendEmailTask = sendEmailTask;
_logger = logger;
Expand Down
4 changes: 1 addition & 3 deletions League/Controllers/Error.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@ public class Error : AbstractController
private readonly ILogger _logger;
private readonly ILogger _notFoundLogger;
private readonly IStringLocalizer<Error> _localizer;
private readonly IWebHostEnvironment _environment;
private readonly ITenantContext _tenantContext;

public Error(ILogger<Error> logger, IStringLocalizer<Error> localizer, ILoggerFactory loggerFactory, IWebHostEnvironment environment, ITenantContext tenantContext)
public Error(ILogger<Error> logger, IStringLocalizer<Error> localizer, ILoggerFactory loggerFactory, ITenantContext tenantContext)
{
_logger = logger;
_environment = environment;
_tenantContext = tenantContext;
_localizer = localizer;
_notFoundLogger = loggerFactory.CreateLogger(nameof(League) + ".NotFound");
Expand Down
8 changes: 2 additions & 6 deletions League/Controllers/Map.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,18 @@ namespace League.Controllers;
[Route(TenantRouteConstraint.Template + "/[controller]")]
public class Map : AbstractController
{
private readonly IConfiguration _configuration;
private readonly ILogger<Map> _logger;
private readonly ITenantContext _tenantContext;
private readonly IAppDb _appDb;
private readonly IStringLocalizer<Map> _localizer;
private readonly GoogleConfiguration _googleConfig;

public Map(ITenantContext tenantContext, IConfiguration configuration, IStringLocalizer<Map> localizer, ILogger<Map> logger)
public Map(ITenantContext tenantContext, IConfiguration configuration, ILogger<Map> logger)
{
_tenantContext = tenantContext;
_appDb = tenantContext.DbContext.AppDb;
_configuration = configuration;
_localizer = localizer;
_logger = logger;
_googleConfig = new GoogleConfiguration();
_configuration.Bind(nameof(GoogleConfiguration), _googleConfig);
configuration.Bind(nameof(GoogleConfiguration), _googleConfig);
}

[Route("")]
Expand Down
4 changes: 2 additions & 2 deletions League/Controllers/Ranking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private async Task<List<RankingListRow>> GetRankingListCached(CancellationToken
cache =>
{
cache.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30);
var tokenSource = new CancellationTokenSource();
using var tokenSource = new CancellationTokenSource();
var token = new CancellationChangeToken(tokenSource.Token);
cache.AddExpirationToken(token);
return _appDb.RankingRepository.GetRankingListAsync(
Expand All @@ -143,7 +143,7 @@ private async Task<List<RoundLegPeriodRow>> GetRoundLegPeriodsCached(List<Rankin
nameof(RoundLegPeriodRow)), cache =>
{
cache.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30);
var tokenSource = new CancellationTokenSource();
using var tokenSource = new CancellationTokenSource();
var token = new CancellationChangeToken(tokenSource.Token);
cache.AddExpirationToken(token);
return (_appDb.RoundRepository.GetRoundLegPeriodAsync(
Expand Down
3 changes: 1 addition & 2 deletions League/Controllers/Role.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class Role : AbstractController
private readonly IAuthorizationService _authorizationService;
private readonly IStringLocalizer<Role> _localizer;
private readonly ILogger<Role> _logger;
private readonly ILoggerFactory _loggerFactory;

private const string _defaultReturnUrl = "/";

public Role(ITenantContext tenantContext,
Expand All @@ -30,7 +30,6 @@ public Role(ITenantContext tenantContext,
_signInManager = signInManager;
_authorizationService = authorizationService;
_localizer = localizer;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<Role>();
}

Expand Down
Loading

0 comments on commit 4fa64ea

Please sign in to comment.