diff --git a/.editorconfig b/.editorconfig index 3151862d60e4..0296b9eb79a8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -175,6 +175,9 @@ dotnet_diagnostic.CA1845.severity = warning # CA1846: Prefer AsSpan over Substring dotnet_diagnostic.CA1846.severity = warning +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = warning + # CA2008: Do not create tasks without passing a TaskScheduler dotnet_diagnostic.CA2008.severity = warning @@ -250,7 +253,7 @@ dotnet_diagnostic.IDE0161.severity = warning dotnet_style_allow_multiple_blank_lines_experimental = false dotnet_diagnostic.IDE2000.severity = warning -[**/{test,samples,perf}/**.{cs,vb}] +[{eng/tools/**.cs,**/{test,samples,perf}/**.cs}] # CA1018: Mark attributes with AttributeUsageAttribute dotnet_diagnostic.CA1018.severity = suggestion # CA1507: Use nameof to express symbol names diff --git a/eng/targets/CSharp.Common.targets b/eng/targets/CSharp.Common.targets index 49f9e3a2ca69..7ce076963759 100644 --- a/eng/targets/CSharp.Common.targets +++ b/eng/targets/CSharp.Common.targets @@ -34,6 +34,12 @@ $(NoWarn);IDE0005 + + $(NoWarn);CA2007 + true diff --git a/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs b/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs index 677efe448fc1..f96b2dbf324c 100644 --- a/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs +++ b/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs @@ -101,7 +101,7 @@ public Task StopAsync(CancellationToken cancellationToken = default) // Yes, async void. We need to be async. We need to be void. We handle the exceptions in RunAsync private async void Timer_Tick(object? state) { - await RunAsync(); + await RunAsync().ConfigureAwait(false); } // Internal for testing @@ -125,7 +125,7 @@ internal async Task RunAsync() _runTokenSource = cancellation; cancellation.CancelAfter(timeout); - await RunAsyncCore(cancellation.Token); + await RunAsyncCore(cancellation.Token).ConfigureAwait(false); Logger.HealthCheckPublisherProcessingEnd(_logger, duration.GetElapsedTime()); } @@ -151,7 +151,7 @@ private async Task RunAsyncCore(CancellationToken cancellationToken) await Task.Yield(); // The health checks service does it's own logging, and doesn't throw exceptions. - var report = await _healthCheckService.CheckHealthAsync(_options.Value.Predicate, cancellationToken); + var report = await _healthCheckService.CheckHealthAsync(_options.Value.Predicate, cancellationToken).ConfigureAwait(false); var publishers = _publishers; var tasks = new Task[publishers.Length]; @@ -160,7 +160,7 @@ private async Task RunAsyncCore(CancellationToken cancellationToken) tasks[i] = RunPublisherAsync(publishers[i], report, cancellationToken); } - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); } private async Task RunPublisherAsync(IHealthCheckPublisher publisher, HealthReport report, CancellationToken cancellationToken) @@ -171,7 +171,7 @@ private async Task RunPublisherAsync(IHealthCheckPublisher publisher, HealthRepo { Logger.HealthCheckPublisherBegin(_logger, publisher); - await publisher.PublishAsync(report, cancellationToken); + await publisher.PublishAsync(report, cancellationToken).ConfigureAwait(false); Logger.HealthCheckPublisherEnd(_logger, publisher, duration.GetElapsedTime()); } catch (OperationCanceledException) when (IsStopping) diff --git a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs index b5829ee21a2c..659fea863463 100644 --- a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs @@ -20,7 +20,7 @@ public class AuthenticatorTokenProvider : IUserTwoFactorTokenProviderTrue if the user has an authenticator key set, otherwise false. public virtual async Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user) { - var key = await manager.GetAuthenticatorKeyAsync(user); + var key = await manager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false); return !string.IsNullOrWhiteSpace(key); } @@ -47,7 +47,7 @@ public virtual Task GenerateAsync(string purpose, UserManager man /// public virtual async Task ValidateAsync(string purpose, string token, UserManager manager, TUser user) { - var key = await manager.GetAuthenticatorKeyAsync(user); + var key = await manager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false); int code; if (key == null || !int.TryParse(token, out code)) { diff --git a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs index 9d83cdfef1bf..dca4a84439b8 100644 --- a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs +++ b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs @@ -19,6 +19,6 @@ public class DefaultUserConfirmation : IUserConfirmation where TUs /// The that represents the asynchronous operation, containing the of the confirmation operation. public virtual async Task IsConfirmedAsync(UserManager manager, TUser user) { - return await manager.IsEmailConfirmedAsync(user); + return await manager.IsEmailConfirmedAsync(user).ConfigureAwait(false); } } diff --git a/src/Identity/Extensions.Core/src/EmailTokenProvider.cs b/src/Identity/Extensions.Core/src/EmailTokenProvider.cs index 699287f1903e..d404d43174e8 100644 --- a/src/Identity/Extensions.Core/src/EmailTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/EmailTokenProvider.cs @@ -20,9 +20,9 @@ public class EmailTokenProvider : TotpSecurityStampBasedTokenProviderTrue if the user has an email address set, otherwise false. public override async Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user) { - var email = await manager.GetEmailAsync(user); + var email = await manager.GetEmailAsync(user).ConfigureAwait(false); - return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user); + return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user).ConfigureAwait(false); } /// @@ -35,7 +35,7 @@ public override async Task CanGenerateTwoFactorTokenAsync(UserManager GetUserModifierAsync(string purpose, UserManager manager, TUser user) { - var email = await manager.GetEmailAsync(user); + var email = await manager.GetEmailAsync(user).ConfigureAwait(false); return $"Email:{purpose}:{email}"; } diff --git a/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs b/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs index 6b850ab2da7d..6de45d6a6080 100644 --- a/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs @@ -33,9 +33,9 @@ public override async Task CanGenerateTwoFactorTokenAsync(UserManager @@ -55,7 +55,7 @@ public override async Task GetUserModifierAsync(string purpose, UserMana throw new ArgumentNullException(nameof(manager)); } - var phoneNumber = await manager.GetPhoneNumberAsync(user); + var phoneNumber = await manager.GetPhoneNumberAsync(user).ConfigureAwait(false); return $"PhoneNumber:{purpose}:{phoneNumber}"; } diff --git a/src/Identity/Extensions.Core/src/RoleManager.cs b/src/Identity/Extensions.Core/src/RoleManager.cs index ac6783cf2b61..6e9b9973e29f 100644 --- a/src/Identity/Extensions.Core/src/RoleManager.cs +++ b/src/Identity/Extensions.Core/src/RoleManager.cs @@ -160,13 +160,13 @@ public virtual async Task CreateAsync(TRole role) { throw new ArgumentNullException(nameof(role)); } - var result = await ValidateRoleAsync(role); + var result = await ValidateRoleAsync(role).ConfigureAwait(false); if (!result.Succeeded) { return result; } - await UpdateNormalizedRoleNameAsync(role); - result = await Store.CreateAsync(role, CancellationToken); + await UpdateNormalizedRoleNameAsync(role).ConfigureAwait(false); + result = await Store.CreateAsync(role, CancellationToken).ConfigureAwait(false); return result; } @@ -179,8 +179,8 @@ public virtual async Task CreateAsync(TRole role) /// public virtual async Task UpdateNormalizedRoleNameAsync(TRole role) { - var name = await GetRoleNameAsync(role); - await Store.SetNormalizedRoleNameAsync(role, NormalizeKey(name), CancellationToken); + var name = await GetRoleNameAsync(role).ConfigureAwait(false); + await Store.SetNormalizedRoleNameAsync(role, NormalizeKey(name), CancellationToken).ConfigureAwait(false); } /// @@ -234,7 +234,7 @@ public virtual async Task RoleExistsAsync(string roleName) throw new ArgumentNullException(nameof(roleName)); } - return await FindByNameAsync(roleName) != null; + return await FindByNameAsync(roleName).ConfigureAwait(false) != null; } /// @@ -288,8 +288,8 @@ public virtual async Task SetRoleNameAsync(TRole role, string na { ThrowIfDisposed(); - await Store.SetRoleNameAsync(role, name, CancellationToken); - await UpdateNormalizedRoleNameAsync(role); + await Store.SetRoleNameAsync(role, name, CancellationToken).ConfigureAwait(false); + await UpdateNormalizedRoleNameAsync(role).ConfigureAwait(false); return IdentityResult.Success; } @@ -348,8 +348,8 @@ public virtual async Task AddClaimAsync(TRole role, Claim claim) throw new ArgumentNullException(nameof(role)); } - await claimStore.AddClaimAsync(role, claim, CancellationToken); - return await UpdateRoleAsync(role); + await claimStore.AddClaimAsync(role, claim, CancellationToken).ConfigureAwait(false); + return await UpdateRoleAsync(role).ConfigureAwait(false); } /// @@ -370,8 +370,8 @@ public virtual async Task RemoveClaimAsync(TRole role, Claim cla throw new ArgumentNullException(nameof(role)); } - await claimStore.RemoveClaimAsync(role, claim, CancellationToken); - return await UpdateRoleAsync(role); + await claimStore.RemoveClaimAsync(role, claim, CancellationToken).ConfigureAwait(false); + return await UpdateRoleAsync(role).ConfigureAwait(false); } /// @@ -426,7 +426,7 @@ protected virtual async Task ValidateRoleAsync(TRole role) var errors = new List(); foreach (var v in RoleValidators) { - var result = await v.ValidateAsync(this, role); + var result = await v.ValidateAsync(this, role).ConfigureAwait(false); if (!result.Succeeded) { errors.AddRange(result.Errors); @@ -434,7 +434,7 @@ protected virtual async Task ValidateRoleAsync(TRole role) } if (errors.Count > 0) { - Logger.LogWarning(LoggerEventIds.RoleValidationFailed, "Role {roleId} validation failed: {errors}.", await GetRoleIdAsync(role), string.Join(";", errors.Select(e => e.Code))); + Logger.LogWarning(LoggerEventIds.RoleValidationFailed, "Role {roleId} validation failed: {errors}.", await GetRoleIdAsync(role).ConfigureAwait(false), string.Join(";", errors.Select(e => e.Code))); return IdentityResult.Failed(errors.ToArray()); } return IdentityResult.Success; @@ -447,13 +447,13 @@ protected virtual async Task ValidateRoleAsync(TRole role) /// Whether the operation was successful. protected virtual async Task UpdateRoleAsync(TRole role) { - var result = await ValidateRoleAsync(role); + var result = await ValidateRoleAsync(role).ConfigureAwait(false); if (!result.Succeeded) { return result; } - await UpdateNormalizedRoleNameAsync(role); - return await Store.UpdateAsync(role, CancellationToken); + await UpdateNormalizedRoleNameAsync(role).ConfigureAwait(false); + return await Store.UpdateAsync(role, CancellationToken).ConfigureAwait(false); } // IRoleClaimStore methods diff --git a/src/Identity/Extensions.Core/src/RoleValidator.cs b/src/Identity/Extensions.Core/src/RoleValidator.cs index 47c3a9e05a06..b55cbc9ee27c 100644 --- a/src/Identity/Extensions.Core/src/RoleValidator.cs +++ b/src/Identity/Extensions.Core/src/RoleValidator.cs @@ -41,7 +41,7 @@ public virtual async Task ValidateAsync(RoleManager manag throw new ArgumentNullException(nameof(role)); } var errors = new List(); - await ValidateRoleName(manager, role, errors); + await ValidateRoleName(manager, role, errors).ConfigureAwait(false); if (errors.Count > 0) { return IdentityResult.Failed(errors.ToArray()); @@ -52,16 +52,16 @@ public virtual async Task ValidateAsync(RoleManager manag private async Task ValidateRoleName(RoleManager manager, TRole role, ICollection errors) { - var roleName = await manager.GetRoleNameAsync(role); + var roleName = await manager.GetRoleNameAsync(role).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(roleName)) { errors.Add(Describer.InvalidRoleName(roleName)); } else { - var owner = await manager.FindByNameAsync(roleName); + var owner = await manager.FindByNameAsync(roleName).ConfigureAwait(false); if (owner != null && - !string.Equals(await manager.GetRoleIdAsync(owner), await manager.GetRoleIdAsync(role))) + !string.Equals(await manager.GetRoleIdAsync(owner).ConfigureAwait(false), await manager.GetRoleIdAsync(role).ConfigureAwait(false))) { errors.Add(Describer.DuplicateRoleName(roleName)); } diff --git a/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs b/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs index de8d86def293..557a2d8b9cac 100644 --- a/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs @@ -39,8 +39,8 @@ public virtual async Task GenerateAsync(string purpose, UserManager ValidateAsync(string purpose, string token, User { return false; } - var securityToken = await manager.CreateSecurityTokenAsync(user); - var modifier = await GetUserModifierAsync(purpose, manager, user); + var securityToken = await manager.CreateSecurityTokenAsync(user).ConfigureAwait(false); + var modifier = await GetUserModifierAsync(purpose, manager, user).ConfigureAwait(false); return securityToken != null && Rfc6238AuthenticationService.ValidateCode(securityToken, code, modifier); } @@ -91,7 +91,7 @@ public virtual async Task GetUserModifierAsync(string purpose, UserManag { throw new ArgumentNullException(nameof(manager)); } - var userId = await manager.GetUserIdAsync(user); + var userId = await manager.GetUserIdAsync(user).ConfigureAwait(false); return $"Totp:{purpose}:{userId}"; } diff --git a/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs b/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs index 5f439169f566..4aef50f5e80a 100644 --- a/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs +++ b/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs @@ -63,7 +63,7 @@ public virtual async Task CreateAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - var id = await GenerateClaimsAsync(user); + var id = await GenerateClaimsAsync(user).ConfigureAwait(false); return new ClaimsPrincipal(id); } @@ -74,8 +74,8 @@ public virtual async Task CreateAsync(TUser user) /// The that represents the asynchronous creation operation, containing the created . protected virtual async Task GenerateClaimsAsync(TUser user) { - var userId = await UserManager.GetUserIdAsync(user); - var userName = await UserManager.GetUserNameAsync(user); + var userId = await UserManager.GetUserIdAsync(user).ConfigureAwait(false); + var userName = await UserManager.GetUserNameAsync(user).ConfigureAwait(false); var id = new ClaimsIdentity("Identity.Application", // REVIEW: Used to match Application scheme Options.ClaimsIdentity.UserNameClaimType, Options.ClaimsIdentity.RoleClaimType); @@ -83,7 +83,7 @@ protected virtual async Task GenerateClaimsAsync(TUser user) id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, userName)); if (UserManager.SupportsUserEmail) { - var email = await UserManager.GetEmailAsync(user); + var email = await UserManager.GetEmailAsync(user).ConfigureAwait(false); if (!string.IsNullOrEmpty(email)) { id.AddClaim(new Claim(Options.ClaimsIdentity.EmailClaimType, email)); @@ -92,11 +92,11 @@ protected virtual async Task GenerateClaimsAsync(TUser user) if (UserManager.SupportsUserSecurityStamp) { id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType, - await UserManager.GetSecurityStampAsync(user))); + await UserManager.GetSecurityStampAsync(user).ConfigureAwait(false))); } if (UserManager.SupportsUserClaim) { - id.AddClaims(await UserManager.GetClaimsAsync(user)); + id.AddClaims(await UserManager.GetClaimsAsync(user).ConfigureAwait(false)); } return id; } @@ -142,19 +142,19 @@ public UserClaimsPrincipalFactory(UserManager userManager, RoleManagerThe that represents the asynchronous creation operation, containing the created . protected override async Task GenerateClaimsAsync(TUser user) { - var id = await base.GenerateClaimsAsync(user); + var id = await base.GenerateClaimsAsync(user).ConfigureAwait(false); if (UserManager.SupportsUserRole) { - var roles = await UserManager.GetRolesAsync(user); + var roles = await UserManager.GetRolesAsync(user).ConfigureAwait(false); foreach (var roleName in roles) { id.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, roleName)); if (RoleManager.SupportsRoleClaims) { - var role = await RoleManager.FindByNameAsync(roleName); + var role = await RoleManager.FindByNameAsync(roleName).ConfigureAwait(false); if (role != null) { - id.AddClaims(await RoleManager.GetClaimsAsync(role)); + id.AddClaims(await RoleManager.GetClaimsAsync(role).ConfigureAwait(false)); } } } diff --git a/src/Identity/Extensions.Core/src/UserManager.cs b/src/Identity/Extensions.Core/src/UserManager.cs index feb77b4c3229..7b73b63d8fd5 100644 --- a/src/Identity/Extensions.Core/src/UserManager.cs +++ b/src/Identity/Extensions.Core/src/UserManager.cs @@ -466,20 +466,20 @@ public virtual Task GenerateConcurrencyStampAsync(TUser user) public virtual async Task CreateAsync(TUser user) { ThrowIfDisposed(); - await UpdateSecurityStampInternal(user); - var result = await ValidateUserAsync(user); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + var result = await ValidateUserAsync(user).ConfigureAwait(false); if (!result.Succeeded) { return result; } if (Options.Lockout.AllowedForNewUsers && SupportsUserLockout) { - await GetUserLockoutStore().SetLockoutEnabledAsync(user, true, CancellationToken); + await GetUserLockoutStore().SetLockoutEnabledAsync(user, true, CancellationToken).ConfigureAwait(false); } - await UpdateNormalizedUserNameAsync(user); - await UpdateNormalizedEmailAsync(user); + await UpdateNormalizedUserNameAsync(user).ConfigureAwait(false); + await UpdateNormalizedEmailAsync(user).ConfigureAwait(false); - return await Store.CreateAsync(user, CancellationToken); + return await Store.CreateAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -549,7 +549,7 @@ public virtual async Task FindByNameAsync(string userName) } userName = NormalizeName(userName); - var user = await Store.FindByNameAsync(userName, CancellationToken); + var user = await Store.FindByNameAsync(userName, CancellationToken).ConfigureAwait(false); // Need to potentially check all keys if (user == null && Options.Stores.ProtectPersonalData) @@ -561,7 +561,7 @@ public virtual async Task FindByNameAsync(string userName) foreach (var key in keyRing.GetAllKeyIds()) { var oldKey = protector.Protect(key, userName); - user = await Store.FindByNameAsync(oldKey, CancellationToken); + user = await Store.FindByNameAsync(oldKey, CancellationToken).ConfigureAwait(false); if (user != null) { return user; @@ -594,12 +594,12 @@ public virtual async Task CreateAsync(TUser user, string passwor { throw new ArgumentNullException(nameof(password)); } - var result = await UpdatePasswordHash(passwordStore, user, password); + var result = await UpdatePasswordHash(passwordStore, user, password).ConfigureAwait(false); if (!result.Succeeded) { return result; } - return await CreateAsync(user); + return await CreateAsync(user).ConfigureAwait(false); } /// @@ -636,9 +636,9 @@ private string ProtectPersonalData(string data) /// The that represents the asynchronous operation. public virtual async Task UpdateNormalizedUserNameAsync(TUser user) { - var normalizedName = NormalizeName(await GetUserNameAsync(user)); + var normalizedName = NormalizeName(await GetUserNameAsync(user).ConfigureAwait(false)); normalizedName = ProtectPersonalData(normalizedName); - await Store.SetNormalizedUserNameAsync(user, normalizedName, CancellationToken); + await Store.SetNormalizedUserNameAsync(user, normalizedName, CancellationToken).ConfigureAwait(false); } /// @@ -653,7 +653,7 @@ public virtual async Task GetUserNameAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await Store.GetUserNameAsync(user, CancellationToken); + return await Store.GetUserNameAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -670,9 +670,9 @@ public virtual async Task SetUserNameAsync(TUser user, string us throw new ArgumentNullException(nameof(user)); } - await Store.SetUserNameAsync(user, userName, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await Store.SetUserNameAsync(user, userName, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -683,7 +683,7 @@ public virtual async Task SetUserNameAsync(TUser user, string us public virtual async Task GetUserIdAsync(TUser user) { ThrowIfDisposed(); - return await Store.GetUserIdAsync(user, CancellationToken); + return await Store.GetUserIdAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -704,11 +704,11 @@ public virtual async Task CheckPasswordAsync(TUser user, string password) return false; } - var result = await VerifyPasswordAsync(passwordStore, user, password); + var result = await VerifyPasswordAsync(passwordStore, user, password).ConfigureAwait(false); if (result == PasswordVerificationResult.SuccessRehashNeeded) { - await UpdatePasswordHash(passwordStore, user, password, validatePassword: false); - await UpdateUserAsync(user); + await UpdatePasswordHash(passwordStore, user, password, validatePassword: false).ConfigureAwait(false); + await UpdateUserAsync(user).ConfigureAwait(false); } var success = result != PasswordVerificationResult.Failed; @@ -758,18 +758,18 @@ public virtual async Task AddPasswordAsync(TUser user, string pa throw new ArgumentNullException(nameof(user)); } - var hash = await passwordStore.GetPasswordHashAsync(user, CancellationToken); + var hash = await passwordStore.GetPasswordHashAsync(user, CancellationToken).ConfigureAwait(false); if (hash != null) { Logger.LogWarning(LoggerEventIds.UserAlreadyHasPassword, "User already has a password."); return IdentityResult.Failed(ErrorDescriber.UserAlreadyHasPassword()); } - var result = await UpdatePasswordHash(passwordStore, user, password); + var result = await UpdatePasswordHash(passwordStore, user, password).ConfigureAwait(false); if (!result.Succeeded) { return result; } - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -792,14 +792,14 @@ public virtual async Task ChangePasswordAsync(TUser user, string throw new ArgumentNullException(nameof(user)); } - if (await VerifyPasswordAsync(passwordStore, user, currentPassword) != PasswordVerificationResult.Failed) + if (await VerifyPasswordAsync(passwordStore, user, currentPassword).ConfigureAwait(false) != PasswordVerificationResult.Failed) { - var result = await UpdatePasswordHash(passwordStore, user, newPassword); + var result = await UpdatePasswordHash(passwordStore, user, newPassword).ConfigureAwait(false); if (!result.Succeeded) { return result; } - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } Logger.LogWarning(LoggerEventIds.ChangePasswordFailed, "Change password failed for user."); return IdentityResult.Failed(ErrorDescriber.PasswordMismatch()); @@ -822,8 +822,8 @@ public virtual async Task RemovePasswordAsync(TUser user) throw new ArgumentNullException(nameof(user)); } - await UpdatePasswordHash(passwordStore, user, null, validatePassword: false); - return await UpdateUserAsync(user); + await UpdatePasswordHash(passwordStore, user, null, validatePassword: false).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -838,7 +838,7 @@ public virtual async Task RemovePasswordAsync(TUser user) /// protected virtual async Task VerifyPasswordAsync(IUserPasswordStore store, TUser user, string password) { - var hash = await store.GetPasswordHashAsync(user, CancellationToken); + var hash = await store.GetPasswordHashAsync(user, CancellationToken).ConfigureAwait(false); if (hash == null) { return PasswordVerificationResult.Failed; @@ -859,7 +859,7 @@ public virtual async Task GetSecurityStampAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - var stamp = await securityStore.GetSecurityStampAsync(user, CancellationToken); + var stamp = await securityStore.GetSecurityStampAsync(user, CancellationToken).ConfigureAwait(false); if (stamp == null) { Logger.LogWarning(LoggerEventIds.GetSecurityStampFailed, "GetSecurityStampAsync for user failed because stamp was null."); @@ -888,8 +888,8 @@ public virtual async Task UpdateSecurityStampAsync(TUser user) throw new ArgumentNullException(nameof(user)); } - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -925,16 +925,16 @@ public virtual async Task ResetPasswordAsync(TUser user, string } // Make sure the token is valid and the stamp matches - if (!await VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose, token)) + if (!await VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose, token).ConfigureAwait(false)) { return IdentityResult.Failed(ErrorDescriber.InvalidToken()); } - var result = await UpdatePasswordHash(user, newPassword, validatePassword: true); + var result = await UpdatePasswordHash(user, newPassword, validatePassword: true).ConfigureAwait(false); if (!result.Succeeded) { return result; } - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -988,9 +988,9 @@ public virtual async Task RemoveLoginAsync(TUser user, string lo throw new ArgumentNullException(nameof(user)); } - await loginStore.RemoveLoginAsync(user, loginProvider, providerKey, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await loginStore.RemoveLoginAsync(user, loginProvider, providerKey, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1015,14 +1015,14 @@ public virtual async Task AddLoginAsync(TUser user, UserLoginInf throw new ArgumentNullException(nameof(user)); } - var existingUser = await FindByLoginAsync(login.LoginProvider, login.ProviderKey); + var existingUser = await FindByLoginAsync(login.LoginProvider, login.ProviderKey).ConfigureAwait(false); if (existingUser != null) { Logger.LogWarning(LoggerEventIds.AddLoginFailed, "AddLogin for user failed because it was already associated with another user."); return IdentityResult.Failed(ErrorDescriber.LoginAlreadyAssociated()); } - await loginStore.AddLoginAsync(user, login, CancellationToken); - return await UpdateUserAsync(user); + await loginStore.AddLoginAsync(user, login, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1040,7 +1040,7 @@ public virtual async Task> GetLoginsAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await loginStore.GetLoginsAsync(user, CancellationToken); + return await loginStore.GetLoginsAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1089,8 +1089,8 @@ public virtual async Task AddClaimsAsync(TUser user, IEnumerable throw new ArgumentNullException(nameof(user)); } - await claimStore.AddClaimsAsync(user, claims, CancellationToken); - return await UpdateUserAsync(user); + await claimStore.AddClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1120,8 +1120,8 @@ public virtual async Task ReplaceClaimAsync(TUser user, Claim cl throw new ArgumentNullException(nameof(user)); } - await claimStore.ReplaceClaimAsync(user, claim, newClaim, CancellationToken); - return await UpdateUserAsync(user); + await claimStore.ReplaceClaimAsync(user, claim, newClaim, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1170,8 +1170,8 @@ public virtual async Task RemoveClaimsAsync(TUser user, IEnumera throw new ArgumentNullException(nameof(claims)); } - await claimStore.RemoveClaimsAsync(user, claims, CancellationToken); - return await UpdateUserAsync(user); + await claimStore.RemoveClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1189,7 +1189,7 @@ public virtual async Task> GetClaimsAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await claimStore.GetClaimsAsync(user, CancellationToken); + return await claimStore.GetClaimsAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1211,12 +1211,12 @@ public virtual async Task AddToRoleAsync(TUser user, string role } var normalizedRole = NormalizeName(role); - if (await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken)) + if (await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) { return UserAlreadyInRoleError(role); } - await userRoleStore.AddToRoleAsync(user, normalizedRole, CancellationToken); - return await UpdateUserAsync(user); + await userRoleStore.AddToRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1244,13 +1244,13 @@ public virtual async Task AddToRolesAsync(TUser user, IEnumerabl foreach (var role in roles.Distinct()) { var normalizedRole = NormalizeName(role); - if (await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken)) + if (await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) { return UserAlreadyInRoleError(role); } - await userRoleStore.AddToRoleAsync(user, normalizedRole, CancellationToken); + await userRoleStore.AddToRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false); } - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1272,12 +1272,12 @@ public virtual async Task RemoveFromRoleAsync(TUser user, string } var normalizedRole = NormalizeName(role); - if (!await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken)) + if (!await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) { return UserNotInRoleError(role); } - await userRoleStore.RemoveFromRoleAsync(user, normalizedRole, CancellationToken); - return await UpdateUserAsync(user); + await userRoleStore.RemoveFromRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } private IdentityResult UserAlreadyInRoleError(string role) @@ -1317,13 +1317,13 @@ public virtual async Task RemoveFromRolesAsync(TUser user, IEnum foreach (var role in roles) { var normalizedRole = NormalizeName(role); - if (!await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken)) + if (!await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) { return UserNotInRoleError(role); } - await userRoleStore.RemoveFromRoleAsync(user, normalizedRole, CancellationToken); + await userRoleStore.RemoveFromRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false); } - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1339,7 +1339,7 @@ public virtual async Task> GetRolesAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await userRoleStore.GetRolesAsync(user, CancellationToken); + return await userRoleStore.GetRolesAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1359,7 +1359,7 @@ public virtual async Task IsInRoleAsync(TUser user, string role) { throw new ArgumentNullException(nameof(user)); } - return await userRoleStore.IsInRoleAsync(user, NormalizeName(role), CancellationToken); + return await userRoleStore.IsInRoleAsync(user, NormalizeName(role), CancellationToken).ConfigureAwait(false); } /// @@ -1375,7 +1375,7 @@ public virtual async Task GetEmailAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetEmailAsync(user, CancellationToken); + return await store.GetEmailAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1396,10 +1396,10 @@ public virtual async Task SetEmailAsync(TUser user, string email throw new ArgumentNullException(nameof(user)); } - await store.SetEmailAsync(user, email, CancellationToken); - await store.SetEmailConfirmedAsync(user, false, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await store.SetEmailAsync(user, email, CancellationToken).ConfigureAwait(false); + await store.SetEmailConfirmedAsync(user, false, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1421,7 +1421,7 @@ public virtual async Task FindByEmailAsync(string email) } email = NormalizeEmail(email); - var user = await store.FindByEmailAsync(email, CancellationToken); + var user = await store.FindByEmailAsync(email, CancellationToken).ConfigureAwait(false); // Need to potentially check all keys if (user == null && Options.Stores.ProtectPersonalData) @@ -1433,7 +1433,7 @@ public virtual async Task FindByEmailAsync(string email) foreach (var key in keyRing.GetAllKeyIds()) { var oldKey = protector.Protect(key, email); - user = await store.FindByEmailAsync(oldKey, CancellationToken); + user = await store.FindByEmailAsync(oldKey, CancellationToken).ConfigureAwait(false); if (user != null) { return user; @@ -1454,8 +1454,8 @@ public virtual async Task UpdateNormalizedEmailAsync(TUser user) var store = GetEmailStore(throwOnFail: false); if (store != null) { - var email = await GetEmailAsync(user); - await store.SetNormalizedEmailAsync(user, ProtectPersonalData(NormalizeEmail(email)), CancellationToken); + var email = await GetEmailAsync(user).ConfigureAwait(false); + await store.SetNormalizedEmailAsync(user, ProtectPersonalData(NormalizeEmail(email)), CancellationToken).ConfigureAwait(false); } } @@ -1490,12 +1490,12 @@ public virtual async Task ConfirmEmailAsync(TUser user, string t throw new ArgumentNullException(nameof(user)); } - if (!await VerifyUserTokenAsync(user, Options.Tokens.EmailConfirmationTokenProvider, ConfirmEmailTokenPurpose, token)) + if (!await VerifyUserTokenAsync(user, Options.Tokens.EmailConfirmationTokenProvider, ConfirmEmailTokenPurpose, token).ConfigureAwait(false)) { return IdentityResult.Failed(ErrorDescriber.InvalidToken()); } - await store.SetEmailConfirmedAsync(user, true, CancellationToken); - return await UpdateUserAsync(user); + await store.SetEmailConfirmedAsync(user, true, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1515,7 +1515,7 @@ public virtual async Task IsEmailConfirmedAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetEmailConfirmedAsync(user, CancellationToken); + return await store.GetEmailConfirmedAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1551,15 +1551,15 @@ public virtual async Task ChangeEmailAsync(TUser user, string ne } // Make sure the token is valid and the stamp matches - if (!await VerifyUserTokenAsync(user, Options.Tokens.ChangeEmailTokenProvider, GetChangeEmailTokenPurpose(newEmail), token)) + if (!await VerifyUserTokenAsync(user, Options.Tokens.ChangeEmailTokenProvider, GetChangeEmailTokenPurpose(newEmail), token).ConfigureAwait(false)) { return IdentityResult.Failed(ErrorDescriber.InvalidToken()); } var store = GetEmailStore(); - await store.SetEmailAsync(user, newEmail, CancellationToken); - await store.SetEmailConfirmedAsync(user, true, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await store.SetEmailAsync(user, newEmail, CancellationToken).ConfigureAwait(false); + await store.SetEmailConfirmedAsync(user, true, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1575,7 +1575,7 @@ public virtual async Task GetPhoneNumberAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetPhoneNumberAsync(user, CancellationToken); + return await store.GetPhoneNumberAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1596,10 +1596,10 @@ public virtual async Task SetPhoneNumberAsync(TUser user, string throw new ArgumentNullException(nameof(user)); } - await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken); - await store.SetPhoneNumberConfirmedAsync(user, false, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken).ConfigureAwait(false); + await store.SetPhoneNumberConfirmedAsync(user, false, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1622,15 +1622,15 @@ public virtual async Task ChangePhoneNumberAsync(TUser user, str throw new ArgumentNullException(nameof(user)); } - if (!await VerifyChangePhoneNumberTokenAsync(user, token, phoneNumber)) + if (!await VerifyChangePhoneNumberTokenAsync(user, token, phoneNumber).ConfigureAwait(false)) { Logger.LogWarning(LoggerEventIds.PhoneNumberChanged, "Change phone number for user failed with invalid token."); return IdentityResult.Failed(ErrorDescriber.InvalidToken()); } - await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken); - await store.SetPhoneNumberConfirmedAsync(user, true, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken).ConfigureAwait(false); + await store.SetPhoneNumberConfirmedAsync(user, true, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1718,7 +1718,7 @@ public virtual async Task VerifyUserTokenAsync(TUser user, string tokenPro throw new NotSupportedException(Resources.FormatNoTokenProvider(nameof(TUser), tokenProvider)); } // Make sure the token is valid - var result = await _tokenProviders[tokenProvider].ValidateAsync(purpose, token, this, user); + var result = await _tokenProviders[tokenProvider].ValidateAsync(purpose, token, this, user).ConfigureAwait(false); if (!result) { @@ -1790,7 +1790,7 @@ public virtual async Task> GetValidTwoFactorProvidersAsync(TUser u var results = new List(); foreach (var f in _tokenProviders) { - if (await f.Value.CanGenerateTwoFactorTokenAsync(this, user)) + if (await f.Value.CanGenerateTwoFactorTokenAsync(this, user).ConfigureAwait(false)) { results.Add(f.Key); } @@ -1821,7 +1821,7 @@ public virtual async Task VerifyTwoFactorTokenAsync(TUser user, string tok } // Make sure the token is valid - var result = await _tokenProviders[tokenProvider].ValidateAsync("TwoFactor", token, this, user); + var result = await _tokenProviders[tokenProvider].ValidateAsync("TwoFactor", token, this, user).ConfigureAwait(false); if (!result) { Logger.LogWarning(LoggerEventIds.VerifyTwoFactorTokenFailed, $"{nameof(VerifyTwoFactorTokenAsync)}() failed for user."); @@ -1870,7 +1870,7 @@ public virtual async Task GetTwoFactorEnabledAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetTwoFactorEnabledAsync(user, CancellationToken); + return await store.GetTwoFactorEnabledAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1891,9 +1891,9 @@ public virtual async Task SetTwoFactorEnabledAsync(TUser user, b throw new ArgumentNullException(nameof(user)); } - await store.SetTwoFactorEnabledAsync(user, enabled, CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateUserAsync(user); + await store.SetTwoFactorEnabledAsync(user, enabled, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1913,11 +1913,11 @@ public virtual async Task IsLockedOutAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - if (!await store.GetLockoutEnabledAsync(user, CancellationToken)) + if (!await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false)) { return false; } - var lockoutTime = await store.GetLockoutEndDateAsync(user, CancellationToken); + var lockoutTime = await store.GetLockoutEndDateAsync(user, CancellationToken).ConfigureAwait(false); return lockoutTime >= DateTimeOffset.UtcNow; } @@ -1939,8 +1939,8 @@ public virtual async Task SetLockoutEnabledAsync(TUser user, boo throw new ArgumentNullException(nameof(user)); } - await store.SetLockoutEnabledAsync(user, enabled, CancellationToken); - return await UpdateUserAsync(user); + await store.SetLockoutEnabledAsync(user, enabled, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -1958,7 +1958,7 @@ public virtual async Task GetLockoutEnabledAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetLockoutEnabledAsync(user, CancellationToken); + return await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1977,7 +1977,7 @@ public virtual async Task GetLockoutEnabledAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetLockoutEndDateAsync(user, CancellationToken); + return await store.GetLockoutEndDateAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -1995,13 +1995,13 @@ public virtual async Task SetLockoutEndDateAsync(TUser user, Dat throw new ArgumentNullException(nameof(user)); } - if (!await store.GetLockoutEnabledAsync(user, CancellationToken)) + if (!await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false)) { Logger.LogWarning(LoggerEventIds.LockoutFailed, "Lockout for user failed because lockout is not enabled for this user."); return IdentityResult.Failed(ErrorDescriber.UserLockoutNotEnabled()); } - await store.SetLockoutEndDateAsync(user, lockoutEnd, CancellationToken); - return await UpdateUserAsync(user); + await store.SetLockoutEndDateAsync(user, lockoutEnd, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -2021,16 +2021,16 @@ public virtual async Task AccessFailedAsync(TUser user) } // If this puts the user over the threshold for lockout, lock them out and reset the access failed count - var count = await store.IncrementAccessFailedCountAsync(user, CancellationToken); + var count = await store.IncrementAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); if (count < Options.Lockout.MaxFailedAccessAttempts) { - return await UpdateUserAsync(user); + return await UpdateUserAsync(user).ConfigureAwait(false); } Logger.LogWarning(LoggerEventIds.UserLockedOut, "User is locked out."); await store.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(Options.Lockout.DefaultLockoutTimeSpan), - CancellationToken); - await store.ResetAccessFailedCountAsync(user, CancellationToken); - return await UpdateUserAsync(user); + CancellationToken).ConfigureAwait(false); + await store.ResetAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -2047,12 +2047,12 @@ public virtual async Task ResetAccessFailedCountAsync(TUser user throw new ArgumentNullException(nameof(user)); } - if (await GetAccessFailedCountAsync(user) == 0) + if (await GetAccessFailedCountAsync(user).ConfigureAwait(false) == 0) { return IdentityResult.Success; } - await store.ResetAccessFailedCountAsync(user, CancellationToken); - return await UpdateUserAsync(user); + await store.ResetAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -2069,7 +2069,7 @@ public virtual async Task GetAccessFailedCountAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - return await store.GetAccessFailedCountAsync(user, CancellationToken); + return await store.GetAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); } /// @@ -2164,8 +2164,8 @@ public virtual async Task SetAuthenticationTokenAsync(TUser user } // REVIEW: should updating any tokens affect the security stamp? - await store.SetTokenAsync(user, loginProvider, tokenName, tokenValue, CancellationToken); - return await UpdateUserAsync(user); + await store.SetTokenAsync(user, loginProvider, tokenName, tokenValue, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -2192,8 +2192,8 @@ public virtual async Task RemoveAuthenticationTokenAsync(TUser u throw new ArgumentNullException(nameof(tokenName)); } - await store.RemoveTokenAsync(user, loginProvider, tokenName, CancellationToken); - return await UpdateUserAsync(user); + await store.RemoveTokenAsync(user, loginProvider, tokenName, CancellationToken).ConfigureAwait(false); + return await UpdateUserAsync(user).ConfigureAwait(false); } /// @@ -2225,9 +2225,9 @@ public virtual async Task ResetAuthenticatorKeyAsync(TUser user) { throw new ArgumentNullException(nameof(user)); } - await store.SetAuthenticatorKeyAsync(user, GenerateNewAuthenticatorKey(), CancellationToken); - await UpdateSecurityStampInternal(user); - return await UpdateAsync(user); + await store.SetAuthenticatorKeyAsync(user, GenerateNewAuthenticatorKey(), CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); + return await UpdateAsync(user).ConfigureAwait(false); } /// @@ -2258,8 +2258,8 @@ public virtual async Task> GenerateNewTwoFactorRecoveryCodes newCodes.Add(CreateTwoFactorRecoveryCode()); } - await store.ReplaceCodesAsync(user, newCodes.Distinct(), CancellationToken); - var update = await UpdateAsync(user); + await store.ReplaceCodesAsync(user, newCodes.Distinct(), CancellationToken).ConfigureAwait(false); + var update = await UpdateAsync(user).ConfigureAwait(false); if (update.Succeeded) { return newCodes; @@ -2290,10 +2290,10 @@ public virtual async Task RedeemTwoFactorRecoveryCodeAsync(TUser throw new ArgumentNullException(nameof(user)); } - var success = await store.RedeemCodeAsync(user, code, CancellationToken); + var success = await store.RedeemCodeAsync(user, code, CancellationToken).ConfigureAwait(false); if (success) { - return await UpdateAsync(user); + return await UpdateAsync(user).ConfigureAwait(false); } return IdentityResult.Failed(ErrorDescriber.RecoveryCodeRedemptionFailed()); } @@ -2375,7 +2375,7 @@ private IUserPhoneNumberStore GetPhoneNumberStore() /// The security token bytes. public virtual async Task CreateSecurityTokenAsync(TUser user) { - return Encoding.Unicode.GetBytes(await GetSecurityStampAsync(user)); + return Encoding.Unicode.GetBytes(await GetSecurityStampAsync(user).ConfigureAwait(false)); } // Update the security stamp if the store supports it @@ -2383,7 +2383,7 @@ private async Task UpdateSecurityStampInternal(TUser user) { if (SupportsUserSecurityStamp) { - await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp(), CancellationToken); + await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp(), CancellationToken).ConfigureAwait(false); } } @@ -2402,15 +2402,15 @@ private async Task UpdatePasswordHash(IUserPasswordStore { if (validatePassword) { - var validate = await ValidatePasswordAsync(user, newPassword); + var validate = await ValidatePasswordAsync(user, newPassword).ConfigureAwait(false); if (!validate.Succeeded) { return validate; } } var hash = newPassword != null ? PasswordHasher.HashPassword(user, newPassword) : null; - await passwordStore.SetPasswordHashAsync(user, hash, CancellationToken); - await UpdateSecurityStampInternal(user); + await passwordStore.SetPasswordHashAsync(user, hash, CancellationToken).ConfigureAwait(false); + await UpdateSecurityStampInternal(user).ConfigureAwait(false); return IdentityResult.Success; } @@ -2483,7 +2483,7 @@ protected async Task ValidateUserAsync(TUser user) { if (SupportsUserSecurityStamp) { - var stamp = await GetSecurityStampAsync(user); + var stamp = await GetSecurityStampAsync(user).ConfigureAwait(false); if (stamp == null) { throw new InvalidOperationException(Resources.NullSecurityStamp); @@ -2492,7 +2492,7 @@ protected async Task ValidateUserAsync(TUser user) var errors = new List(); foreach (var v in UserValidators) { - var result = await v.ValidateAsync(this, user); + var result = await v.ValidateAsync(this, user).ConfigureAwait(false); if (!result.Succeeded) { errors.AddRange(result.Errors); @@ -2519,7 +2519,7 @@ protected async Task ValidatePasswordAsync(TUser user, string pa var isValid = true; foreach (var v in PasswordValidators) { - var result = await v.ValidateAsync(this, user, password); + var result = await v.ValidateAsync(this, user, password).ConfigureAwait(false); if (!result.Succeeded) { if (result.Errors.Any()) @@ -2545,14 +2545,14 @@ protected async Task ValidatePasswordAsync(TUser user, string pa /// Whether the operation was successful. protected virtual async Task UpdateUserAsync(TUser user) { - var result = await ValidateUserAsync(user); + var result = await ValidateUserAsync(user).ConfigureAwait(false); if (!result.Succeeded) { return result; } - await UpdateNormalizedUserNameAsync(user); - await UpdateNormalizedEmailAsync(user); - return await Store.UpdateAsync(user, CancellationToken); + await UpdateNormalizedUserNameAsync(user).ConfigureAwait(false); + await UpdateNormalizedEmailAsync(user).ConfigureAwait(false); + return await Store.UpdateAsync(user, CancellationToken).ConfigureAwait(false); } private IUserAuthenticatorKeyStore GetAuthenticatorKeyStore() diff --git a/src/Identity/Extensions.Core/src/UserValidator.cs b/src/Identity/Extensions.Core/src/UserValidator.cs index bd173fdbeb5d..7a4c37989cb5 100644 --- a/src/Identity/Extensions.Core/src/UserValidator.cs +++ b/src/Identity/Extensions.Core/src/UserValidator.cs @@ -47,17 +47,17 @@ public virtual async Task ValidateAsync(UserManager manag throw new ArgumentNullException(nameof(user)); } var errors = new List(); - await ValidateUserName(manager, user, errors); + await ValidateUserName(manager, user, errors).ConfigureAwait(false); if (manager.Options.User.RequireUniqueEmail) { - await ValidateEmail(manager, user, errors); + await ValidateEmail(manager, user, errors).ConfigureAwait(false); } return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; } private async Task ValidateUserName(UserManager manager, TUser user, ICollection errors) { - var userName = await manager.GetUserNameAsync(user); + var userName = await manager.GetUserNameAsync(user).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(userName)) { errors.Add(Describer.InvalidUserName(userName)); @@ -69,9 +69,9 @@ private async Task ValidateUserName(UserManager manager, TUser user, ICol } else { - var owner = await manager.FindByNameAsync(userName); + var owner = await manager.FindByNameAsync(userName).ConfigureAwait(false); if (owner != null && - !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user))) + !string.Equals(await manager.GetUserIdAsync(owner).ConfigureAwait(false), await manager.GetUserIdAsync(user).ConfigureAwait(false))) { errors.Add(Describer.DuplicateUserName(userName)); } @@ -81,7 +81,7 @@ private async Task ValidateUserName(UserManager manager, TUser user, ICol // make sure email is not empty, valid, and unique private async Task ValidateEmail(UserManager manager, TUser user, List errors) { - var email = await manager.GetEmailAsync(user); + var email = await manager.GetEmailAsync(user).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(email)) { errors.Add(Describer.InvalidEmail(email)); @@ -92,9 +92,9 @@ private async Task ValidateEmail(UserManager manager, TUser user, List FindByLoginAsync(string loginProvider, string p { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - var userLogin = await FindUserLoginAsync(loginProvider, providerKey, cancellationToken); + var userLogin = await FindUserLoginAsync(loginProvider, providerKey, cancellationToken).ConfigureAwait(false); if (userLogin != null) { - return await FindUserAsync(userLogin.UserId, cancellationToken); + return await FindUserAsync(userLogin.UserId, cancellationToken).ConfigureAwait(false); } return null; } @@ -924,10 +924,10 @@ public virtual async Task SetTokenAsync(TUser user, string loginProvider, string throw new ArgumentNullException(nameof(user)); } - var token = await FindTokenAsync(user, loginProvider, name, cancellationToken); + var token = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); if (token == null) { - await AddUserTokenAsync(CreateUserToken(user, loginProvider, name, value)); + await AddUserTokenAsync(CreateUserToken(user, loginProvider, name, value)).ConfigureAwait(false); } else { @@ -952,10 +952,10 @@ public virtual async Task RemoveTokenAsync(TUser user, string loginProvider, str { throw new ArgumentNullException(nameof(user)); } - var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken); + var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); if (entry != null) { - await RemoveUserTokenAsync(entry); + await RemoveUserTokenAsync(entry).ConfigureAwait(false); } } @@ -976,7 +976,7 @@ public virtual async Task GetTokenAsync(TUser user, string loginProvider { throw new ArgumentNullException(nameof(user)); } - var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken); + var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); return entry?.Value; } @@ -1018,7 +1018,7 @@ public virtual async Task CountCodesAsync(TUser user, CancellationToken can { throw new ArgumentNullException(nameof(user)); } - var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; + var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken).ConfigureAwait(false) ?? ""; if (mergedCodes.Length > 0) { return mergedCodes.Split(';').Length; @@ -1061,12 +1061,12 @@ public virtual async Task RedeemCodeAsync(TUser user, string code, Cancell throw new ArgumentNullException(nameof(code)); } - var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; + var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken).ConfigureAwait(false) ?? ""; var splitCodes = mergedCodes.Split(';'); if (splitCodes.Contains(code)) { var updatedCodes = new List(splitCodes.Where(s => s != code)); - await ReplaceCodesAsync(user, updatedCodes, cancellationToken); + await ReplaceCodesAsync(user, updatedCodes, cancellationToken).ConfigureAwait(false); return true; } return false; diff --git a/src/Logging.AzureAppServices/src/BatchingLoggerProvider.cs b/src/Logging.AzureAppServices/src/BatchingLoggerProvider.cs index e947781e7d36..b2b0cb2d2927 100644 --- a/src/Logging.AzureAppServices/src/BatchingLoggerProvider.cs +++ b/src/Logging.AzureAppServices/src/BatchingLoggerProvider.cs @@ -103,7 +103,7 @@ private async Task ProcessLogQueue() { try { - await WriteMessagesAsync(_currentBatch, _cancellationTokenSource.Token); + await WriteMessagesAsync(_currentBatch, _cancellationTokenSource.Token).ConfigureAwait(false); } catch { @@ -114,7 +114,7 @@ private async Task ProcessLogQueue() } else { - await IntervalAsync(_interval, _cancellationTokenSource.Token); + await IntervalAsync(_interval, _cancellationTokenSource.Token).ConfigureAwait(false); } } } diff --git a/src/Logging.AzureAppServices/src/BlobAppendReferenceWrapper.cs b/src/Logging.AzureAppServices/src/BlobAppendReferenceWrapper.cs index 5ff69160275e..38749564fde8 100644 --- a/src/Logging.AzureAppServices/src/BlobAppendReferenceWrapper.cs +++ b/src/Logging.AzureAppServices/src/BlobAppendReferenceWrapper.cs @@ -41,7 +41,7 @@ Task AppendDataAsync() return _client.SendAsync(message, cancellationToken); } - var response = await AppendDataAsync(); + var response = await AppendDataAsync().ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.NotFound) { @@ -58,14 +58,14 @@ Task AppendDataAsync() AddCommonHeaders(message); - response = await _client.SendAsync(message, cancellationToken); + response = await _client.SendAsync(message, cancellationToken).ConfigureAwait(false); // If result is 2** or 412 try to append again if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.PreconditionFailed) { // Retry sending data after blob creation - response = await AppendDataAsync(); + response = await AppendDataAsync().ConfigureAwait(false); } } diff --git a/src/Logging.AzureAppServices/src/BlobLoggerProvider.cs b/src/Logging.AzureAppServices/src/BlobLoggerProvider.cs index 7b74f20e8e92..b85d7984181b 100644 --- a/src/Logging.AzureAppServices/src/BlobLoggerProvider.cs +++ b/src/Logging.AzureAppServices/src/BlobLoggerProvider.cs @@ -76,10 +76,10 @@ internal override async Task WriteMessagesAsync(IEnumerable messages writer.Write(logEvent.Message); } - await writer.FlushAsync(); + await writer.FlushAsync().ConfigureAwait(false); var tryGetBuffer = stream.TryGetBuffer(out var buffer); System.Diagnostics.Debug.Assert(tryGetBuffer); - await blob.AppendAsync(buffer, cancellationToken); + await blob.AppendAsync(buffer, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Logging.AzureAppServices/src/FileLoggerProvider.cs b/src/Logging.AzureAppServices/src/FileLoggerProvider.cs index 1ca2efa38071..8291b8520c40 100644 --- a/src/Logging.AzureAppServices/src/FileLoggerProvider.cs +++ b/src/Logging.AzureAppServices/src/FileLoggerProvider.cs @@ -53,7 +53,7 @@ internal override async Task WriteMessagesAsync(IEnumerable messages { foreach (var item in group) { - await streamWriter.WriteAsync(item.Message); + await streamWriter.WriteAsync(item.Message).ConfigureAwait(false); } } } diff --git a/src/Security/Authorization/Core/src/AssertionRequirement.cs b/src/Security/Authorization/Core/src/AssertionRequirement.cs index 46a6c7ec64d9..15865bf056aa 100644 --- a/src/Security/Authorization/Core/src/AssertionRequirement.cs +++ b/src/Security/Authorization/Core/src/AssertionRequirement.cs @@ -51,7 +51,7 @@ public AssertionRequirement(Func> handle /// The authorization information. public async Task HandleAsync(AuthorizationHandlerContext context) { - if (await Handler(context)) + if (await Handler(context).ConfigureAwait(false)) { context.Succeed(this); } diff --git a/src/Security/Authorization/Core/src/AuthorizationHandler.cs b/src/Security/Authorization/Core/src/AuthorizationHandler.cs index 7880614ecbc1..8b3b6cdf2be4 100644 --- a/src/Security/Authorization/Core/src/AuthorizationHandler.cs +++ b/src/Security/Authorization/Core/src/AuthorizationHandler.cs @@ -21,7 +21,7 @@ public virtual async Task HandleAsync(AuthorizationHandlerContext context) { foreach (var req in context.Requirements.OfType()) { - await HandleRequirementAsync(context, req); + await HandleRequirementAsync(context, req).ConfigureAwait(false); } } @@ -52,7 +52,7 @@ public virtual async Task HandleAsync(AuthorizationHandlerContext context) { foreach (var req in context.Requirements.OfType()) { - await HandleRequirementAsync(context, req, (TResource)context.Resource); + await HandleRequirementAsync(context, req, (TResource)context.Resource).ConfigureAwait(false); } } } diff --git a/src/Security/Authorization/Core/src/AuthorizationPolicy.cs b/src/Security/Authorization/Core/src/AuthorizationPolicy.cs index afb62f810d16..30959fe85c38 100644 --- a/src/Security/Authorization/Core/src/AuthorizationPolicy.cs +++ b/src/Security/Authorization/Core/src/AuthorizationPolicy.cs @@ -140,7 +140,7 @@ public static AuthorizationPolicy Combine(IEnumerable polic var useDefaultPolicy = true; if (!string.IsNullOrWhiteSpace(authorizeDatum.Policy)) { - var policy = await policyProvider.GetPolicyAsync(authorizeDatum.Policy); + var policy = await policyProvider.GetPolicyAsync(authorizeDatum.Policy).ConfigureAwait(false); if (policy == null) { throw new InvalidOperationException(Resources.FormatException_AuthorizationPolicyNotFound(authorizeDatum.Policy)); @@ -171,7 +171,7 @@ public static AuthorizationPolicy Combine(IEnumerable polic if (useDefaultPolicy) { - policyBuilder.Combine(await policyProvider.GetDefaultPolicyAsync()); + policyBuilder.Combine(await policyProvider.GetDefaultPolicyAsync().ConfigureAwait(false)); } } } @@ -179,7 +179,7 @@ public static AuthorizationPolicy Combine(IEnumerable polic // If we have no policy by now, use the fallback policy if we have one if (policyBuilder == null) { - var fallbackPolicy = await policyProvider.GetFallbackPolicyAsync(); + var fallbackPolicy = await policyProvider.GetFallbackPolicyAsync().ConfigureAwait(false); if (fallbackPolicy != null) { return fallbackPolicy; diff --git a/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs b/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs index 4129cb72638e..7278dc2d887a 100644 --- a/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs +++ b/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs @@ -84,10 +84,10 @@ public virtual async Task AuthorizeAsync(ClaimsPrincipal us } var authContext = _contextFactory.CreateContext(requirements, user, resource); - var handlers = await _handlers.GetHandlersAsync(authContext); + var handlers = await _handlers.GetHandlersAsync(authContext).ConfigureAwait(false); foreach (var handler in handlers) { - await handler.HandleAsync(authContext); + await handler.HandleAsync(authContext).ConfigureAwait(false); if (!_options.InvokeHandlersAfterFailure && authContext.HasFailed) { break; @@ -123,11 +123,11 @@ public virtual async Task AuthorizeAsync(ClaimsPrincipal us throw new ArgumentNullException(nameof(policyName)); } - var policy = await _policyProvider.GetPolicyAsync(policyName); + var policy = await _policyProvider.GetPolicyAsync(policyName).ConfigureAwait(false); if (policy == null) { throw new InvalidOperationException($"No policy found: {policyName}."); } - return await this.AuthorizeAsync(user, resource, policy); + return await this.AuthorizeAsync(user, resource, policy).ConfigureAwait(false); } } diff --git a/src/Security/Authorization/Core/src/PassThroughAuthorizationHandler.cs b/src/Security/Authorization/Core/src/PassThroughAuthorizationHandler.cs index 4ee0a7705ef5..bce2452f6778 100644 --- a/src/Security/Authorization/Core/src/PassThroughAuthorizationHandler.cs +++ b/src/Security/Authorization/Core/src/PassThroughAuthorizationHandler.cs @@ -20,7 +20,7 @@ public async Task HandleAsync(AuthorizationHandlerContext context) { foreach (var handler in context.Requirements.OfType()) { - await handler.HandleAsync(context); + await handler.HandleAsync(context).ConfigureAwait(false); } } } diff --git a/src/Shared/TaskExtensions.cs b/src/Shared/TaskExtensions.cs index 05eb900e5b94..0e8610d7a80f 100644 --- a/src/Shared/TaskExtensions.cs +++ b/src/Shared/TaskExtensions.cs @@ -80,12 +80,12 @@ public static async Task TimeoutAfter(this Task task, TimeSpan timeout, // or the debugger is attached if (task.IsCompleted || Debugger.IsAttached) { - return await task; + return await task.ConfigureAwait(false); } #if NET6_0_OR_GREATER try { - return await task.WaitAsync(timeout); + return await task.WaitAsync(timeout).ConfigureAwait(false); } catch (TimeoutException ex) when (ex.Source == typeof(TaskExtensions).Namespace) { @@ -93,10 +93,10 @@ public static async Task TimeoutAfter(this Task task, TimeSpan timeout, } #else var cts = new CancellationTokenSource(); - if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token))) + if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)).ConfigureAwait(false)) { cts.Cancel(); - return await task; + return await task.ConfigureAwait(false); } else { @@ -114,13 +114,13 @@ public static async Task TimeoutAfter(this Task task, TimeSpan timeout, // or the debugger is attached if (task.IsCompleted || Debugger.IsAttached) { - await task; + await task.ConfigureAwait(false); return; } #if NET6_0_OR_GREATER try { - await task.WaitAsync(timeout); + await task.WaitAsync(timeout).ConfigureAwait(false); } catch (TimeoutException ex) when (ex.Source == typeof(TaskExtensions).Namespace) { @@ -128,10 +128,10 @@ public static async Task TimeoutAfter(this Task task, TimeSpan timeout, } #else var cts = new CancellationTokenSource(); - if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token))) + if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)).ConfigureAwait(false)) { cts.Cancel(); - await task; + await task.ConfigureAwait(false); } else { diff --git a/src/SignalR/clients/csharp/Client/test/.editorconfig b/src/SignalR/clients/csharp/Client/test/.editorconfig deleted file mode 100644 index 10b085cdfa24..000000000000 --- a/src/SignalR/clients/csharp/Client/test/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{cs,vb}] - -# CA2007: Consider calling ConfigureAwait on the awaited task -dotnet_diagnostic.CA2007.severity = silent \ No newline at end of file diff --git a/src/SignalR/common/.editorconfig b/src/SignalR/common/.editorconfig deleted file mode 100644 index 2e160823941e..000000000000 --- a/src/SignalR/common/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{cs,vb}] - -# CA2007: Consider calling ConfigureAwait on the awaited task -dotnet_diagnostic.CA2007.severity = warning \ No newline at end of file diff --git a/src/SignalR/common/Http.Connections/.editorconfig b/src/SignalR/common/Http.Connections/.editorconfig deleted file mode 100644 index 10b085cdfa24..000000000000 --- a/src/SignalR/common/Http.Connections/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{cs,vb}] - -# CA2007: Consider calling ConfigureAwait on the awaited task -dotnet_diagnostic.CA2007.severity = silent \ No newline at end of file diff --git a/src/SignalR/common/SignalR.Common/test/.editorconfig b/src/SignalR/common/SignalR.Common/test/.editorconfig deleted file mode 100644 index 10b085cdfa24..000000000000 --- a/src/SignalR/common/SignalR.Common/test/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{cs,vb}] - -# CA2007: Consider calling ConfigureAwait on the awaited task -dotnet_diagnostic.CA2007.severity = silent \ No newline at end of file diff --git a/src/SignalR/common/testassets/.editorconfig b/src/SignalR/common/testassets/.editorconfig deleted file mode 100644 index 10b085cdfa24..000000000000 --- a/src/SignalR/common/testassets/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{cs,vb}] - -# CA2007: Consider calling ConfigureAwait on the awaited task -dotnet_diagnostic.CA2007.severity = silent \ No newline at end of file diff --git a/src/Testing/src/ExceptionAssertions.cs b/src/Testing/src/ExceptionAssertions.cs index c8af16cf93b2..adf326deafe1 100644 --- a/src/Testing/src/ExceptionAssertions.cs +++ b/src/Testing/src/ExceptionAssertions.cs @@ -53,7 +53,7 @@ public static async Task ThrowsAsync(Func testCode // The 'testCode' Task might execute asynchronously in a different thread making it hard to enforce the thread culture. // The correct way to verify exception messages in such a scenario would be to run the task synchronously inside of a // culture enforced block. - var ex = await Assert.ThrowsAsync(testCode); + var ex = await Assert.ThrowsAsync(testCode).ConfigureAwait(false); VerifyExceptionMessage(ex, exceptionMessage); return ex; } @@ -117,7 +117,7 @@ private static async Task ThrowsArgumentAsyncInternal( string exceptionMessage) where TException : ArgumentException { - var ex = await Assert.ThrowsAsync(testCode); + var ex = await Assert.ThrowsAsync(testCode).ConfigureAwait(false); if (paramName != null) { Assert.Equal(paramName, ex.ParamName); diff --git a/src/Testing/src/HttpClientSlim.cs b/src/Testing/src/HttpClientSlim.cs index 470ecef0fb11..b8d089f1bb0d 100644 --- a/src/Testing/src/HttpClientSlim.cs +++ b/src/Testing/src/HttpClientSlim.cs @@ -41,7 +41,7 @@ public static async Task GetStringAsync(Uri requestUri, bool validateCer return await ReadResponse(stream).ConfigureAwait(false); } - }); + }).ConfigureAwait(false); } internal static string GetHost(Uri requestUri) @@ -73,7 +73,7 @@ public static async Task PostAsync(Uri requestUri, HttpContent content, { return await RetryRequest(async () => { - using (var stream = await GetStream(requestUri, validateCertificate)) + using (var stream = await GetStream(requestUri, validateCertificate).ConfigureAwait(false)) { using (var writer = new StreamWriter(stream, Encoding.ASCII, bufferSize: 1024, leaveOpen: true)) { @@ -88,7 +88,7 @@ public static async Task PostAsync(Uri requestUri, HttpContent content, return await ReadResponse(stream).ConfigureAwait(false); } - }); + }).ConfigureAwait(false); } private static async Task ReadResponse(Stream stream) @@ -149,7 +149,7 @@ private static HttpStatusCode GetStatus(string response) private static async Task GetStream(Uri requestUri, bool validateCertificate) { - var socket = await GetSocket(requestUri); + var socket = await GetSocket(requestUri).ConfigureAwait(false); var stream = new NetworkStream(socket, ownsSocket: true); if (requestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Testing/src/xunit/AspNetTestAssemblyRunner.cs b/src/Testing/src/xunit/AspNetTestAssemblyRunner.cs index 55db1a44b907..0d99ffcff58b 100644 --- a/src/Testing/src/xunit/AspNetTestAssemblyRunner.cs +++ b/src/Testing/src/xunit/AspNetTestAssemblyRunner.cs @@ -28,7 +28,7 @@ public AspNetTestAssemblyRunner( protected override async Task AfterTestAssemblyStartingAsync() { - await base.AfterTestAssemblyStartingAsync(); + await base.AfterTestAssemblyStartingAsync().ConfigureAwait(false); // Find all the AssemblyFixtureAttributes on the test assembly await Aggregator.RunAsync(async () => @@ -57,10 +57,10 @@ await Aggregator.RunAsync(async () => if (instance is IAsyncLifetime asyncInit) { - await asyncInit.InitializeAsync(); + await asyncInit.InitializeAsync().ConfigureAwait(false); } } - }); + }).ConfigureAwait(false); } protected override async Task BeforeTestAssemblyFinishedAsync() @@ -73,10 +73,10 @@ protected override async Task BeforeTestAssemblyFinishedAsync() foreach (var disposable in _assemblyFixtureMappings.Values.OfType()) { - await Aggregator.RunAsync(disposable.DisposeAsync); + await Aggregator.RunAsync(disposable.DisposeAsync).ConfigureAwait(false); } - await base.BeforeTestAssemblyFinishedAsync(); + await base.BeforeTestAssemblyFinishedAsync().ConfigureAwait(false); } protected override Task RunTestCollectionAsync( diff --git a/src/Testing/src/xunit/AspNetTestCollectionRunner.cs b/src/Testing/src/xunit/AspNetTestCollectionRunner.cs index 9f44db2c98c1..ee05c25d7dcb 100644 --- a/src/Testing/src/xunit/AspNetTestCollectionRunner.cs +++ b/src/Testing/src/xunit/AspNetTestCollectionRunner.cs @@ -32,7 +32,7 @@ public AspNetTestCollectionRunner( protected override async Task AfterTestCollectionStartingAsync() { - await base.AfterTestCollectionStartingAsync(); + await base.AfterTestCollectionStartingAsync().ConfigureAwait(false); // note: We pass the assembly fixtures into the runner as ICollectionFixture<> - this seems to work OK without any // drawbacks. It's reasonable that we could add IAssemblyFixture<> and related plumbing if it ever became required. diff --git a/src/Testing/src/xunit/AspNetTestFrameworkExecutor.cs b/src/Testing/src/xunit/AspNetTestFrameworkExecutor.cs index df06276984a3..bcfa515b5566 100644 --- a/src/Testing/src/xunit/AspNetTestFrameworkExecutor.cs +++ b/src/Testing/src/xunit/AspNetTestFrameworkExecutor.cs @@ -19,7 +19,7 @@ protected override async void RunTestCases(IEnumerable testCases { using (var assemblyRunner = new AspNetTestAssemblyRunner(TestAssembly, testCases, DiagnosticMessageSink, executionMessageSink, executionOptions)) { - await assemblyRunner.RunAsync(); + await assemblyRunner.RunAsync().ConfigureAwait(false); } } } diff --git a/src/Testing/src/xunit/AspNetTestInvoker.cs b/src/Testing/src/xunit/AspNetTestInvoker.cs index c7737d11e06b..4dbe5e607ea3 100644 --- a/src/Testing/src/xunit/AspNetTestInvoker.cs +++ b/src/Testing/src/xunit/AspNetTestInvoker.cs @@ -41,20 +41,20 @@ await Aggregator.RunAsync(async () => { foreach (var lifecycleHook in lifecycleHooks) { - await lifecycleHook.OnTestStartAsync(context, CancellationTokenSource.Token); + await lifecycleHook.OnTestStartAsync(context, CancellationTokenSource.Token).ConfigureAwait(false); } - }); + }).ConfigureAwait(false); - var time = await base.InvokeTestMethodAsync(testClassInstance); + var time = await base.InvokeTestMethodAsync(testClassInstance).ConfigureAwait(false); await Aggregator.RunAsync(async () => { var exception = Aggregator.HasExceptions ? Aggregator.ToException() : null; foreach (var lifecycleHook in lifecycleHooks) { - await lifecycleHook.OnTestEndAsync(context, exception, CancellationTokenSource.Token); + await lifecycleHook.OnTestEndAsync(context, exception, CancellationTokenSource.Token).ConfigureAwait(false); } - }); + }).ConfigureAwait(false); return time; } diff --git a/src/Testing/src/xunit/AspNetTestRunner.cs b/src/Testing/src/xunit/AspNetTestRunner.cs index 3b78900063b9..f0df056853e9 100644 --- a/src/Testing/src/xunit/AspNetTestRunner.cs +++ b/src/Testing/src/xunit/AspNetTestRunner.cs @@ -59,8 +59,8 @@ protected override async Task> InvokeTestAsync(ExceptionA var retryAttribute = GetRetryAttribute(TestMethod); var result = retryAttribute is null - ? await base.InvokeTestAsync(aggregator) - : await RunTestCaseWithRetryAsync(retryAttribute, aggregator); + ? await base.InvokeTestAsync(aggregator).ConfigureAwait(false) + : await RunTestCaseWithRetryAsync(retryAttribute, aggregator).ConfigureAwait(false); if (_ownsTestOutputHelper) { @@ -81,7 +81,7 @@ private async Task> RunTestCaseWithRetryAsync(RetryAttrib for (var attempt = 1; attempt <= numAttempts; attempt++) { - var result = await base.InvokeTestAsync(aggregator); + var result = await base.InvokeTestAsync(aggregator).ConfigureAwait(false); totalTimeTaken += result.Item1; messages.Add(result.Item2); @@ -94,7 +94,7 @@ private async Task> RunTestCaseWithRetryAsync(RetryAttrib // We can't use the ITestOutputHelper here because there's no active test messages.Add($"[{TestCase.DisplayName}] Attempt {attempt} of {retryAttribute.MaxRetries} failed due to {aggregator.ToException()}"); - await Task.Delay(5000); + await Task.Delay(5000).ConfigureAwait(false); aggregator.Clear(); } } @@ -107,7 +107,7 @@ protected override async Task InvokeTestMethodAsync(ExceptionAggregator var repeatAttribute = GetRepeatAttribute(TestMethod); if (repeatAttribute == null) { - return await InvokeTestMethodCoreAsync(aggregator); + return await InvokeTestMethodCoreAsync(aggregator).ConfigureAwait(false); } var repeatContext = new RepeatContext(repeatAttribute.RunCount); @@ -116,7 +116,7 @@ protected override async Task InvokeTestMethodAsync(ExceptionAggregator var timeTaken = 0.0M; for (repeatContext.CurrentIteration = 0; repeatContext.CurrentIteration < repeatContext.Limit; repeatContext.CurrentIteration++) { - timeTaken = await InvokeTestMethodCoreAsync(aggregator); + timeTaken = await InvokeTestMethodCoreAsync(aggregator).ConfigureAwait(false); if (aggregator.HasExceptions) { return timeTaken;