Skip to content

Commit

Permalink
Updated dependencies to use nullable context
Browse files Browse the repository at this point in the history
  • Loading branch information
EdCharbeneau committed Sep 15, 2023
1 parent f9b6aa8 commit c240c05
Show file tree
Hide file tree
Showing 20 changed files with 133 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

<PropertyGroup>
<TargetFramework>$(TargetFrameworkVersion)</TargetFramework>
<ImplicitUsings>true</ImplicitUsings>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

@code {
string elementId = $"map-{Guid.NewGuid().ToString("D")}";

[Parameter] public double Zoom { get; set; }
[Parameter] public List<Marker> Markers { get; set; }
[Parameter, EditorRequired] public List<Marker> Markers { get; set; } = new();

protected async override Task OnAfterRenderAsync(bool firstRender)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

public class Marker
{
public string Description { get; set; }
public string Description { get; set; } = string.Empty;

public double X { get; set; }

public double Y { get; set; }

public bool ShowPopup { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ public class Point
public double X { get; set; }

public double Y { get; set; }
}
}
// Compare this snippet from save-points\01-Components-and-layout\BlazingPizza.ComponentsLibrary\Map\Marker.cs:
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
{
<img src="~/img/user.svg" />
<div>
<a class="username" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">@User.Identity.Name</a>
<a class="username" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">@User?.Identity?.Name</a>
<form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="/" method="post">
<button type="submit" class="btn btn-link sign-out">Sign out</button>
</form>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>$(TargetFrameworkVersion)</TargetFramework>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ public async Task<ActionResult<int>> PlaceOrder(Order order)
// new specials and toppings
foreach (var pizza in order.Pizzas)
{
pizza.SpecialId = pizza.Special.Id;
pizza.SpecialId = pizza.Special?.Id ?? 0;
pizza.Special = null;

foreach (var topping in pizza.Toppings)
{
topping.ToppingId = topping.Topping.Id;
topping.ToppingId = topping.Topping?.Id ?? 0;
topping.Topping = null;
}
}
Expand All @@ -75,7 +75,7 @@ public async Task<ActionResult<int>> PlaceOrder(Order order)
await _db.SaveChangesAsync();

// In the background, send push notifications if possible
var subscription = await _db.NotificationSubscriptions.Where(e => e.UserId == GetUserId()).SingleOrDefaultAsync();
var subscription = await _db.NotificationSubscriptions.Where(e => e.UserId == PizzaApiExtensions.GetUserId(HttpContext)).SingleOrDefaultAsync();
if (subscription != null)
{
_ = TrackAndSendNotificationsAsync(order, subscription);
Expand All @@ -84,11 +84,6 @@ public async Task<ActionResult<int>> PlaceOrder(Order order)
return order.OrderId;
}

private string GetUserId()
{
return HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}

private static async Task TrackAndSendNotificationsAsync(Order order, NotificationSubscription subscription)
{
// In a realistic case, some other backend process would track
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@ public static WebApplication MapPizzaApi(this WebApplication app)

}

private static string GetUserId(HttpContext context)
public static string GetUserId(HttpContext context)
{
return context.User.FindFirstValue(ClaimTypes.NameIdentifier);
string? result = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (result is null) throw new UnauthorizedAccessException("User claim was not found.");
return result;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
// Inline the Lat-Long pairs in Order rather than having a FK to another table
modelBuilder.Entity<Order>().OwnsOne(o => o.DeliveryLocation);
}
}
}
69 changes: 69 additions & 0 deletions save-points/03-show-order-status/BlazingPizza.Server/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace BlazingPizza.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();

services.AddDbContext<PizzaStoreContext>(options =>
options.UseSqlite("Data Source=pizza.db"));

services.AddDefaultIdentity<PizzaStoreUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<PizzaStoreContext>();

services.AddIdentityServer()
.AddApiAuthorization<PizzaStoreUser, PizzaStoreContext>();

services.AddAuthentication()
.AddIdentityServerJwt();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapRazorPages();
endpoints.MapFallbackToFile("index.html");
});
}
}
}
16 changes: 7 additions & 9 deletions save-points/03-show-order-status/BlazingPizza.Shared/Address.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
using System.ComponentModel.DataAnnotations;

namespace BlazingPizza;
namespace BlazingPizza;

public class Address
{
public int Id { get; set; }

public string Name { get; set; }
public string Name { get; set; } = string.Empty;

public string Line1 { get; set; }
public string Line1 { get; set; } = string.Empty;

public string Line2 { get; set; }
public string Line2 { get; set; } = string.Empty;

public string City { get; set; }
public string City { get; set; } = string.Empty;

public string Region { get; set; }
public string Region { get; set; } = string.Empty;

public string PostalCode { get; set; }
public string PostalCode { get; set; } = string.Empty;
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(TargetFrameworkVersion)</TargetFramework>
<RootNamespace>BlazingPizza</RootNamespace>
<PropertyGroup>
<TargetFramework>$(TargetFrameworkVersion)</TargetFramework>
<RootNamespace>BlazingPizza</RootNamespace>
<ImplicitUsings>true</ImplicitUsings>
</PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BlazingPizza.ComponentsLibrary\BlazingPizza.ComponentsLibrary.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="System.ComponentModel.DataAnnotations" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BlazingPizza.ComponentsLibrary\BlazingPizza.ComponentsLibrary.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

public class NotificationSubscription
{
public int NotificationSubscriptionId { get; set; }
public required int NotificationSubscriptionId { get; set; }

public string UserId { get; set; }
public required string UserId { get; set; }

public string Url { get; set; }
public required string Url { get; set; }

public string P256dh { get; set; }
public required string P256dh { get; set; }

public string Auth { get; set; }
public required string Auth { get; set; }
}
6 changes: 4 additions & 2 deletions save-points/03-show-order-status/BlazingPizza.Shared/Order.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ public class Order
{
public int OrderId { get; set; }

public string UserId { get; set; }
// Set by the server during POST
public string? UserId { get; set; }

public DateTime CreatedTime { get; set; }

public Address DeliveryAddress { get; set; } = new Address();

public LatLong DeliveryLocation { get; set; }
// Set by server during POST
public LatLong? DeliveryLocation { get; set; }

public List<Pizza> Pizzas { get; set; } = new List<Pizza>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,19 @@ public class OrderWithStatus
public readonly static TimeSpan PreparationDuration = TimeSpan.FromSeconds(10);
public readonly static TimeSpan DeliveryDuration = TimeSpan.FromMinutes(1); // Unrealistic, but more interesting to watch

public Order Order { get; set; }
// Set from DB
public Order Order { get; set; } = null!;

public string StatusText { get; set; }
// Set from Order
public string StatusText { get; set; } = null!;

public bool IsDelivered => StatusText == "Delivered";

public List<Marker> MapMarkers { get; set; }
public List<Marker> MapMarkers { get; set; } = null!;

public static OrderWithStatus FromOrder(Order order)
{
ArgumentNullException.ThrowIfNull(order.DeliveryLocation);
// To simulate a real backend process, we fake status updates based on the amount
// of time since the order was placed
string statusText;
Expand Down Expand Up @@ -65,6 +68,7 @@ public static OrderWithStatus FromOrder(Order order)

private static LatLong ComputeStartPosition(Order order)
{
ArgumentNullException.ThrowIfNull(order.DeliveryLocation);
// Random but deterministic based on order ID
var rng = new Random(order.OrderId);
var distance = 0.01 + rng.NextDouble() * 0.02;
Expand Down
8 changes: 5 additions & 3 deletions save-points/03-show-order-status/BlazingPizza.Shared/Pizza.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,24 @@ public class Pizza

public int OrderId { get; set; }

public PizzaSpecial Special { get; set; }
public PizzaSpecial? Special { get; set; }

public int SpecialId { get; set; }

public int Size { get; set; }

public List<PizzaTopping> Toppings { get; set; }
public List<PizzaTopping> Toppings { get; set; } = new();

public decimal GetBasePrice()
{
if(Special == null) throw new NullReferenceException($"{nameof(Special)} was null when calculating Base Price.");
return ((decimal)Size / (decimal)DefaultSize) * Special.BasePrice;
}

public decimal GetTotalPrice()
{
return GetBasePrice() + Toppings.Sum(t => t.Topping.Price);
if (Toppings.Any(t => t.Topping is null)) throw new NullReferenceException($"{nameof(Toppings)} contained null when calculating the Total Price.");
return GetBasePrice() + Toppings.Sum(t => t.Topping!.Price);
}

public string GetFormattedTotalPrice()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ public class PizzaSpecial
{
public int Id { get; set; }

public string Name { get; set; }
public string Name { get; set; } = string.Empty;

public decimal BasePrice { get; set; }

public string Description { get; set; }
public string Description { get; set; } = string.Empty;

public string ImageUrl { get; set; }
public string ImageUrl { get; set; } = "img/pizzas/cheese.jpg";

public string GetFormattedBasePrice() => BasePrice.ToString("0.00");
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class PizzaTopping
{
public Topping Topping { get; set; }
public Topping? Topping { get; set; }

public int ToppingId { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class Topping
{
public int Id { get; set; }

public string Name { get; set; }
public string Name { get; set; } = string.Empty;

public decimal Price { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ public class UserInfo
{
public bool IsAuthenticated { get; set; }

public string Name { get; set; }
public string Name { get; set; } = string.Empty;

}

0 comments on commit c240c05

Please sign in to comment.