Fix Null Warnings (#874)

* Fixing null warnings

* Fix null warnings
Fix other compiler warnings
This commit is contained in:
Steve Smith
2023-03-20 11:52:14 -04:00
committed by GitHub
parent a2ebd3fe26
commit d2412a84a9
38 changed files with 400 additions and 285 deletions

View File

@@ -25,7 +25,7 @@ public class LoginModel : PageModel
}
[BindProperty]
public InputModel? Input { get; set; }
public required InputModel Input { get; set; }
public IList<AuthenticationScheme>? ExternalLogins { get; set; }
@@ -74,7 +74,8 @@ public class LoginModel : PageModel
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
//var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
var result = await _signInManager.PasswordSignInAsync(Input?.Email, Input?.Password, false, true);
var result = await _signInManager.PasswordSignInAsync(Input!.Email!, Input!.Password!,
false, true);
if (result.Succeeded)
{

View File

@@ -35,7 +35,7 @@ public class RegisterModel : PageModel
}
[BindProperty]
public InputModel? Input { get; set; }
public required InputModel Input { get; set; }
public string? ReturnUrl { get; set; }
@@ -69,7 +69,7 @@ public class RegisterModel : PageModel
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input?.Email, Email = Input?.Email };
var result = await _userManager.CreateAsync(user, Input?.Password);
var result = await _userManager.CreateAsync(user, Input?.Password!);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
@@ -82,7 +82,7 @@ public class RegisterModel : PageModel
protocol: Request.Scheme);
Guard.Against.Null(callbackUrl, nameof(callbackUrl));
await _emailSender.SendEmailAsync(Input?.Email, "Confirm your email",
await _emailSender.SendEmailAsync(Input!.Email!, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
await _signInManager.SignInAsync(user, isPersistent: false);

View File

@@ -4,8 +4,6 @@ using Microsoft.eShopWeb.Infrastructure.Data;
using Microsoft.eShopWeb.Infrastructure.Data.Queries;
using Microsoft.eShopWeb.Infrastructure.Logging;
using Microsoft.eShopWeb.Infrastructure.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.eShopWeb.Web.Configuration;
@@ -20,7 +18,10 @@ public static class ConfigureCoreServices
services.AddScoped<IBasketService, BasketService>();
services.AddScoped<IOrderService, OrderService>();
services.AddScoped<IBasketQueryService, BasketQueryService>();
services.AddSingleton<IUriComposer>(new UriComposer(configuration.Get<CatalogSettings>()));
var catalogSettings = configuration.Get<CatalogSettings>() ?? new CatalogSettings();
services.AddSingleton<IUriComposer>(new UriComposer(catalogSettings));
services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
services.AddTransient<IEmailSender, EmailSender>();

View File

@@ -122,6 +122,11 @@ public class ManageController : Controller
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
Guard.Against.Null(callbackUrl, nameof(callbackUrl));
var email = user.Email;
if (email == null)
{
throw new ApplicationException($"No email associated with user {user.UserName}'.");
}
await _emailSender.SendEmailConfirmationAsync(email, callbackUrl);
StatusMessage = "Verification email sent. Please check your email.";
@@ -162,7 +167,8 @@ public class ManageController : Controller
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
var changePasswordResult = await _userManager
.ChangePasswordAsync(user, model.OldPassword!, model.NewPassword!);
if (!changePasswordResult.Succeeded)
{
AddErrors(changePasswordResult);
@@ -211,7 +217,7 @@ public class ManageController : Controller
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword);
var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword!);
if (!addPasswordResult.Succeeded)
{
AddErrors(addPasswordResult);
@@ -293,6 +299,10 @@ public class ManageController : Controller
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
return View(model);
}
var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (!result.Succeeded)
@@ -407,7 +417,7 @@ public class ManageController : Controller
}
// Strip spaces and hypens
var verificationCode = model.Code?.Replace(" ", string.Empty).Replace("-", string.Empty);
string verificationCode = model.Code?.Replace(" ", string.Empty).Replace("-", string.Empty) ?? "";
var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
@@ -421,7 +431,7 @@ public class ManageController : Controller
await _userManager.SetTwoFactorEnabledAsync(user, true);
_logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10) ?? new List<string>();
TempData[RecoveryCodesKey] = recoveryCodes.ToArray();
return RedirectToAction(nameof(ShowRecoveryCodes));
@@ -465,7 +475,7 @@ public class ManageController : Controller
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
}
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10) ?? new List<string>();
_logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id);
var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes.ToArray() };
@@ -533,8 +543,8 @@ public class ManageController : Controller
unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
}
model.SharedKey = FormatKey(unformattedKey);
model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
model.SharedKey = FormatKey(unformattedKey!);
model.AuthenticatorUri = GenerateQrCodeUri(user.Email!, unformattedKey!);
}
}

View File

@@ -13,7 +13,7 @@ public class IndexModel : PageModel
_catalogViewModelService = catalogViewModelService;
}
public CatalogIndexViewModel CatalogModel { get; set; } = new CatalogIndexViewModel();
public required CatalogIndexViewModel CatalogModel { get; set; } = new CatalogIndexViewModel();
public async Task OnGet(CatalogIndexViewModel catalogModel, int? pageId)
{

View File

@@ -82,7 +82,7 @@ var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
// Blazor Admin Required Services for Prerendering
builder.Services.AddScoped<HttpClient>(s => new HttpClient
{
BaseAddress = new Uri(baseUrlConfig.WebBase)
BaseAddress = new Uri(baseUrlConfig!.WebBase)
});
// add blazor services
@@ -171,15 +171,13 @@ app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
endpoints.MapRazorPages();
endpoints.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
endpoints.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
//endpoints.MapBlazorHub("/admin");
endpoints.MapFallbackToFile("index.html");
});
app.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
app.MapRazorPages();
app.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
app.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
//endpoints.MapBlazorHub("/admin");
app.MapFallbackToFile("index.html");
app.Logger.LogInformation("LAUNCHING");
app.Run();

View File

@@ -21,30 +21,30 @@ public class CachedCatalogViewModelService : ICatalogViewModelService
public async Task<IEnumerable<SelectListItem>> GetBrands()
{
return await _cache.GetOrCreateAsync(CacheHelpers.GenerateBrandsCacheKey(), async entry =>
return (await _cache.GetOrCreateAsync(CacheHelpers.GenerateBrandsCacheKey(), async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetBrands();
});
})) ?? new List<SelectListItem>();
}
public async Task<CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int? brandId, int? typeId)
{
var cacheKey = CacheHelpers.GenerateCatalogItemCacheKey(pageIndex, Constants.ITEMS_PER_PAGE, brandId, typeId);
return await _cache.GetOrCreateAsync(cacheKey, async entry =>
return (await _cache.GetOrCreateAsync(cacheKey, async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetCatalogItems(pageIndex, itemsPage, brandId, typeId);
});
})) ?? new CatalogIndexViewModel();
}
public async Task<IEnumerable<SelectListItem>> GetTypes()
{
return await _cache.GetOrCreateAsync(CacheHelpers.GenerateTypesCacheKey(), async entry =>
return (await _cache.GetOrCreateAsync(CacheHelpers.GenerateTypesCacheKey(), async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetTypes();
});
})) ?? new List<SelectListItem>();
}
}

View File

@@ -1,13 +1,12 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Microsoft.eShopWeb.Web.ViewModels;
public class CatalogIndexViewModel
{
public List<CatalogItemViewModel>? CatalogItems { get; set; }
public List<SelectListItem>? Brands { get; set; }
public List<SelectListItem>? Types { get; set; }
public List<CatalogItemViewModel> CatalogItems { get; set; } = new List<CatalogItemViewModel>();
public List<SelectListItem>? Brands { get; set; } = new List<SelectListItem>();
public List<SelectListItem>? Types { get; set; } = new List<SelectListItem>();
public int? BrandFilterApplied { get; set; }
public int? TypesFilterApplied { get; set; }
public PaginationInfoViewModel? PaginationInfo { get; set; }

View File

@@ -1,7 +1,11 @@
namespace Microsoft.eShopWeb.Web.ViewModels.Manage;
using System.ComponentModel.DataAnnotations;
namespace Microsoft.eShopWeb.Web.ViewModels.Manage;
public class RemoveLoginViewModel
{
public string? LoginProvider { get; set; }
public string? ProviderKey { get; set; }
[Required]
public string LoginProvider { get; set; } = string.Empty;
[Required]
public string ProviderKey { get; set; } = string.Empty;
}

View File

@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate;
using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate;
namespace Microsoft.eShopWeb.Web.ViewModels;
@@ -13,5 +11,5 @@ public class OrderViewModel
public decimal Total { get; set; }
public string Status => DEFAULT_STATUS;
public Address? ShippingAddress { get; set; }
public List<OrderItemViewModel> OrderItems { get; set; } = new List<OrderItemViewModel>();
public List<OrderItemViewModel> OrderItems { get; set; } = new();
}

View File

@@ -16,10 +16,13 @@
</div>
<div class="row">
<div class="col-md-12">
@for (var row = 0; row < Model.RecoveryCodes.Length; row += 2)
@if (Model.RecoveryCodes != null)
{
<code>@Model.RecoveryCodes[row]</code><text>&nbsp;</text><code>@Model.RecoveryCodes[row + 1]</code><br />
@for (var row = 0; row < Model.RecoveryCodes.Length; row += 2)
{
<code>@Model.RecoveryCodes[row]</code><text>&nbsp;</text><code>@Model.RecoveryCodes[row + 1]</code><br />
}
}
</div>
</div>
© 2021 GitHub, Inc.
© 2023 GitHub, Inc.

View File

@@ -30,15 +30,15 @@
</article>
<article class="esh-orders-detail-items row">
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress.Street</section>
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress?.Street</section>
</article>
<article class="esh-orders-detail-items row">
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress.City</section>
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress?.City</section>
</article>
<article class="esh-orders-detail-items row">
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress.Country</section>
<section class="esh-orders-detail-item col-xs-12">@Model.ShippingAddress?.Country</section>
</article>
</section>

View File

@@ -1,4 +1,4 @@
@if (Context.User.Identity.IsAuthenticated)
@if (Context!.User!.Identity!.IsAuthenticated)
{
<section class="col-lg-4 col-md-5 col-xs-12">
<div class="esh-identity">