diff --git a/Axuno.BackgroundTask/BackgroundQueue.cs b/Axuno.BackgroundTask/BackgroundQueue.cs index 5902cfb0..36d18670 100644 --- a/Axuno.BackgroundTask/BackgroundQueue.cs +++ b/Axuno.BackgroundTask/BackgroundQueue.cs @@ -37,7 +37,7 @@ public void QueueTask(IBackgroundTask taskItem) TaskItems.Enqueue(taskItem); _signal.Release(); // increase the semaphore count for each item - _logger.LogDebug("Number of queued TaskItems is {taskItemCount}", _signal.CurrentCount); + _logger.LogDebug("Number of queued TaskItems is {TaskItemCount}", _signal.CurrentCount); } /// @@ -46,7 +46,7 @@ public void QueueTask(IBackgroundTask taskItem) /// Returns the next from the queue. public IBackgroundTask DequeueTask() { - if (TaskItems.TryDequeue(out var nextTaskItem)) + if (TaskItems.TryDequeue(out var nextTaskItem)) return nextTaskItem; _logger.LogDebug("No TaskItem could be dequeued."); @@ -72,20 +72,17 @@ public async Task RunTaskAsync(IBackgroundTask? task, CancellationToken cancella } catch (Exception e) when (e is TaskCanceledException || e is OperationCanceledException) { - _logger.LogError(e, $"Task canceled when executing a {nameof(IBackgroundTask)}."); // _onException will deliberately not be called throw; } catch (Exception e) when (e is TimeoutException) { - _logger.LogError(e, $"Task timed out."); - _onException?.Invoke(e); + _onException.Invoke(e); throw; } catch (Exception e) { - _logger.LogError(e, $"Exception when executing a {nameof(IBackgroundTask)}. "); - _onException?.Invoke(e); + _onException.Invoke(e); throw; } finally diff --git a/League.Demo/Program.cs b/League.Demo/Program.cs index bfcc24c1..def05c84 100644 --- a/League.Demo/Program.cs +++ b/League.Demo/Program.cs @@ -57,7 +57,6 @@ public static async Task Main(string[] args) catch (Exception e) { logger.Fatal(e, "Application stopped after Exception."); - throw; } finally { diff --git a/League.Demo/Seed/Create-Db-Objects.sql b/League.Demo/Seed/Create-Db-Objects.sql index 8d54ce0d..0a905c75 100644 --- a/League.Demo/Seed/Create-Db-Objects.sql +++ b/League.Demo/Seed/Create-Db-Objects.sql @@ -1,3 +1,4 @@ +/* @Generated by a tool */ /****** Object: UserDefinedFunction [dbo].[GetSetsAsText] Script Date: 06.08.2023 20:51:06 ******/ SET ANSI_NULLS ON GO diff --git a/League.Demo/Seed/Insert-Initial-Data.sql b/League.Demo/Seed/Insert-Initial-Data.sql index 6ece1c6c..f7bfb707 100644 --- a/League.Demo/Seed/Insert-Initial-Data.sql +++ b/League.Demo/Seed/Insert-Initial-Data.sql @@ -1,3 +1,4 @@ +/* @Generated by a tool */ /* Data for the 'dbo.IdentityRole' table (Records 1 - 2) */ SET IDENTITY_INSERT dbo.IdentityRole ON; diff --git a/League.Demo/ViewComponents/CustomMainNavigationNodeBuilder.cs b/League.Demo/ViewComponents/CustomMainNavigationNodeBuilder.cs index 332d3462..dbc2225b 100644 --- a/League.Demo/ViewComponents/CustomMainNavigationNodeBuilder.cs +++ b/League.Demo/ViewComponents/CustomMainNavigationNodeBuilder.cs @@ -14,7 +14,7 @@ namespace League.WebApp.ViewComponents; public class CustomMainNavigationNodeBuilder : MainNavigationNodeBuilder { /// - public CustomMainNavigationNodeBuilder(TenantStore tenantStore, ITenantContext tenantContext, IAuthorizationService authorizationService, TenantLink tenantUrlHelper, IStringLocalizer localizer, ILogger logger) : base(tenantStore, tenantContext, authorizationService, tenantUrlHelper, localizer, logger) + public CustomMainNavigationNodeBuilder(TenantStore tenantStore, ITenantContext tenantContext, IAuthorizationService authorizationService, TenantLink tenantUrlHelper, IStringLocalizer localizer, ILogger logger) : base(tenantStore, tenantContext, authorizationService, tenantUrlHelper, localizer, logger) { } /// diff --git a/League.Tests/Identity/RoleStoreTests.cs b/League.Tests/Identity/RoleStoreTests.cs index 220a81c6..b5691fdd 100644 --- a/League.Tests/Identity/RoleStoreTests.cs +++ b/League.Tests/Identity/RoleStoreTests.cs @@ -131,8 +131,8 @@ await da.ExecuteSQLAsync(CancellationToken.None, _appDb.DbContext.CommandTimeOut = 2; // new claim var claim = new Claim(Constants.ClaimType.ManagesTeam, "y", "z"); - Assert.ThrowsAsync(() => _roleStore.AddClaimAsync(role, claim, CancellationToken.None)); - Assert.ThrowsAsync(() => _roleStore.RemoveClaimAsync(role, claim, CancellationToken.None)); + Assert.ThrowsAsync(() => _roleStore.AddClaimAsync(role, claim, CancellationToken.None)); + Assert.ThrowsAsync(() => _roleStore.RemoveClaimAsync(role, claim, CancellationToken.None)); da.Rollback("transaction1"); } _appDb.DbContext.CommandTimeOut = currentTimeOut; diff --git a/League.Tests/Identity/UserAuthenticationTokenStoreTests.cs b/League.Tests/Identity/UserAuthenticationTokenStoreTests.cs index 78397a15..cd7cc292 100644 --- a/League.Tests/Identity/UserAuthenticationTokenStoreTests.cs +++ b/League.Tests/Identity/UserAuthenticationTokenStoreTests.cs @@ -108,7 +108,7 @@ await da.ExecuteSQLAsync(CancellationToken.None, $"SELECT 1 FROM [{_appDb.DbContext.Schema}].[{da.GetPersistentTableName(new IdentityUserLoginEntity())}] WITH (TABLOCKX)"); // Trying to update will fail because the table is locked _appDb.DbContext.CommandTimeOut = 2; - Assert.ThrowsAsync(async () => await _store.SetTokenAsync(GetNewUser(), "Provider", "TokenName", "TheValue", CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.SetTokenAsync(GetNewUser(), "Provider", "TokenName", "TheValue", CancellationToken.None)); Assert.ThrowsAsync(async () => await _store.RemoveTokenAsync(GetNewUser(), "Provider", "TokenName", CancellationToken.None)); da.Rollback("transaction1"); } diff --git a/League.Tests/Identity/UserClaimStoreTests.cs b/League.Tests/Identity/UserClaimStoreTests.cs index 4d352807..e036c491 100644 --- a/League.Tests/Identity/UserClaimStoreTests.cs +++ b/League.Tests/Identity/UserClaimStoreTests.cs @@ -69,9 +69,9 @@ await da.ExecuteSQLAsync(CancellationToken.None, _appDb.DbContext.CommandTimeOut = 2; // new claim var claim = new Claim("type", "value", "valueType", "issuer"); - Assert.ThrowsAsync(async () => await _store.AddClaimsAsync(_user, new[] { claim }, CancellationToken.None)); - Assert.ThrowsAsync(async () => await _store.RemoveClaimsAsync(_user, new[] { claim }, CancellationToken.None)); - Assert.ThrowsAsync(async () => await _store.ReplaceClaimAsync(_user, claim, claim, CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.AddClaimsAsync(_user, new[] { claim }, CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.RemoveClaimsAsync(_user, new[] { claim }, CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.ReplaceClaimAsync(_user, claim, claim, CancellationToken.None)); da.Rollback("transaction1"); } _appDb.DbContext.CommandTimeOut = currentTimeOut; @@ -148,10 +148,10 @@ public async Task Add_and_Remove_Manager_Claim() var claim = new Claim(Constants.ClaimType.ManagesTeam, _team.Id.ToString()); await _store.AddClaimsAsync(_user, new[] { claim }, CancellationToken.None); // non-existent team should throw - Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, + Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, new [] {new Claim(Constants.ClaimType.ManagesTeam, "0")}, CancellationToken.None)); // not implemented claim - should throw - Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, + Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, new [] { new Claim(Constants.ClaimType.NotImplementedClaim, _team.Id.ToString()) }, CancellationToken.None)); // same manager claim again - should not be added @@ -165,10 +165,10 @@ public async Task Add_and_Remove_Manager_Claim() claims = await _store.GetClaimsAsync(_user, CancellationToken.None); Assert.That(claims.FirstOrDefault(c => c.Type == claim.Type && c.Value == claim.Value), Is.EqualTo(null)); // non-existent team should throw - Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, + Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, new [] { new Claim(Constants.ClaimType.ManagesTeam, "0") }, CancellationToken.None)); // not implemented claim - should throw - Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, + Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, new [] { new Claim(Constants.ClaimType.NotImplementedClaim, _team.Id.ToString()) }, CancellationToken.None)); // replace manager should fail @@ -229,14 +229,14 @@ public void Add_and_Replace_and_Remove_Programmatic_Claim() { // Programmatic claims cannot be stored var claim = new Claim(Constants.ClaimType.ImpersonatedByUser, "123", "valueType", "issuer"); - Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, new []{claim}, CancellationToken.None)); + Assert.ThrowsAsync(() => _store.AddClaimsAsync(_user, new []{claim}, CancellationToken.None)); // Programmatic claims cannot be replaced Assert.ThrowsAsync(() => _store.ReplaceClaimAsync(_user, claim, new Claim("type", "value"), CancellationToken.None)); Assert.ThrowsAsync(() => _store.ReplaceClaimAsync(_user, new Claim("type", "value"), claim, CancellationToken.None)); // Programmatic claims cannot be removed - Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, new []{ claim }, CancellationToken.None)); + Assert.ThrowsAsync(() => _store.RemoveClaimsAsync(_user, new []{ claim }, CancellationToken.None)); } #endregion diff --git a/League.Tests/Identity/UserLoginStoreTests.cs b/League.Tests/Identity/UserLoginStoreTests.cs index 35245d83..b86a4e80 100644 --- a/League.Tests/Identity/UserLoginStoreTests.cs +++ b/League.Tests/Identity/UserLoginStoreTests.cs @@ -126,8 +126,8 @@ await da.ExecuteSQLAsync(CancellationToken.None, $"SELECT 1 FROM [{_appDb.DbContext.Schema}].[{da.GetPersistentTableName(new IdentityUserLoginEntity())}] WITH (TABLOCKX)"); // Trying to update will fail because the table is locked _appDb.DbContext.CommandTimeOut = 2; - Assert.ThrowsAsync(async () => await _store.AddLoginAsync(GetNewUser(), GetUserLoginInfo() , CancellationToken.None)); - Assert.ThrowsAsync(async () => await _store.RemoveLoginAsync(GetNewUser(), "x", "y", CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.AddLoginAsync(GetNewUser(), GetUserLoginInfo() , CancellationToken.None)); + Assert.ThrowsAsync(async () => await _store.RemoveLoginAsync(GetNewUser(), "x", "y", CancellationToken.None)); da.Rollback("transaction1"); } _appDb.DbContext.CommandTimeOut = currentTimeOut; diff --git a/League.Tests/TestComponents/UnitTestHelpers.cs b/League.Tests/TestComponents/UnitTestHelpers.cs index ceb91787..6699fbbb 100644 --- a/League.Tests/TestComponents/UnitTestHelpers.cs +++ b/League.Tests/TestComponents/UnitTestHelpers.cs @@ -82,7 +82,7 @@ public UserStore GetUserStore() public RoleStore GetRoleStore() { - return new RoleStore(_tenantContext, new NullLogger(), new UpperInvariantLookupNormalizer(), new Mock(null!).Object); + return new League.Identity.RoleStore(_tenantContext, new NullLogger(), new UpperInvariantLookupNormalizer(), new Mock(null!).Object); } public ServiceProvider GetStandardServiceProvider() diff --git a/League/ApiControllers/Cron.cs b/League/ApiControllers/Cron.cs index c6ec90e3..212e5f0b 100644 --- a/League/ApiControllers/Cron.cs +++ b/League/ApiControllers/Cron.cs @@ -89,7 +89,7 @@ public async Task RunAllAutoMails(string key) } catch (AggregateException e) { - _logger.LogCritical("Failure invoking automail urls. {exception}", e); + _logger.LogCritical(e, "Failure invoking automail Urls."); } return Ok(results); @@ -227,7 +227,7 @@ private async Task InvokeUrl(string urlSegmentValue) routeValues, scheme: Uri.UriSchemeHttps) ?? string.Empty; var result = await httpClient.GetAsync(url); - _logger.LogInformation("Get request for url '{url}' completed.", url); + _logger.LogInformation("Get request for url '{Url}' completed.", url); return new InvocationResult { Success = true, Url = url, diff --git a/League/Areas/Admin/Controllers/Impersonation.cs b/League/Areas/Admin/Controllers/Impersonation.cs index f7e80ad4..cff64cf6 100644 --- a/League/Areas/Admin/Controllers/Impersonation.cs +++ b/League/Areas/Admin/Controllers/Impersonation.cs @@ -15,11 +15,11 @@ namespace League.Areas.Admin.Controllers; [Route(TenantRouteConstraint.Template + "/[area]/[controller]")] public class Impersonation : AbstractController { - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly SignInManager _signInManager; private readonly ITenantContext _tenantContext; - public Impersonation(SignInManager signInManager, ITenantContext tenantContext, ILogger logger) + public Impersonation(SignInManager signInManager, ITenantContext tenantContext, ILogger logger) { _signInManager = signInManager; _tenantContext = tenantContext; @@ -65,7 +65,7 @@ public async Task Start(long id) // impersonate the target user await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, targetClaimsPrincipal); - _logger.LogInformation("User '{user}' now impersonates user '{targetUser}'.", + _logger.LogInformation("User '{User}' now impersonates user '{TargetUser}'.", currentUser.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value, targetClaimsPrincipal?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value); diff --git a/League/BackgroundTasks/SendEmailTask.cs b/League/BackgroundTasks/SendEmailTask.cs index 0f593ee4..065b6642 100644 --- a/League/BackgroundTasks/SendEmailTask.cs +++ b/League/BackgroundTasks/SendEmailTask.cs @@ -2,6 +2,7 @@ using Axuno.TextTemplating; using League.Emailing.Creators; using League.Templates.Email.Localization; +using MailMergeLib; using MailMergeLib.AspNet; using TournamentManager.MultiTenancy; @@ -53,7 +54,7 @@ public void SetMessageCreator(IMailMessageCreator mailMessageCreator) { _mailMessageCreator = mailMessageCreator; } - + /// /// Invokes the and sends the mail messages. /// @@ -69,18 +70,22 @@ public async Task RunAsync(CancellationToken cancellationToken) { await _mailMergeService.Sender.SendAsync(mmm, null); } - catch (Exception e) when (e is TaskCanceledException || e is OperationCanceledException) + catch (Exception e) when (e is TaskCanceledException) + { + _mailMergeService.Sender.SendCancel(); + throw new TaskCanceledException( + $"Sending mail canceled. {mmm.MailMergeAddresses}\nSubject: {mmm.Subject}\nMessage: {mmm.PlainText}", e, cancellationToken); + } + catch (Exception e) when (e is OperationCanceledException) { - _logger.LogError(e, "Sending mail canceled. {recipients}\nSubject: {subject}\nMessage: {message}", - mmm.MailMergeAddresses, mmm.Subject, mmm.PlainText); _mailMergeService.Sender.SendCancel(); - throw; + throw new OperationCanceledException( + $"Sending mail canceled. {mmm.MailMergeAddresses}\nSubject: {mmm.Subject}\nMessage: {mmm.PlainText}", e, cancellationToken); } catch (Exception e) { - _logger.LogError(e, "Mail sender failure. {recipients}\nSubject: {subject}\nMessage: {message}", - mmm.MailMergeAddresses, mmm.Subject, mmm.PlainText); - throw; + throw new MailMergeMessage.MailMergeMessageException( + $"Mail sender failure. {mmm.MailMergeAddresses}\nSubject: {mmm.Subject}\nMessage: {mmm.PlainText}", new []{e}, null); } } } diff --git a/League/Controllers/Contact.cs b/League/Controllers/Contact.cs index d9c02639..a42497bf 100644 --- a/League/Controllers/Contact.cs +++ b/League/Controllers/Contact.cs @@ -61,7 +61,7 @@ public IActionResult Index(ContactViewModel model) } SendEmail(model); - _logger.LogDebug("Mail sent: {@model}", model); + _logger.LogDebug("Mail sent: {Model}", model); return _tenantContext.IsDefault ? RedirectToRoute(RouteNames.GeneralContactConfirmation) diff --git a/League/Controllers/Error.cs b/League/Controllers/Error.cs index 55f136b4..a4fd1d00 100644 --- a/League/Controllers/Error.cs +++ b/League/Controllers/Error.cs @@ -8,7 +8,7 @@ namespace League.Controllers; public class Error : AbstractController { private readonly ILogger _logger; - private readonly ILogger _notFoundLogger; + private readonly ILogger _loggerNotFound; //NOSONAR private readonly IStringLocalizer _localizer; private readonly ITenantContext _tenantContext; @@ -17,7 +17,7 @@ public Error(ILogger logger, IStringLocalizer localizer, ILoggerFa _logger = logger; _tenantContext = tenantContext; _localizer = localizer; - _notFoundLogger = loggerFactory.CreateLogger(nameof(League) + ".NotFound"); + _loggerNotFound = loggerFactory.CreateLogger(nameof(League) + ".NotFound"); } [Route("{id?}")] @@ -40,7 +40,7 @@ public IActionResult Index(string? id) { viewModel.OrigPath = exceptionFeature?.Path; viewModel.Exception = exceptionFeature?.Error; - _logger.LogError(viewModel.Exception, "Path: {origPath}", viewModel.OrigPath); + _logger.LogError(viewModel.Exception, "Path: {OrigPath}", viewModel.OrigPath); } else { @@ -48,7 +48,7 @@ public IActionResult Index(string? id) .Get()?.OriginalPath ?? string.Empty; if (Response.StatusCode == 404) - _notFoundLogger.LogInformation("{NotFound}", new {Status = Response.StatusCode, Ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1", Path = viewModel.OrigPath}); + _loggerNotFound.LogInformation("{NotFound}", new {Status = Response.StatusCode, Ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1", Path = viewModel.OrigPath}); else _logger.LogWarning("StatusCode: {StatusCode}, Path: {OrigPath}", Response.StatusCode, viewModel.OrigPath); } diff --git a/League/Controllers/Manage.cs b/League/Controllers/Manage.cs index 0a53bd63..c3dc5d81 100644 --- a/League/Controllers/Manage.cs +++ b/League/Controllers/Manage.cs @@ -18,6 +18,8 @@ namespace League.Controllers; [Route(TenantRouteConstraint.Template + "/[controller]")] public class Manage : AbstractController { + private const string UserNotFoundInRepository = "Username '{UserName}' not found in repository"; + private readonly UserManager _userManager; private readonly SignInManager _signInManager; private readonly IStringLocalizer _localizer; @@ -91,7 +93,7 @@ public async Task ChangeUserName() var user = await GetCurrentUserAsync(); if (user == null) { - _logger.LogError("Username '{userName}' not found in repository", HttpContext.User.Identity?.Name); + _logger.LogError(UserNotFoundInRepository, HttpContext.User.Identity?.Name); ModelState.AddModelError(string.Empty, _localizer["'{0}' not found", _metaData.GetDisplayName(nameof(ChangeUsernameViewModel.Username)) ?? string.Empty]); return PartialView(ViewNames.Manage._ChangeUsernameModalPartial, model); } @@ -122,7 +124,7 @@ public async Task ChangeUserName(ChangeUsernameViewModel model) if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); - _logger.LogInformation("User Id '{userId}' changed the username successfully.", user.Id); + _logger.LogInformation("User Id '{UserId}' changed the username successfully.", user.Id); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Success, MessageId = MessageId.ChangeUsernameSuccess }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -144,7 +146,7 @@ public async Task ChangeEmail() var user = await GetCurrentUserAsync(); if (user == null) { - _logger.LogError("User id '{userId}' not found in repository", GetCurrentUserId()); + _logger.LogError("User id '{UserId}' not found in repository", GetCurrentUserId()); ModelState.AddModelError(string.Empty, _localizer["'{0}' not found", _metaData.GetDisplayName(nameof(ChangeEmailViewModel.Email)) ?? string.Empty]); return PartialView(ViewNames.Manage._ChangeEmailModalPartial, model); } @@ -172,7 +174,7 @@ public async Task ChangeEmail(ChangeEmailViewModel model) if (user.NormalizedEmail == _userManager.KeyNormalizer.NormalizeEmail(model.Email)) { - _logger.LogInformation("Current and new email are equal ('{email}').", model.Email); + _logger.LogInformation("Current and new email are equal ('{Email}').", model.Email); ModelState.AddModelError(nameof(ChangeEmailViewModel.Email), _localizer["Current and new email must be different"]); return PartialView(ViewNames.Manage._ChangeEmailModalPartial, model); } @@ -213,7 +215,7 @@ public async Task EditEmail2() var user = await GetCurrentUserAsync(); if (user == null) { - _logger.LogError("User id '{userId}' not found in repository", GetCurrentUserId()); + _logger.LogError("User id '{USserId}' not found in repository", GetCurrentUserId()); ModelState.AddModelError(string.Empty, _localizer["'{0}' not found", _metaData.GetDisplayName(nameof(EditEmail2ViewModel.Email2)) ?? string.Empty]); return PartialView(ViewNames.Manage._EditEmail2ModalPartial, model); } @@ -253,7 +255,7 @@ public async Task EditEmail2(EditEmail2ViewModel model, Cancellat if (_userManager.KeyNormalizer.NormalizeEmail(userEntity.Email) == _userManager.KeyNormalizer.NormalizeEmail(model.Email2)) { - _logger.LogInformation("Primary and additional email are equal ('{userEmail}').", userEntity.Email); + _logger.LogInformation("Primary and additional email are equal ('{UserEmail}').", userEntity.Email); ModelState.AddModelError(nameof(EditEmail2ViewModel.Email2), _localizer["'{0}' and '{1}' must be different", _metaData.GetDisplayName(nameof(EditEmail2ViewModel.Email2)) ?? string.Empty, _metaData.GetDisplayName(nameof(ChangeEmailViewModel.Email)) ?? string.Empty]); return PartialView(ViewNames.Manage._EditEmail2ModalPartial, model); } @@ -267,7 +269,7 @@ public async Task EditEmail2(EditEmail2ViewModel model, Cancellat } catch (Exception e) { - _logger.LogError(e, "Save user name '{userName}' failed", userEntity.UserName); + _logger.LogError(e, "Save user name '{UserName}' failed", userEntity.UserName); return PartialView(ViewNames.Manage._EditEmail2ModalPartial, model); } } @@ -300,7 +302,7 @@ public async Task ChangePassword(ChangePasswordViewModel model) if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); - _logger.LogInformation("User Id '{userId}' changed the password successfully.", user.Id); + _logger.LogInformation("User Id '{UserId}' changed the password successfully.", user.Id); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Success, MessageId = MessageId.ChangePasswordSuccess }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -352,7 +354,7 @@ public async Task EditPersonalDetails(CancellationToken cancellat var user = await _tenantContext.DbContext.AppDb.UserRepository.GetLoginUserByUserNameAsync(HttpContext.User.Identity?.Name ?? string.Empty, cancellationToken); if (user == null) { - _logger.LogError("User id '{userId}' not found in repository", GetCurrentUserId()); + _logger.LogError("User id '{UserId}' not found in repository", GetCurrentUserId()); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePersonalDetailsFailure }); ModelState.AddModelError(string.Empty, _localizer["Personal details not found"]); return PartialView(ViewNames.Manage._EditPersonalDetailsModalPartial, model); @@ -378,7 +380,7 @@ public async Task EditPersonalDetails(PersonalDetailsViewModel mo var user = await _tenantContext.DbContext.AppDb.UserRepository.GetLoginUserByUserNameAsync(HttpContext.User.Identity?.Name ?? string.Empty, cancellationToken); if (user == null) { - _logger.LogError("Username '{userName}' not found in repository", HttpContext.User.Identity?.Name ?? string.Empty); + _logger.LogError(UserNotFoundInRepository, HttpContext.User.Identity?.Name ?? string.Empty); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePersonalDetailsFailure }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -393,12 +395,12 @@ public async Task EditPersonalDetails(PersonalDetailsViewModel mo } catch (Exception e) { - _logger.LogError(e, "Failure saving personal data for user id '{userId}'", GetCurrentUserId()); + _logger.LogError(e, "Failure saving personal data for user id '{UserId}'", GetCurrentUserId()); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePersonalDetailsFailure }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } - _logger.LogInformation("Personal data for user id '{userId}' updated", GetCurrentUserId()); + _logger.LogInformation("Personal data for user id '{UserId}' updated", GetCurrentUserId()); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Success, MessageId = MessageId.ChangePersonalDetailsSuccess }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -410,7 +412,7 @@ public async Task EditPhoneNumber(CancellationToken cancellationT var user = await _tenantContext.DbContext.AppDb.UserRepository.GetLoginUserByUserNameAsync(HttpContext.User.Identity?.Name ?? string.Empty, cancellationToken); if (user == null) { - _logger.LogError("Username '{userName}' not found in repository", HttpContext.User.Identity?.Name ?? string.Empty); + _logger.LogError(UserNotFoundInRepository, HttpContext.User.Identity?.Name ?? string.Empty); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePhoneFailure }); ModelState.AddModelError(string.Empty, _localizer["Primary phone number not found"]); return PartialView(ViewNames.Manage._EditPhoneModalPartial, model); @@ -437,7 +439,7 @@ async Task Save() } catch (Exception e) { - _logger.LogError(e, "Save user name '{userName}' failed", userEntity.UserName); + _logger.LogError(e, "Save user name '{UserName}' failed", userEntity.UserName); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePhoneFailure }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -481,14 +483,14 @@ async Task Save() if (_phoneNumberService.IsMatch(userEntity.PhoneNumber, model.PhoneNumber, _regionInfo.TwoLetterISORegionName)) { - _logger.LogInformation("Current and new primary phone number are equal ('{phoneNumber}').", userEntity.PhoneNumber); + _logger.LogInformation("Current and new primary phone number are equal ('{PhoneNumber}').", userEntity.PhoneNumber); ModelState.AddModelError(nameof(EditPhoneViewModel.PhoneNumber), _localizer["Current and new primary phone number must be different"]); return PartialView(ViewNames.Manage._EditPhoneModalPartial, model); } if (_phoneNumberService.IsMatch(userEntity.PhoneNumber2, model.PhoneNumber, _regionInfo.TwoLetterISORegionName)) { - _logger.LogInformation("Primary and additional phone number are equal ('{phoneNumber}').", userEntity.PhoneNumber); + _logger.LogInformation("Primary and additional phone number are equal ('{PhoneNumber}').", userEntity.PhoneNumber); ModelState.AddModelError(nameof(EditPhone2ViewModel.PhoneNumber2), _localizer["'{0}' and '{1}' must be different", _metaData.GetDisplayName(nameof(EditPhoneViewModel.PhoneNumber)) ?? string.Empty, _metaData.GetDisplayName(nameof(EditPhone2ViewModel.PhoneNumber2)) ?? string.Empty]); return PartialView(ViewNames.Manage._EditPhoneModalPartial, model); } @@ -503,7 +505,7 @@ public async Task EditPhoneNumber2(CancellationToken cancellation var user = await _tenantContext.DbContext.AppDb.UserRepository.GetLoginUserByUserNameAsync(HttpContext.User.Identity?.Name ?? string.Empty, cancellationToken); if (user == null) { - _logger.LogError("Username '{userName}' not found in repository", HttpContext.User.Identity?.Name ?? string.Empty); + _logger.LogError(UserNotFoundInRepository, HttpContext.User.Identity?.Name ?? string.Empty); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePhone2Failure }); ModelState.AddModelError(string.Empty, _localizer["'{0}' not found", _metaData.GetDisplayName(nameof(EditPhone2ViewModel.PhoneNumber2)) ?? string.Empty]); return PartialView(ViewNames.Manage._EditPhone2ModalPartial, model); @@ -529,7 +531,7 @@ async Task Save() } catch (Exception e) { - _logger.LogError(e, "Save user name '{userName}' failed", userEntity.UserName); + _logger.LogError(e, "Save user name '{UserName}' failed", userEntity.UserName); TempData.Put(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangePhone2Failure }); return JsonResponseRedirect(TenantLink.Action(nameof(Index), nameof(Manage))); } @@ -573,7 +575,7 @@ async Task Save() if (_phoneNumberService.IsMatch(userEntity.PhoneNumber, model.PhoneNumber2, _regionInfo.TwoLetterISORegionName)) { - _logger.LogInformation("Primary and additional phone number are equal ('{phoneNumber}').", userEntity.PhoneNumber); + _logger.LogInformation("Primary and additional phone number are equal ('{PhoneNumber}').", userEntity.PhoneNumber); ModelState.AddModelError(nameof(EditPhone2ViewModel.PhoneNumber2), _localizer["'{0}' and '{1}' must be different", _metaData.GetDisplayName(nameof(EditPhone2ViewModel.PhoneNumber2)) ?? string.Empty, _metaData.GetDisplayName(nameof(EditPhoneViewModel.PhoneNumber)) ?? string.Empty]); return PartialView(ViewNames.Manage._EditPhone2ModalPartial, model); } @@ -674,7 +676,7 @@ public async Task DeleteAccountConfirmed() var result = await _userManager.DeleteAsync(user); if (!result.Succeeded) { - _logger.LogError("Account for user id '{userId}' could not be deleted.", user.Id); + _logger.LogError("Account for user id '{UserId}' could not be deleted.", user.Id); } } await _signInManager.SignOutAsync(); diff --git a/League/Controllers/Map.cs b/League/Controllers/Map.cs index 57ca6dd5..b8113a44 100644 --- a/League/Controllers/Map.cs +++ b/League/Controllers/Map.cs @@ -39,7 +39,7 @@ public async Task Index(CancellationToken cancellationToken) }; if (model.Tournament == null) { - _logger.LogError("{variable} '{value}' does not exist", nameof(_tenantContext.TournamentContext.MapTournamentId), _tenantContext.TournamentContext.MapTournamentId); + _logger.LogError("{Variable} '{Value}' does not exist", nameof(_tenantContext.TournamentContext.MapTournamentId), _tenantContext.TournamentContext.MapTournamentId); } return View(Views.ViewNames.Map.Index, model); } @@ -62,7 +62,7 @@ public async Task Venue(long id, CancellationToken cancellationTo }; if (model.Tournament == null) { - _logger.LogError("{variable} '{value}' does not exist", nameof(_tenantContext.TournamentContext.MapTournamentId), _tenantContext.TournamentContext.MapTournamentId); + _logger.LogError("{Variable} '{Value}' does not exist", nameof(_tenantContext.TournamentContext.MapTournamentId), _tenantContext.TournamentContext.MapTournamentId); } return View(Views.ViewNames.Map.Index, model); diff --git a/League/Controllers/Match.cs b/League/Controllers/Match.cs index 403a7e80..1c8e29b7 100644 --- a/League/Controllers/Match.cs +++ b/League/Controllers/Match.cs @@ -307,7 +307,7 @@ public async Task EnterResult(long id, CancellationToken cancella catch (Exception e) { _logger.LogError(e, "Building {Model} failed for MatchId '{MatchId}'", nameof(EnterResultViewModel), id); - throw; + return Forbid(); } } @@ -379,7 +379,7 @@ public async Task EnterResult([FromForm] EnterResultViewModel? mo catch (Exception e) { _logger.LogError(e, "Building {Model} failed for MatchId '{ModelId}'. User ID '{CurrentUser}'", nameof(EnterResultViewModel), model?.Id, GetCurrentUserId()); - throw; + return Forbid(); } try diff --git a/League/Controllers/Ranking.cs b/League/Controllers/Ranking.cs index 0a0ae12a..196a9f76 100644 --- a/League/Controllers/Ranking.cs +++ b/League/Controllers/Ranking.cs @@ -63,7 +63,7 @@ await _appDb.TournamentRepository.GetTournamentAsync(new PredicateExpression(Tou if (model.Tournament == null) { - _logger.LogError("{name} '{id}' does not exist. User ID '{currentUser}'.", nameof(_tenantContext.TournamentContext.MatchPlanTournamentId), _tenantContext.TournamentContext.MatchResultTournamentId, GetCurrentUserId()); + _logger.LogError("{Name} '{Id}' does not exist. User ID '{CurrentUser}'.", nameof(_tenantContext.TournamentContext.MatchPlanTournamentId), _tenantContext.TournamentContext.MatchResultTournamentId, GetCurrentUserId()); return NotFound(); } @@ -93,8 +93,8 @@ public async Task AllTimeTournament(long?id, CancellationToken ca } catch (Exception e) { - _logger.LogError(e, $"Error when creating the {nameof(AllTimeTournament)} table"); - throw; + _logger.LogError(e, "Error when creating the {AllTimeTournament} table", nameof(AllTimeTournament)); + return NotFound(); } } @@ -114,8 +114,8 @@ public async Task AllTimeTeam(long? id, CancellationToken cancell } catch (Exception e) { - _logger.LogError(e, $"Error when creating the {nameof(AllTimeTeam)} table"); - throw; + _logger.LogError(e, "Error when creating the {AllTimeTeam} table", nameof(AllTimeTeam)); + return NotFound(); } } diff --git a/League/Controllers/Role.cs b/League/Controllers/Role.cs index 031e7fa9..7206ba6d 100644 --- a/League/Controllers/Role.cs +++ b/League/Controllers/Role.cs @@ -79,7 +79,7 @@ public async Task Remove([FromForm] RoleRemoveModel model, Cancel (await _tenantContext.DbContext.AppDb.ManagerOfTeamRepository.GetManagerIdsOfTeamAsync(model.TeamId, cancellationToken)).Count <= 1) { - _logger.LogInformation("Rejected to remove last claim '{claimType}' for team id '{teamId}' and user id {userId}", + _logger.LogInformation("Rejected to remove last claim '{ClaimType}' for team id '{TeamId}' and user id {userId}", model.ClaimType, model.TeamId, model.UserId); return JsonResponseRedirect(SetCannotRemoveLastTeamManagerReturnResult(model.ReturnUrl, model.TeamId)); } @@ -95,7 +95,7 @@ public async Task Remove([FromForm] RoleRemoveModel model, Cancel } catch (Exception e) { - _logger.LogError(e, "Failed to remove claim '{claimType}' for team id '{teamId}' and user id {userId}", model.ClaimType, model.TeamId, model.UserId); + _logger.LogError(e, "Failed to remove claim '{ClaimType}' for team id '{TeamId}' and user id {UserId}", model.ClaimType, model.TeamId, model.UserId); return JsonResponseRedirect(SetAdjustedReturnResult(nameof(Remove), model.ReturnUrl, model.TeamId, false)); } } @@ -157,7 +157,7 @@ public async Task Add([FromForm] RoleAddModel model, Cancellation } catch (Exception e) { - _logger.LogError(e, "Failed to add claim '{claimType}' for team id '{teamId}' and user id '{userId}'", model.ClaimType, model.TeamId, newTeamMember.Id); + _logger.LogError(e, "Failed to add claim '{ClaimType}' for team id '{TeamId}' and user id '{UserId}'", model.ClaimType, model.TeamId, newTeamMember.Id); } } else diff --git a/League/Controllers/Team.cs b/League/Controllers/Team.cs index e586d511..6fb701e4 100644 --- a/League/Controllers/Team.cs +++ b/League/Controllers/Team.cs @@ -1,5 +1,4 @@ -using System.Security.Claims; -using League.Components; +using League.Components; using League.Helpers; using League.Models.TeamViewModels; using League.Models.UploadViewModels; @@ -59,7 +58,7 @@ public async Task List(CancellationToken cancellationToken) if (model.Tournament == null) { - _logger.LogError("{teamTournamentId} '{id}' does not exist", nameof(_tenantContext.TournamentContext.TeamTournamentId), _tenantContext.TournamentContext.TeamTournamentId); + _logger.LogError("{TeamTournamentId} '{Td}' does not exist", nameof(_tenantContext.TournamentContext.TeamTournamentId), _tenantContext.TournamentContext.TeamTournamentId); return NotFound(); } @@ -202,7 +201,7 @@ public async Task Edit([FromForm] TeamEditModel model, Cancellati cancellationToken)); if (team.TeamInRounds.Count > 1) - _logger.LogError("Teams ID {teamId} belongs to {roundsCount} rounds for tournament ID {tournamentId}", team.Id, + _logger.LogError("Teams ID {TeamId} belongs to {RoundsCount} rounds for tournament ID {TournamentId}", team.Id, team.TeamInRounds.Count, _tenantContext.TournamentContext.TeamTournamentId); } @@ -249,7 +248,7 @@ public async Task Edit([FromForm] TeamEditModel model, Cancellati catch (Exception e) { TempData.Put(nameof(MyTeamMessageModel.MyTeamMessage), new MyTeamMessageModel.MyTeamMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MyTeamMessageModel.MessageId.TeamDataFailure}); - _logger.LogError(e, "Error saving team id '{teamId}'", model.Team.IsNew ? "new" : model.Team.Id.ToString()); + _logger.LogError(e, "Error saving team id '{TeamId}'", model.Team.IsNew ? "new" : model.Team.Id.ToString()); return JsonResponseRedirect(TenantLink.Action(nameof(MyTeam), nameof(Team),new { id = team.Id })); } @@ -347,7 +346,7 @@ public async Task SelectVenue([FromForm][Bind("TeamId, VenueId")] } catch (Exception e) { - _logger.LogError(e, "Failed to save selected venue for team id {teamId}, venue id {venueId}", model.TeamId, model.VenueId); + _logger.LogError(e, "Failed to save selected venue for team id {TeamId}, venue id {VSenueId}", model.TeamId, model.VenueId); } return JsonResponseRedirect(TenantLink.Action(nameof(MyTeam), nameof(Team), new { model.TeamId })); diff --git a/League/Controllers/TeamApplication.cs b/League/Controllers/TeamApplication.cs index 3cf2d966..bd5a5a11 100644 --- a/League/Controllers/TeamApplication.cs +++ b/League/Controllers/TeamApplication.cs @@ -84,7 +84,7 @@ public async Task List(CancellationToken cancellationToken) if (model.Tournament == null) { - _logger.LogError("{name} '{id}' does not exist", nameof(_tenantContext.TournamentContext.ApplicationTournamentId), _tenantContext.TournamentContext.ApplicationTournamentId); + _logger.LogError("{Name} '{Id}' does not exist", nameof(_tenantContext.TournamentContext.ApplicationTournamentId), _tenantContext.TournamentContext.ApplicationTournamentId); return NotFound(); } @@ -244,7 +244,7 @@ public async Task EditTeam([FromForm] TeamEditModel teamEditModel cancellationToken)); if (teamEntity.TeamInRounds.Count > 1) - _logger.LogError("Teams ID {teamId} belongs to {rounds} rounds for tournament ID {tournamentId}", teamEntity.Id, + _logger.LogError("Teams ID {TeamId} belongs to {Rounds} rounds for tournament ID {TournamentId}", teamEntity.Id, teamEntity.TeamInRounds.Count, _tenantContext.TournamentContext.ApplicationTournamentId); } @@ -498,8 +498,8 @@ public async Task Confirm(bool done, CancellationToken cancellati } catch (Exception e) { - _logger.LogError(e, "{entityName} with ID {teamInRoundId} for team ID {teamId} not found", nameof(TeamInRoundEntity), sessionModel.TeamInRound!.Id, sessionModel.TeamInRound.TeamId); - throw; + _logger.LogError(e, "{EntityName} with ID {TeamInRoundId} for team ID {TeamId} not found", nameof(TeamInRoundEntity), sessionModel.TeamInRound!.Id, sessionModel.TeamInRound.TeamId); + NotFound(); } sessionModel.TeamInRound.MapFormFieldsToEntity(teamInRoundEntity); @@ -683,7 +683,7 @@ private VenueEditModel GetVenueEditModel(VenueEntity venueEntity, TeamEntity? te if (!geoResponse.Success) { _logger.LogError(geoResponse.Exception, - "{methodName} failed. Response status text: {statusText}", + "{MethodName} failed. Response status text: {StatusText}", $"{nameof(VenueEditModel)}.{nameof(VenueEditModel.TrySetGeoLocation)}()", geoResponse.StatusText); } @@ -739,7 +739,7 @@ private async Task GetModelFromSession(CancellationToke } catch (Exception e) { - _logger.LogError(e, "Could not restore '{model}' from session", nameof(ApplicationSessionModel)); + _logger.LogError(e, "Could not restore '{Model}' from session", nameof(ApplicationSessionModel)); return await GetNewSessionModel(cancellationToken); } } diff --git a/League/Controllers/Upload.cs b/League/Controllers/Upload.cs index 8f4215a4..2186687f 100644 --- a/League/Controllers/Upload.cs +++ b/League/Controllers/Upload.cs @@ -67,7 +67,7 @@ public async Task TeamPhoto(long id, CancellationToken cancellati else { // shouldn't be the case - _logger.LogError("Photo file for team id '{teamId}' not found", id); + _logger.LogError("Photo file for team id '{TeamId}' not found", id); model.PhotoFileUrl = null; } @@ -134,7 +134,7 @@ await _tenantContext.DbContext.AppDb.TeamRepository.GetTeamEntityAsync( } catch (Exception e) { - _logger.LogError(e, "File for team id '{teamId}' could not be stored", teamId); + _logger.LogError(e, "File for team id '{TeamId}' could not be stored", teamId); Response.StatusCode = 409; return Json(new {error = _localizer["Uploaded file could not be processed"].Value}); } diff --git a/League/Controllers/Venue.cs b/League/Controllers/Venue.cs index a5f926f9..a2d70847 100644 --- a/League/Controllers/Venue.cs +++ b/League/Controllers/Venue.cs @@ -252,7 +252,7 @@ private string SetAdjustedReturnResult(string method, string returnUrl, bool isS if (!geoResponse.Success) { _logger.LogError(geoResponse.Exception, - "{modelName} failed. Response status text: {statusText}", + "{ModelName} failed. Response status text: {StatusText}", $"{nameof(VenueEditModel)}.{nameof(VenueEditModel.TrySetGeoLocation)}()", geoResponse.StatusText); } diff --git a/League/Identity/RoleStore.cs b/League/Identity/RoleStore.cs index 10687eb0..e8044f12 100644 --- a/League/Identity/RoleStore.cs +++ b/League/Identity/RoleStore.cs @@ -11,11 +11,11 @@ namespace League.Identity; public class RoleStore : IRoleStore, IRoleClaimStore { private readonly IAppDb _appDb; - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly ILookupNormalizer _keyNormalizer; private readonly IdentityErrorDescriber _identityErrorDescriber; - public RoleStore(ITenantContext tenantContext, ILogger logger, ILookupNormalizer keyNormalizer, IdentityErrorDescriber identityErrorDescriber) + public RoleStore(ITenantContext tenantContext, ILogger logger, ILookupNormalizer keyNormalizer, IdentityErrorDescriber identityErrorDescriber) { _appDb = tenantContext.DbContext.AppDb; _logger = logger; @@ -44,9 +44,9 @@ public async Task CreateAsync(ApplicationRole role, Cancellation await _appDb.GenericRepository.SaveEntityAsync(roleEntity, true, false, cancellationToken); role.Id = roleEntity.Id; } - catch (Exception) + catch (Exception e) { - _logger.LogError("Role name '{roleName}' could not be created", role.Name); + _logger.LogError(e,"Role name '{RoleName}' could not be created", role.Name); return IdentityResult.Failed(_identityErrorDescriber.DefaultError()); } @@ -83,7 +83,7 @@ public async Task UpdateAsync(ApplicationRole role, Cancellation } catch (Exception e) { - _logger.LogError(e, "Role id '{roleId}' could not be updated", role.Id); + _logger.LogError(e, "Role id '{RoleId}' could not be updated", role.Id); return IdentityResult.Failed(_identityErrorDescriber.DefaultError()); } @@ -104,9 +104,9 @@ public async Task DeleteAsync(ApplicationRole role, Cancellation return IdentityResult.Success; } } - catch (Exception) + catch (Exception e) { - _logger.LogError("Role id '{roleId}' could not be removed", role.Id); + _logger.LogError(e, "Role id '{RoleId}' could not be removed", role.Id); } return IdentityResult.Failed(_identityErrorDescriber.DefaultError()); @@ -217,8 +217,7 @@ public async Task AddClaimAsync(ApplicationRole role, Claim claim, CancellationT } catch (Exception e) { - _logger.LogError(e, "Error adding role claim type '{claimType}' to role id '{roleId}'", claim.Type, role.Id); - throw; + throw new InvalidOperationException($"Error adding role claim type '{claim.Type}' to role id '{role.Id}'", e); } } @@ -244,8 +243,7 @@ public async Task RemoveClaimAsync(ApplicationRole role, Claim claim, Cancellati } catch (Exception e) { - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException(msg, e); } } diff --git a/League/Identity/UserStore.cs b/League/Identity/UserStore.cs index a6397c68..f8df118b 100644 --- a/League/Identity/UserStore.cs +++ b/League/Identity/UserStore.cs @@ -95,7 +95,7 @@ public async Task DeleteAsync(ApplicationUser user, Cancellation } catch (Exception e) { - _logger.LogError(e, "Account for user id {userId} could not be deleted", user.Id); + _logger.LogError(e, "Account for user id {UWserId} could not be deleted", user.Id); return IdentityResult.Failed(_identityErrorDescriber.DefaultError()); } } @@ -414,10 +414,7 @@ public async Task AddToRoleAsync(ApplicationUser user, string roleName, Cancella if (Constants.RoleName.GetTeamRelatedRoles().Contains(roleName)) { - var msg = $"The role name '{roleName}' cannot be added explicitly."; - - _logger.LogError(msg); - throw new InvalidOperationException(msg); + throw new InvalidOperationException($"The role name '{roleName}' cannot be added explicitly."); } bool success; @@ -428,13 +425,12 @@ public async Task AddToRoleAsync(ApplicationUser user, string roleName, Cancella } catch (Exception e) { - _logger.LogError(exceptionMsg, e); + _logger.LogError(e, exceptionMsg); success = false; } if (!success) { - _logger.LogError(exceptionMsg); throw new InvalidOperationException(exceptionMsg); } } @@ -449,9 +445,7 @@ public async Task RemoveFromRoleAsync(ApplicationUser user, string roleName, Can if (Constants.RoleName.GetTeamRelatedRoles().Contains(roleName)) { - var msg = $"The role name '{roleName}' cannot be removed explicitly."; - _logger.LogError(msg); - throw new InvalidOperationException(msg); + throw new InvalidOperationException($"The role name '{roleName}' cannot be removed explicitly."); } bool success; @@ -462,13 +456,12 @@ public async Task RemoveFromRoleAsync(ApplicationUser user, string roleName, Can } catch(Exception e) { - _logger.LogError(exceptionMsg, e); + _logger.LogError(e, exceptionMsg); success = false; } if (!success) { - _logger.LogError(exceptionMsg); throw new InvalidOperationException(exceptionMsg); } } @@ -482,7 +475,7 @@ public async Task> GetRolesAsync(ApplicationUser user, Cancellatio if (userEntity == null) { var ex = new ArgumentException($"User id '{user.Id}' does not exist"); - _logger.LogError(ex.Message, ex); + _logger.LogError(ex, ex.Message); throw ex; } @@ -601,7 +594,7 @@ public async Task AddClaimsAsync(ApplicationUser user, IEnumerable claims if (Constants.ClaimType.GetProgrammaticClaimTypes().Contains(claim.Type)) { var ex = new ArgumentException($"Programmatic claim type '{claim.Type}' cannot be stored."); - _logger.LogError(ex.Message, ex); + _logger.LogError(ex, ex.Message); throw ex; } @@ -619,9 +612,7 @@ public async Task AddClaimsAsync(ApplicationUser user, IEnumerable claims } catch (Exception e) { - var msg = $"Claim types '{string.Join(", ", claims.Select(c => c.Type))}' could not be added"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"Claim types '{string.Join(", ", claims.Select(c => c.Type))}' could not be added", e); } } @@ -632,7 +623,7 @@ private async Task AddTeamRelatedClaimAsync(ApplicationUser user, Claim claim, C if (!exists) { var ex = new ArgumentException($"Claim type '{claim.Type}': Team Id '{claim.Value}' does not exist"); - _logger.LogError(ex.Message, ex); + _logger.LogError(ex, ex.Message); throw ex; } @@ -652,7 +643,7 @@ await _appDb.GenericRepository.SaveEntityAsync( return; default: var ex = new NotImplementedException(errorMsg); - _logger.LogError(errorMsg, ex); + _logger.LogError(ex, errorMsg); throw ex; } } @@ -678,9 +669,7 @@ public async Task ReplaceClaimAsync(ApplicationUser user, Claim claim, Claim new if (Constants.ClaimType.GetProgrammaticClaimTypes().Contains(claim.Type) || Constants.ClaimType.GetProgrammaticClaimTypes().Contains(newClaim.Type)) { - var ex = new ArgumentException($"Programmatic claim types cannot be replaced or stored. Current claim type: '{claim.Type}'. New claim type: '{newClaim.Type}'"); - _logger.LogError(ex.Message, ex); - throw ex; + throw new ArgumentException($"Programmatic claim types cannot be replaced or stored. Current claim type: '{claim.Type}'. New claim type: '{newClaim.Type}'"); } try @@ -703,9 +692,7 @@ public async Task ReplaceClaimAsync(ApplicationUser user, Claim claim, Claim new } catch (Exception e) { - var msg = $"Claim type {claim.Type} could not be replaced"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"Claim type {claim.Type} could not be replaced", e); } } @@ -736,7 +723,7 @@ public async Task RemoveClaimsAsync(ApplicationUser user, IEnumerable cla if (Constants.ClaimType.GetProgrammaticClaimTypes().Contains(claim.Type)) { var ex = new ArgumentException($"Programmatic claim type '{claim.Type}' cannot be removed."); - _logger.LogError(ex.Message, ex); + _logger.LogError(ex, ex.Message); throw ex; } @@ -747,9 +734,7 @@ public async Task RemoveClaimsAsync(ApplicationUser user, IEnumerable cla } catch (Exception e) { - var msg = $"Claim types '{string.Join(", ", claims.Select(c => c.Type))}' could not be removed"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"Claim types '{string.Join(", ", claims.Select(c => c.Type))}' could not be removed", e); } } @@ -796,7 +781,7 @@ public async Task> GetUsersForClaimAsync(Claim claim, Can default: var errorMsg = $"Claim type '{claim.Type}' with value '{teamId}' could not be processed"; var e = new NotImplementedException(errorMsg); - _logger.LogError(errorMsg, e); + _logger.LogError(e, errorMsg); throw e; } } @@ -851,9 +836,7 @@ public async Task AddLoginAsync(ApplicationUser user, UserLoginInfo login, Cance } catch (Exception e) { - var msg = $"LoginInfo for provider '{login.LoginProvider}' and user id '{user.Id}' could not be added"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"LoginInfo for provider '{login.LoginProvider}' and user id '{user.Id}' could not be added", e); } } @@ -876,9 +859,7 @@ public async Task RemoveLoginAsync(ApplicationUser user, string loginProvider, s } catch (Exception e) { - var msg = $"LoginInfo for provider '{loginProvider}' and user id '{user.Id}' could not be removed"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"LoginInfo for provider '{loginProvider}' and user id '{user.Id}' could not be removed", e); } } @@ -957,9 +938,7 @@ public async Task SetTokenAsync(ApplicationUser user, string loginProvider, stri } catch (Exception e) { - var msg = $"AuthenticationToken with name '{name}' for provider '{loginProvider}' and user id '{user.Id}' could not be set"; - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException($"AuthenticationToken with name '{name}' for provider '{loginProvider}' and user id '{user.Id}' could not be set", e); } } @@ -980,14 +959,12 @@ public async Task RemoveTokenAsync(ApplicationUser user, string loginProvider, s var userTokenEntity = new IdentityUserTokenEntity(loginProvider, name, user.Id); if (!await _appDb.GenericRepository.DeleteEntityAsync(userTokenEntity, cancellationToken)) { - _logger.LogError(msg); throw new InvalidOperationException(msg); } } catch (Exception e) { - _logger.LogError(msg, e); - throw; + throw new InvalidOperationException(msg, e); } } diff --git a/League/LeagueStartup.cs b/League/LeagueStartup.cs index 541ad4d1..4cb39cf0 100644 --- a/League/LeagueStartup.cs +++ b/League/LeagueStartup.cs @@ -629,15 +629,15 @@ public static void Configure(WebApplication app, ILoggerFactory loggerFactory) var folderName = Path.Combine(environment.WebRootPath, folder); if (!Directory.Exists(folderName)) { - logger.LogInformation("Folder '{folderName}' does not exist.", folderName); + logger.LogInformation("Folder '{FolderName}' does not exist.", folderName); try { Directory.CreateDirectory(folderName); - logger.LogInformation("Folder '{folderName}' created.", folderName); + logger.LogInformation("Folder '{FolderName}' created.", folderName); } catch (Exception e) { - logger.LogError(e, "Folder '{folderName}': Does not exist and could not be created.", folderName); + logger.LogError(e, "Folder '{FolderName}': Does not exist and could not be created.", folderName); } } } diff --git a/League/Middleware/ClientAbortMiddleware.cs b/League/Middleware/ClientAbortMiddleware.cs index 3e6886d6..d933e84b 100644 --- a/League/Middleware/ClientAbortMiddleware.cs +++ b/League/Middleware/ClientAbortMiddleware.cs @@ -28,7 +28,7 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next) catch (Exception ex) when (ex is TaskCanceledException or SqlException && context.RequestAborted.IsCancellationRequested) { // Log the exception and stop the request queue. - _logger.LogWarning("Request aborted by client: '{exception}'. Processing stops.", ex.GetType().ToString()); + _logger.LogWarning(ex, "Request aborted by client. Processing stops."); } } } diff --git a/League/ModelBinders/DateOnlyModelBinder.cs b/League/ModelBinders/DateOnlyModelBinder.cs index 10d73d23..6c22270a 100644 --- a/League/ModelBinders/DateOnlyModelBinder.cs +++ b/League/ModelBinders/DateOnlyModelBinder.cs @@ -46,12 +46,12 @@ public Task BindModelAsync(ModelBindingContext bindingContext) if (!TryParseDateOnly(valueAsString, out var dateTime)) { - _logger.LogDebug("Could not bind model '{modelName}' to value '{valueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); + _logger.LogDebug("Could not bind model '{ModelName}' to value '{ValueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); return _fallbackBinder.BindModelAsync(bindingContext); } bindingContext.Result = ModelBindingResult.Success(dateTime); - _logger.LogDebug("Parsed string '{originalValue}': {dateTime} ", valueAsString, dateTime); + _logger.LogDebug("Parsed string '{OriginalValue}': {DateTime} ", valueAsString, dateTime); return Task.CompletedTask; } diff --git a/League/ModelBinders/DateTimeModelBinder.cs b/League/ModelBinders/DateTimeModelBinder.cs index 8a0b6ac4..88724abd 100644 --- a/League/ModelBinders/DateTimeModelBinder.cs +++ b/League/ModelBinders/DateTimeModelBinder.cs @@ -54,12 +54,12 @@ public Task BindModelAsync(ModelBindingContext bindingContext) if (!TryParseDateTime(valueAsString, out var dateTime)) { - _logger.LogDebug("Could not bind model '{modelName}' to value '{valueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); + _logger.LogDebug("Could not bind model '{ModelName}' to value '{ValueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); return _fallbackBinder.BindModelAsync(bindingContext); } bindingContext.Result = ModelBindingResult.Success(dateTime); - _logger.LogDebug("Parsed string '{originalValue}': {dateTime} ", valueAsString, dateTime); + _logger.LogDebug("Parsed string '{OriginalValue}': {DateTime} ", valueAsString, dateTime); return Task.CompletedTask; } diff --git a/League/ModelBinders/StringTrimmingModelBinder.cs b/League/ModelBinders/StringTrimmingModelBinder.cs index 6e1b2c0e..678fd1a6 100644 --- a/League/ModelBinders/StringTrimmingModelBinder.cs +++ b/League/ModelBinders/StringTrimmingModelBinder.cs @@ -39,7 +39,7 @@ public Task BindModelAsync(ModelBindingContext bindingContext) var trimmedValue = valueProviderResult.FirstValue?.Trim(); bindingContext.Result = ModelBindingResult.Success(trimmedValue); - _logger.LogDebug("Value after trimming any white-space from '{originalValue}': {newValue} ", valueProviderResult.FirstValue, trimmedValue); + _logger.LogDebug("Value after trimming any white-space from '{OriginalValue}': {NewValue} ", valueProviderResult.FirstValue, trimmedValue); return Task.CompletedTask; } } diff --git a/League/ModelBinders/TimeOnlyModelBinder.cs b/League/ModelBinders/TimeOnlyModelBinder.cs index 8846bc93..ac4cbb1f 100644 --- a/League/ModelBinders/TimeOnlyModelBinder.cs +++ b/League/ModelBinders/TimeOnlyModelBinder.cs @@ -43,12 +43,12 @@ public Task BindModelAsync(ModelBindingContext bindingContext) if (!TryParseTimeOnly(valueAsString, out var time)) { - _logger.LogDebug("Could not bind model '{modelName}' to value '{valueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); + _logger.LogDebug("Could not bind model '{ModelName}' to value '{ValueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); return _fallbackBinder.BindModelAsync(bindingContext); } bindingContext.Result = ModelBindingResult.Success(time); - _logger.LogDebug("Parsed string '{originalValue}': {timeSpan} ", valueAsString, time); + _logger.LogDebug("Parsed string '{OriginalValue}': {TimeSpan} ", valueAsString, time); return Task.CompletedTask; } diff --git a/League/ModelBinders/TimeSpanModelBinder.cs b/League/ModelBinders/TimeSpanModelBinder.cs index 49cad056..c22330b9 100644 --- a/League/ModelBinders/TimeSpanModelBinder.cs +++ b/League/ModelBinders/TimeSpanModelBinder.cs @@ -43,12 +43,12 @@ public Task BindModelAsync(ModelBindingContext bindingContext) if (!TryParseTime(valueAsString, out var time)) { - _logger.LogDebug("Could not bind model '{modelName}' to value '{valueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); + _logger.LogDebug("Could not bind model '{ModelName}' to value '{ValueAsString}', falling back to {fallbackBinder}", bindingContext.ModelName, valueAsString, nameof(SimpleTypeModelBinder)); return _fallbackBinder.BindModelAsync(bindingContext); } bindingContext.Result = ModelBindingResult.Success(time); - _logger.LogDebug("Parsed string '{originalValue}': {timeSpan} ", valueAsString, time); + _logger.LogDebug("Parsed string '{OriginalValue}': {TimeSpan} ", valueAsString, time); return Task.CompletedTask; } diff --git a/League/Models/UploadViewModels/AbstractStaticFile.cs b/League/Models/UploadViewModels/AbstractStaticFile.cs index eb30e85d..c228309c 100644 --- a/League/Models/UploadViewModels/AbstractStaticFile.cs +++ b/League/Models/UploadViewModels/AbstractStaticFile.cs @@ -34,12 +34,12 @@ protected async Task SaveFileAsync(IFormFile formFile, string fullFilePa { await using var outStream = new FileStream(fullFilePath, FileMode.Create); await formFile.CopyToAsync(outStream, cancellationToken); + _logger.LogDebug("{File} saved", fullFilePath); return Path.GetFileName(fullFilePath); } catch (Exception e) { - _logger.LogError(e, "File '{path}' could not be saved", fullFilePath); - throw; + throw new InvalidOperationException($"File '{fullFilePath}' could not be saved", e); } } #pragma warning disable CA3003 @@ -58,11 +58,11 @@ protected void DeleteObsoleteFiles(DirectoryInfo dirInfo, string searchPattern) try { File.Delete(fileInfo.FullName); + _logger.LogDebug("Obsolete {File} deleted", fileInfo.FullName); } catch (Exception e) { - _logger.LogError(e, "File '{filename}' could not be deleted", fileInfo.FullName); - throw; + throw new InvalidOperationException($"File '{fileInfo.FullName}' could not be deleted", e); } } } @@ -80,11 +80,11 @@ protected void DeleteMostRecentFile(DirectoryInfo dirInfo, string searchPattern) try { File.Delete(fileInfo.FullName); + _logger.LogDebug("Most recent file {File} deleted", fileInfo.FullName); } catch (Exception e) { - _logger.LogError(e, "File '{fileName}' could not be deleted", fileInfo.FullName); - throw; + throw new InvalidOperationException($"File '{fileInfo.FullName}' could not be deleted", e); } } } diff --git a/TournamentManager/TournamentManager/DI/PhoneNumberService.cs b/TournamentManager/TournamentManager/DI/PhoneNumberService.cs index 035ecafb..70ddbb4f 100644 --- a/TournamentManager/TournamentManager/DI/PhoneNumberService.cs +++ b/TournamentManager/TournamentManager/DI/PhoneNumberService.cs @@ -12,6 +12,7 @@ namespace TournamentManager.DI; /// public class PhoneNumberService { + private const string PhoneNumberLiteral = "{PhoneNumber}"; // used for logging private readonly PhoneNumbers.PhoneNumberUtil _fnu; private static readonly object Locker = new(); private readonly ILogger _logger = AppLogging.CreateLogger(); @@ -41,7 +42,7 @@ public bool IsValid(string phoneNumber, string defaultRegion) } catch (Exception e) { - _logger.LogDebug(e, "{@phoneNumber}", phoneNumber); + _logger.LogDebug(e, PhoneNumberLiteral, phoneNumber); return false; } } @@ -72,7 +73,7 @@ public string Format(string phoneNumber, string region) } catch (Exception e) { - _logger.LogDebug(e, "{@phoneNumber}", phoneNumber); + _logger.LogDebug(e, PhoneNumberLiteral, phoneNumber); return phoneNumber; } } @@ -96,7 +97,7 @@ public string FormatForStorage(string phoneNumber, string region) } catch (Exception e) { - _logger.LogDebug(e, "{@phoneNumber}", phoneNumber); + _logger.LogDebug(e, PhoneNumberLiteral, phoneNumber); return phoneNumber; } } @@ -120,7 +121,7 @@ public string FormatAsTelephoneUri(string phoneNumber, string region) } catch (Exception e) { - _logger.LogDebug(e, "{@phoneNumber}", phoneNumber); + _logger.LogDebug(e, PhoneNumberLiteral, phoneNumber); return "tel:" + phoneNumber; } } @@ -146,4 +147,4 @@ public bool IsMatch(string number1, string number2, string defaultRegion) PhoneNumberUtil.MatchType.EXACT_MATCH; } } -} \ No newline at end of file +} diff --git a/TournamentManager/TournamentManager/Data/AvailableMatchDateRepository.cs b/TournamentManager/TournamentManager/Data/AvailableMatchDateRepository.cs index a32c6350..b16a982a 100644 --- a/TournamentManager/TournamentManager/Data/AvailableMatchDateRepository.cs +++ b/TournamentManager/TournamentManager/Data/AvailableMatchDateRepository.cs @@ -35,7 +35,7 @@ public virtual async Task> GetAvailab }; await da.FetchEntityCollectionAsync(qp, cancellationToken); - _logger.LogDebug("Fetched {count} available match dates for tournament {tournamentId}.", available.Count, tournamentId); + _logger.LogDebug("Fetched {Count} available match dates for tournament {TournamentId}.", available.Count, tournamentId); return available; } @@ -73,7 +73,7 @@ public virtual async Task ClearAsync(long tournamentId, MatchDateClearOptio filterAvailable, cancellationToken); } - _logger.LogDebug("Deleted {deleted} available match dates for tournament {tournamentId}.", deleted, tournamentId); + _logger.LogDebug("Deleted {Deleted} available match dates for tournament {TournamentId}.", deleted, tournamentId); return deleted; } diff --git a/TournamentManager/TournamentManager/Data/GenericRepository.cs b/TournamentManager/TournamentManager/Data/GenericRepository.cs index 2ff6f83c..23d96d61 100644 --- a/TournamentManager/TournamentManager/Data/GenericRepository.cs +++ b/TournamentManager/TournamentManager/Data/GenericRepository.cs @@ -27,12 +27,10 @@ public virtual async Task SaveEntityAsync(T entityToSave, bool refetchA } catch (Exception e) { - _logger.LogError(e, "Error saving entity in transaction: {entity}", entityToSave); - if (da.IsTransactionInProgress) da.Rollback(); - throw; + throw new InvalidOperationException($"Error saving entity in transaction: {entityToSave}", e); } } diff --git a/TournamentManager/TournamentManager/Data/MatchRepository.cs b/TournamentManager/TournamentManager/Data/MatchRepository.cs index 2991b806..abb7cc49 100644 --- a/TournamentManager/TournamentManager/Data/MatchRepository.cs +++ b/TournamentManager/TournamentManager/Data/MatchRepository.cs @@ -208,7 +208,7 @@ public virtual async Task AreTeamsBusyAsync(MatchEntity match, bool only matches.ForEach(m => { _logger.LogDebug( - "{methodName}: {date} MatchId={matchId}, HomeTeamId={homeTeamId}, GuestTeamId={guestTeamId}", + "{MethodName}: {Date} MatchId={MatchId}, HomeTeamId={HomeTeamId}, GuestTeamId={GuestTeamId}", nameof(AreTeamsBusyAsync), onlyUseDatePart ? match.PlannedStart?.ToString("'Date='yyyy-MM-dd") @@ -354,7 +354,7 @@ await da.StartTransactionAsync(IsolationLevel.ReadCommitted, } catch (Exception e) { - _logger.LogError(e, "Error saving in transaction: MatchId={matchId}", matchEntity.Id); + _logger.LogError(e, "Error saving in transaction: MatchId={MatchId}", matchEntity.Id); if (da.IsTransactionInProgress) da.Rollback(); diff --git a/TournamentManager/TournamentManager/Data/PlayerInTeamRepository.cs b/TournamentManager/TournamentManager/Data/PlayerInTeamRepository.cs index 70bf8019..52256428 100644 --- a/TournamentManager/TournamentManager/Data/PlayerInTeamRepository.cs +++ b/TournamentManager/TournamentManager/Data/PlayerInTeamRepository.cs @@ -27,7 +27,7 @@ public virtual async Task> GetPlayersInTeamAsync(long teamId, where pit.TeamId == teamId select pit.User).ToListAsync(cancellationToken); - _logger.LogDebug("{count} player(s) found for team id {teamId}", result.Count, teamId); + _logger.LogDebug("{Count} player(s) found for team id {TeamId}", result.Count, teamId); return result; } @@ -41,7 +41,7 @@ public virtual async Task> GetTeamIdsForPlayerAsync(long userId, Canc where pit.UserId == userId select pit.TeamId).ToListAsync(cancellationToken); - _logger.LogDebug("{userId} team(s) found for user id {count}", userId, result.Count); + _logger.LogDebug("{UserId} team(s) found for user id: {Count}", userId, result.Count); return result; } @@ -54,8 +54,8 @@ public virtual async Task> GetPlayersAsync(CancellationToken ca var result = await (from pit in metaData.PlayerInTeam select pit.User).ToListAsync(cancellationToken); - _logger.LogDebug("{count} player(s) found", result.Count); + _logger.LogDebug("{Count} player(s) found", result.Count); return result; } -} \ No newline at end of file +} diff --git a/TournamentManager/TournamentManager/Data/RankingRepository.cs b/TournamentManager/TournamentManager/Data/RankingRepository.cs index e05e9d96..8e0ca297 100644 --- a/TournamentManager/TournamentManager/Data/RankingRepository.cs +++ b/TournamentManager/TournamentManager/Data/RankingRepository.cs @@ -86,12 +86,10 @@ public virtual async Task ReplaceAsync(RankingList rankingList, long roundId, Ca } catch (Exception e) { - _logger.LogError(e, "Error updating Ranking in transaction: RoundId={roundId}", roundId); - if (da.IsTransactionInProgress) da.Rollback(); - throw; + throw new InvalidOperationException($"Error updating Ranking in transaction: RoundId={roundId}", e); } } diff --git a/TournamentManager/TournamentManager/Data/RoleRepository.cs b/TournamentManager/TournamentManager/Data/RoleRepository.cs index 9b513071..926e915e 100644 --- a/TournamentManager/TournamentManager/Data/RoleRepository.cs +++ b/TournamentManager/TournamentManager/Data/RoleRepository.cs @@ -51,7 +51,7 @@ public virtual async Task RoleNameExistsAsync(string roleName, Cancellatio where roleName.Equals(r.Name, StringComparison.InvariantCultureIgnoreCase) select r).FirstOrDefaultAsync(cancellationToken); - _logger.LogDebug("{roleName} exists: {trueFalse}", roleName, result != null); + _logger.LogDebug("{RoleName} exists: {trueOrFalse}", roleName, result != null); return result != null; } diff --git a/TournamentManager/TournamentManager/Data/TeamInRoundRepository.cs b/TournamentManager/TournamentManager/Data/TeamInRoundRepository.cs index 11ee9a9a..f0f3a773 100644 --- a/TournamentManager/TournamentManager/Data/TeamInRoundRepository.cs +++ b/TournamentManager/TournamentManager/Data/TeamInRoundRepository.cs @@ -33,8 +33,8 @@ public virtual async Task> GetTeamInRoundAsync(IPredica var result = (IList) await da.FetchQueryAsync( q, cancellationToken); - _logger.LogDebug("{teamCount} team(s) found", result.Count); + _logger.LogDebug("{TeamCount} team(s) found", result.Count); return result; } -} \ No newline at end of file +} diff --git a/TournamentManager/TournamentManager/Data/TeamRespository.cs b/TournamentManager/TournamentManager/Data/TeamRespository.cs index 5e45eaff..2599a880 100644 --- a/TournamentManager/TournamentManager/Data/TeamRespository.cs +++ b/TournamentManager/TournamentManager/Data/TeamRespository.cs @@ -89,7 +89,7 @@ public virtual async Task> GetTeamsAndRounds using var da = _dbContext.GetNewAdapter(); await da.FetchEntityCollectionAsync(qp, cancellationToken); - _logger.LogDebug("{teamCount} found for {tournamentId}", tir.Count, tournament.Id); + _logger.LogDebug("{TeamCount} found for {TournamentId}", tir.Count, tournament.Id); return tir; } diff --git a/TournamentManager/TournamentManager/Data/UserClaimRepository.cs b/TournamentManager/TournamentManager/Data/UserClaimRepository.cs index ee996ae6..96debf7f 100644 --- a/TournamentManager/TournamentManager/Data/UserClaimRepository.cs +++ b/TournamentManager/TournamentManager/Data/UserClaimRepository.cs @@ -24,7 +24,7 @@ public virtual async Task> GetUserClaimsAsync(lon where uc.UserId == userId select uc).ToListAsync(cancellationToken); - _logger.LogDebug("{claimsCount} found", result.Count); + _logger.LogDebug("{ClaimsCount} found", result.Count); return result; } diff --git a/TournamentManager/TournamentManager/Data/UserLoginRepository.cs b/TournamentManager/TournamentManager/Data/UserLoginRepository.cs index 541bc686..ea5d2046 100644 --- a/TournamentManager/TournamentManager/Data/UserLoginRepository.cs +++ b/TournamentManager/TournamentManager/Data/UserLoginRepository.cs @@ -21,7 +21,7 @@ public virtual async Task> GetUserLoginsAsync(long using var da = _dbContext.GetNewAdapter(); var metaData = new LinqMetaData(da); var result = await (from login in metaData.IdentityUserLogin where login.UserId == userId select login).ExecuteAsync>(cancellationToken); - _logger.LogDebug("{userLoginCount} found for {userId}", result.Count, userId); + _logger.LogDebug("{UserLoginCount} found for {UserId}", result.Count, userId); return result.ToList(); } diff --git a/TournamentManager/TournamentManager/Data/UserRepository.cs b/TournamentManager/TournamentManager/Data/UserRepository.cs index a06dd685..d76af11d 100644 --- a/TournamentManager/TournamentManager/Data/UserRepository.cs +++ b/TournamentManager/TournamentManager/Data/UserRepository.cs @@ -184,11 +184,11 @@ public virtual async Task SetLastLoginDateAsync(string userName, DateTime? if (count == 1) { - _logger.LogInformation("Sign-in date for user id '{userId}' updated.", user.Id); + _logger.LogInformation("Sign-in date for user id '{UserId}' updated.", user.Id); } else { - _logger.LogError("Sign-in date for user id '{userId}' could not be updated.", user.Id); + _logger.LogError("Sign-in date for user id '{UserId}' could not be updated.", user.Id); } return count == 1; diff --git a/TournamentManager/TournamentManager/Data/UserRoleRepository.cs b/TournamentManager/TournamentManager/Data/UserRoleRepository.cs index ef923c50..e853434a 100644 --- a/TournamentManager/TournamentManager/Data/UserRoleRepository.cs +++ b/TournamentManager/TournamentManager/Data/UserRoleRepository.cs @@ -23,7 +23,7 @@ public virtual async Task> GetUserRolesAsync(long user var result = await (from ur in metaData.IdentityUserRole where ur.UserId == userId select ur.IdentityRole).ToListAsync(cancellationToken); - _logger.LogDebug("{roleCount} found for {userId}", result.Count, userId); + _logger.LogDebug("{RoleCount} found for {UserId}", result.Count, userId); return result; } diff --git a/TournamentManager/TournamentManager/Data/UserTokenRepository.cs b/TournamentManager/TournamentManager/Data/UserTokenRepository.cs index 1462dfa6..1e953d7e 100644 --- a/TournamentManager/TournamentManager/Data/UserTokenRepository.cs +++ b/TournamentManager/TournamentManager/Data/UserTokenRepository.cs @@ -25,9 +25,9 @@ public UserTokenRepository(MultiTenancy.IDbContext dbContext) select token).FirstOrDefaultAsync(cancellationToken); if (result != null) - _logger.LogDebug("User Id {userId}: Token {tokenName} found for {loginProvider}", userId, name, + _logger.LogDebug("User Id {UserId}: Token {TokenName} found for {LoginProvider}", userId, name, loginProvider); return result; } -} \ No newline at end of file +} diff --git a/TournamentManager/TournamentManager/Data/VenueRepository.cs b/TournamentManager/TournamentManager/Data/VenueRepository.cs index 3c7a1520..0506e6db 100644 --- a/TournamentManager/TournamentManager/Data/VenueRepository.cs +++ b/TournamentManager/TournamentManager/Data/VenueRepository.cs @@ -53,7 +53,7 @@ public virtual async Task> GetOccupyingMatchesAsync(long v public virtual async Task IsValidVenueIdAsync(long? venueId, CancellationToken cancellationToken) { var result = (await GetVenuesAsync(new PredicateExpression(VenueFields.Id.Equal(venueId)), cancellationToken)).Count == 1; - _logger.LogDebug("Valid venue: {validVenue}", result); + _logger.LogDebug("Valid venue: {ValidVenue}", result); return result; } diff --git a/TournamentManager/TournamentManager/Importers/ExcludeDates/ExcelImporter.cs b/TournamentManager/TournamentManager/Importers/ExcludeDates/ExcelImporter.cs index f7ebe4f8..8ed4d694 100644 --- a/TournamentManager/TournamentManager/Importers/ExcludeDates/ExcelImporter.cs +++ b/TournamentManager/TournamentManager/Importers/ExcludeDates/ExcelImporter.cs @@ -41,12 +41,12 @@ public ExcelImporter(string xlPathAndFileName, Axuno.Tools.DateAndTime.TimeZoneC public IEnumerable Import(DateTimePeriod fromToTimePeriod) { var xlFile = new FileInfo(_xlPathAndFileName); - _logger.LogDebug("Opening Excel file '{excelFile}'", _xlPathAndFileName); + _logger.LogDebug("Opening Excel file '{ExcelFile}'", _xlPathAndFileName); using var package = new ExcelPackage(xlFile); var worksheet = package.Workbook.Worksheets.First(); - _logger.LogDebug("Using the first worksheet, '{worksheetName}'", worksheet.Name); - _logger.LogDebug("Date limits are {dateStart} - {dateEnd}", fromToTimePeriod.Start, fromToTimePeriod.End); + _logger.LogDebug("Using the first worksheet, '{WorksheetName}'", worksheet.Name); + _logger.LogDebug("Date limits are {DateStart} - {DateEnd}", fromToTimePeriod.Start, fromToTimePeriod.End); var row = 0; while (true) @@ -61,7 +61,7 @@ public IEnumerable Import(DateTimePeriod fromToTimePeriod) if (!(worksheet.Cells[row, 1].Value is DateTime from && worksheet.Cells[row, 2].Value is DateTime to) || row > 1000) { - _logger.LogDebug("Import finished with worksheet row {rowNo}", row - 1); + _logger.LogDebug("Import finished with worksheet row {RowNo}", row - 1); yield break; } @@ -79,13 +79,13 @@ public IEnumerable Import(DateTimePeriod fromToTimePeriod) if (!fromToTimePeriod.Overlaps(new DateTimePeriod(from, to))) { - _logger.LogDebug("UTC Dates {from} - {to} are out of limits", from, to); + _logger.LogDebug("UTC Dates {From} - {To} are out of limits", from, to); continue; } var reason = worksheet.Cells[row, 3].Value as string ?? string.Empty; yield return new ExcludeDateRecord(new DateTimePeriod(from, to), reason); - _logger.LogDebug("Imported UTC {from} - {to} ({reason})", from, to, reason); + _logger.LogDebug("Imported UTC {From} - {To} ({Reason})", from, to, reason); } } } diff --git a/TournamentManager/TournamentManager/ModelValidators/AbstractValidator.cs b/TournamentManager/TournamentManager/ModelValidators/AbstractValidator.cs index 92854155..3c791326 100644 --- a/TournamentManager/TournamentManager/ModelValidators/AbstractValidator.cs +++ b/TournamentManager/TournamentManager/ModelValidators/AbstractValidator.cs @@ -210,7 +210,7 @@ public virtual async Task> CheckAsync(TFactId id, CancellationToke fact.Success = factResult.Success; fact.Message = factResult.Message; fact.IsChecked = true; - Logger.LogTrace("Fact '{factId}': {factSuccess}", id, fact.Success); + Logger.LogTrace("Fact '{FactId}': {FactSuccess}", id, fact.Success); } catch (Exception e) { @@ -218,7 +218,7 @@ public virtual async Task> CheckAsync(TFactId id, CancellationToke fact.IsChecked = true; fact.Message = string.Empty; fact.Exception = e; - Logger.LogError(e, "Fact '{factId}': {factSuccess}", id, fact.Success); + Logger.LogError(e, "Fact '{FactId}': {FactSuccess}", id, fact.Success); } return fact; diff --git a/TournamentManager/TournamentManager/MultiTenancy/AbstractTenantStore.cs b/TournamentManager/TournamentManager/MultiTenancy/AbstractTenantStore.cs index be723e38..518b9c91 100644 --- a/TournamentManager/TournamentManager/MultiTenancy/AbstractTenantStore.cs +++ b/TournamentManager/TournamentManager/MultiTenancy/AbstractTenantStore.cs @@ -72,7 +72,7 @@ public IReadOnlyDictionary GetTenants() public bool TryAddTenant(T tenant) { var success = Tenants.TryAdd(tenant.Identifier, tenant); - Logger.LogTrace("Tenant with {tenant} '{tenantIdentifier}' {successMsg}.", nameof(tenant.Identifier), tenant.Identifier, success ? "added" : "failed to add"); + Logger.LogTrace("Tenant with {Tenant} '{TenantIdentifier}' {SuccessMsg}.", nameof(tenant.Identifier), tenant.Identifier, success ? "added" : "failed to add"); return success; } @@ -84,7 +84,7 @@ public bool TryAddTenant(T tenant) public bool TryRemoveTenant(string identifier) { var success = Tenants.TryRemove(identifier, out _); - Logger.LogTrace("Tenant with {name} '{identifier}' {successMsg}.", nameof(identifier), identifier, success ? "removed" : "failed to remove"); + Logger.LogTrace("Tenant with {Name} '{Identifier}' {SuccessMsg}.", nameof(identifier), identifier, success ? "removed" : "failed to remove"); return success; } @@ -103,7 +103,7 @@ public bool TryUpdateTenant(string identifier, T newTenant) newTenant.Identifier = identifier; success = Tenants.TryUpdate(identifier, newTenant, currentTenant); } - Logger.LogTrace("Tenant with {name} '{identifier}' {successMsg}.", nameof(identifier), identifier, success ? "updated" : "failed to update"); + Logger.LogTrace("Tenant with {Name} '{Identifier}' {SuccessMsg}.", nameof(identifier), identifier, success ? "updated" : "failed to update"); return success; } diff --git a/TournamentManager/TournamentManager/MultiTenancy/TenantStore.cs b/TournamentManager/TournamentManager/MultiTenancy/TenantStore.cs index 27f66d89..ce3a0de7 100644 --- a/TournamentManager/TournamentManager/MultiTenancy/TenantStore.cs +++ b/TournamentManager/TournamentManager/MultiTenancy/TenantStore.cs @@ -31,8 +31,7 @@ public override ITenantStore LoadTenants() } catch (Exception e) { - Logger.LogCritical("Loading tenant configurations failed. {Exception}", e); - throw; + throw new InvalidOperationException("Loading tenant configurations failed.", e); } } } diff --git a/TournamentManager/TournamentManager/Plan/AvailableMatchDates.cs b/TournamentManager/TournamentManager/Plan/AvailableMatchDates.cs index af5bfc2a..71da60f2 100644 --- a/TournamentManager/TournamentManager/Plan/AvailableMatchDates.cs +++ b/TournamentManager/TournamentManager/Plan/AvailableMatchDates.cs @@ -47,14 +47,14 @@ private async Task Initialize(CancellationToken cancellationToken) await _appDb.ExcludedMatchDateRepository.GetExcludedMatchDatesAsync( _tenantContext.TournamentContext.MatchPlanTournamentId, cancellationToken)); - _logger.LogDebug("{count} excluded match dates loaded from storage", _excludedMatchDates.Count); + _logger.LogDebug("{Count} excluded match dates loaded from storage", _excludedMatchDates.Count); _availableDatesFromDb.Clear(); _availableDatesFromDb.AddRange( await _appDb.AvailableMatchDateRepository.GetAvailableMatchDatesAsync( _tenantContext.TournamentContext.MatchPlanTournamentId, cancellationToken)); - _logger.LogDebug("{count} available match dates loaded from storage", _availableDatesFromDb.Count); + _logger.LogDebug("{Count} available match dates loaded from storage", _availableDatesFromDb.Count); _generatedAvailableDates.Clear(); } @@ -104,7 +104,7 @@ private bool IsDateUsable(DateTime matchDateTimeUtc, RoundLegEntity roundLeg, IE new DateTimePeriod(matchDateTimeUtc, matchDateTimeUtc.Add(plannedDuration)), team.VenueId!.Value, tournamentMatches); - _logger.LogDebug("Venue '{venueId}' is available for '{matchDateTimeUtc}': {isAvailable}", team.VenueId, matchDateTimeUtc, isAvailable); + _logger.LogDebug("Venue '{VenueId}' is available for '{MatchDateTimeUtc}': {IsAvailable}", team.VenueId, matchDateTimeUtc, isAvailable); return isAvailable; } diff --git a/TournamentManager/TournamentManager/Plan/ExcludeMatchDates.cs b/TournamentManager/TournamentManager/Plan/ExcludeMatchDates.cs index 5a737c9e..00edffde 100644 --- a/TournamentManager/TournamentManager/Plan/ExcludeMatchDates.cs +++ b/TournamentManager/TournamentManager/Plan/ExcludeMatchDates.cs @@ -41,7 +41,7 @@ public async Task GenerateExcludeDates(IExcludeDateImporter importer, long tourn RoundLegPeriodFields.TournamentId == tournamentId), cancellationToken); - _logger.LogDebug("Generating excluded dates for tournament {tournamentId} with {roundLegPeriods} round leg periods.", tournamentId, roundLegPeriods.Count); + _logger.LogDebug("Generating excluded dates for tournament {TournamentId} with {RoundLegPeriods} round leg periods.", tournamentId, roundLegPeriods.Count); var minDate = roundLegPeriods.Min(leg => leg.StartDateTime); var maxDate = roundLegPeriods.Max(leg => leg.EndDateTime); @@ -49,7 +49,7 @@ public async Task GenerateExcludeDates(IExcludeDateImporter importer, long tourn // remove all existing excluded dates for the tournament if (removeExisting) { - _logger.LogDebug("Removing existing excluded dates for tournament {tournamentId}.", tournamentId); + _logger.LogDebug("Removing existing excluded dates for tournament {TournamentId}.", tournamentId); var filter = new RelationPredicateBucket(ExcludeMatchDateFields.TournamentId == tournamentId); await _appDb.GenericRepository.DeleteEntitiesDirectlyAsync(typeof(ExcludeMatchDateEntity), filter, cancellationToken); @@ -57,7 +57,7 @@ await _appDb.GenericRepository.DeleteEntitiesDirectlyAsync(typeof(ExcludeMatchDa var excludedDates = new EntityCollection(); - _logger.LogDebug("Importing excluded dates from {minDate} to {maxDate} for tournament {tournamentId}.", tournamentId, minDate, maxDate); + _logger.LogDebug("Importing excluded dates from {MinDate} to {MaxDate} for tournament {TournamentId}.", minDate, maxDate, tournamentId); foreach (var record in importer.Import(new DateTimePeriod(minDate, maxDate))) { var entity = record.ToExcludeMatchDateEntity(); @@ -65,7 +65,7 @@ await _appDb.GenericRepository.DeleteEntitiesDirectlyAsync(typeof(ExcludeMatchDa excludedDates.Add(entity); } - _logger.LogDebug("Saving {excludedDates} excluded dates for tournament {tournamentId}.", excludedDates.Count, tournamentId); + _logger.LogDebug("Saving {ExcludedDates} excluded dates for tournament {TournamentId}.", excludedDates.Count, tournamentId); await _appDb.GenericRepository.SaveEntitiesAsync(excludedDates, false, false, cancellationToken); } } diff --git a/TournamentManager/TournamentManager/Plan/MatchCreator.cs b/TournamentManager/TournamentManager/Plan/MatchCreator.cs index 2cb8a56d..f105c4ef 100644 --- a/TournamentManager/TournamentManager/Plan/MatchCreator.cs +++ b/TournamentManager/TournamentManager/Plan/MatchCreator.cs @@ -55,7 +55,7 @@ private void CreateCombinations(RefereeType refereeType) if (Participants.Count < 3 && refereeType == RefereeType.OtherFromRound) throw new ArgumentOutOfRangeException(nameof(refereeType), refereeType,@"Round-robin system with referee from round requires at least 3 participants."); - _logger.LogDebug("Creating combinations for {participantCount} participants.", Participants.Count); + _logger.LogDebug("Creating combinations for {ParticipantCount} participants.", Participants.Count); _maxNumOfCombinations = Participants.Count * (Participants.Count - 1) / 2; CombinationsPerLeg = Participants.Count - 1;