# Capstone Project - Tea Shop

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Project & References
Source: https://www.devtutorials.ai/learn/blazor/project-references/capstone-project

> Build Tea Shop, a complete food ordering app: project setup, layout and navigation, a Web API, ASP.NET Core Identity with registration, login and logout, secured pages and APIs, a menu, a shared cart service, checkout with validation, order history, roles and admin pages for food items and orders.

## Project Overview

In this lesson, you build **Tea Shop**: a real food ordering website. Customers order tea and snacks; the shop's admin manages the menu and the orders. It brings together everything from this course in one project.

### Real-World Example

Ravi opens the Tea Shop, adds two Masala Chai and a Samosa to his cart, logs in, types his address and places the order. In the kitchen, Meena (the admin) sees the new order, marks it **Preparing**, then **Delivered**. Ravi sees the new status in **My orders**. Meena also adds a new snack to the menu.

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-cap-journey">
  <title id="fig-cap-journey">Animation: a dot follows the user journey. Menu, then Cart, then Log in, then Checkout, then My orders. Below, the admin path: Manage orders and Manage food.</title>
  <defs><marker id="fig-cap-journey-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="30" width="105" height="50" rx="10" />
  <text className="t m" x="62" y="60" textAnchor="middle" style={{ fontSize: 12 }}>Menu</text>
  <rect className="blu" x="140" y="30" width="105" height="50" rx="10" />
  <text className="t m" x="192" y="60" textAnchor="middle" style={{ fontSize: 12 }}>Cart</text>
  <rect className="pur" x="270" y="30" width="105" height="50" rx="10" />
  <text className="t m" x="322" y="60" textAnchor="middle" style={{ fontSize: 12 }}>Log in</text>
  <rect className="blu" x="400" y="30" width="105" height="50" rx="10" />
  <text className="t m" x="452" y="60" textAnchor="middle" style={{ fontSize: 12 }}>Checkout</text>
  <rect className="grn" x="530" y="30" width="100" height="50" rx="10" />
  <text className="t m" x="580" y="60" textAnchor="middle" style={{ fontSize: 12 }}>My orders</text>
  <path className="line" d="M115 55 H136" markerEnd="url(#fig-cap-journey-a)" />
  <path className="line" d="M245 55 H266" markerEnd="url(#fig-cap-journey-a)" />
  <path className="line" d="M375 55 H396" markerEnd="url(#fig-cap-journey-a)" />
  <path className="line" d="M505 55 H526" markerEnd="url(#fig-cap-journey-a)" />
  <text className="t" x="320" y="18" textAnchor="middle" style={{ fontSize: 11 }}>Customer (Ravi)</text>
  <rect className="org" x="140" y="125" width="170" height="50" rx="10" />
  <text className="t m" x="225" y="155" textAnchor="middle" style={{ fontSize: 12 }}>Manage orders</text>
  <rect className="org" x="335" y="125" width="170" height="50" rx="10" />
  <text className="t m" x="420" y="155" textAnchor="middle" style={{ fontSize: 12 }}>Manage food</text>
  <text className="t" x="320" y="113" textAnchor="middle" style={{ fontSize: 11 }}>Admin (Meena)</text>
  <path className="line" d="M580 80 V150 H509" markerEnd="url(#fig-cap-journey-a)" />
  <text className="t" x="600" y="118" textAnchor="middle" style={{ fontSize: 10 }}>status</text>
  <circle r="7" cy="55" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="62;192;322;452;580;580" keyTimes="0;0.2;0.4;0.6;0.8;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The customer journey on top, the admin’s pages below.</figcaption>
</figure>

What the finished app can do:

- Show the **menu** with a category filter, and add items to a **cart**.
- **Register**, **log in** and **log out** with ASP.NET Core Identity.
- **Place orders** with a validated form, and see the **order history**.
- Let **admins** add, edit and delete food items, and change order statuses.
- Offer a **Web API** (`api/foods`, `api/orders`) protected by roles.

| Part of the app | Lesson where you learned it |
|---|---|
| Project, Razor, components, parameters, `EventCallback` | Getting Started to Components |
| Layouts, `NavLink`, routing, `@page` | Layouts, Built-in Components |
| `EditForm`, `InputText`, validation attributes | Forms & Events, Form Validation |
| Interactive Server, static pages for login | Server Rendering, WebAssembly & Auto |
| `confirm()` and `localStorage` from C# | JavaScript Interop |
| `@inject`, scoped services, `FoodService` | Dependency Injection, Services |
| EF Core, `DbContext`, SQLite | Database Handling |
| Controllers, routes, status codes | API Integration |
| Middleware, Identity, roles, antiforgery | Application Security chapter |

## Project Setup

The project starts from the Blazor Web App template, with two NuGet packages for the database and Identity:

The finished project has these folders:

| Folder or file | What it contains |
|---|---|
| `Models/` | `FoodItem`, `Order`, `OrderItem`, `CheckoutForm` |
| `Data/` | `AppDbContext` (EF Core + Identity tables), `ApplicationUser`, `SeedData` |
| `Services/` | `FoodService`, `OrderService`, `CartService` |
| `Controllers/` | The Web API: `FoodsController`, `OrdersController` |
| `Components/Layout/` | `MainLayout`, `NavMenu` |
| `Components/Pages/` | Menu (`Home`), cart, checkout, my orders, not found |
| `Components/Account/` | Register and log in (static pages) |
| `Components/Admin/` | Manage food, manage orders (Admin role only) |
| `Components/Shared/` | `FoodCard`, `RedirectToLogin` |
| `Program.cs` | Services and the middleware pipeline |
| `TeaShop.http` | Sample API requests |

The **models** are plain classes. Validation attributes on them protect both the forms and the API:

- `OrderItem` **copies** the food name and price. If the admin changes a price later, old orders still show what the customer paid.

`AppDbContext` holds the tables. Because it inherits **`IdentityDbContext`**, the Identity tables (users, roles) live in the same database:

`Program.cs` registers everything (see **Dependency Injection**) and builds the pipeline (see **Middleware Pipeline**):

      {
          options.DefaultScheme = IdentityConstants.ApplicationScheme;
          options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
      })
      .AddIdentityCookies();
builder.Services.ConfigureApplicationCookie(options =>
{
      options.LoginPath = "/account/login";
      options.AccessDeniedPath = "/access-denied";
});
builder.Services.AddIdentityCore<ApplicationUser>(options =>
      {
          options.Password.RequiredLength = 8;
          options.Lockout.MaxFailedAccessAttempts = 5;
      })
      .AddRoles<IdentityRole>()
      .AddEntityFrameworkStores<AppDbContext>()
      .AddSignInManager();
builder.Services.AddAuthorization();

// 4. The app's own services
builder.Services.AddScoped<FoodService>();
builder.Services.AddScoped<OrderService>();
builder.Services.AddScoped<CartService>();   // one cart per user connection

var app = builder.Build();

// Create the database, the roles, two users and the menu on first run
await SeedData.InitializeAsync(app.Services);

// 5. The middleware pipeline
if (!app.Environment.IsDevelopment())
{
      app.UseExceptionHandler("/Error", createScopeForErrors: true);
      app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();
app.UseAntiforgery();

app.MapStaticAssets();
app.MapControllers();
app.MapRazorComponents<App>()
      .AddInteractiveServerRenderMode();

// Logout: a form post, checked by the antiforgery token
app.MapPost("/account/logout", async (
      SignInManager<ApplicationUser> signInManager,
      [FromForm] string? returnUrl) =>
{
      await signInManager.SignOutAsync();
      return Results.LocalRedirect("/");
});

app.Run();
`}
/>

- `AddDbContextFactory` gives each service a fresh `DbContext` per operation, which is safe in Blazor Server (see **Database Handling**).
- `SeedData.InitializeAsync` creates `teashop.db` with `EnsureCreatedAsync()`, the two roles, two demo users and the menu. For a growing app, switch to **migrations** (`dotnet ef migrations add ...`).

The code boxes on this page run small versions of each part in your browser, with in-memory stand-ins (`MemoryFoodService`, `MemoryOrderService`) instead of the database. The complete project, with SQLite and Identity, is in the download at the end.

## Layout and Navigation

- **`MainLayout`** puts the header with the **`NavMenu`** on every page, and `@Body` in the middle (see **Layouts**).
- **`App.razor`** chooses the render mode per page: account pages stay **static** (they set the login cookie), all others are **Interactive Server**.

<html lang="en">

<head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <base href="/" />
      <link rel="stylesheet" href="@Assets["app.css"]" />
</head>

<body>
      <script src="@Assets["_framework/blazor.web.js"]"></script>
</body>

</html>

@code {
      [CascadingParameter]
      private HttpContext HttpContext { get; set; } = default!;

      // Account pages stay static, because they set the login cookie.
      // Every other page is interactive (Interactive Server).
      private IComponentRenderMode? PageRenderMode =>
          HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
}
`}
/>

      <NavLink href="" Match="NavLinkMatch.All">Menu</NavLink>
      <NavLink href="cart">Cart <span class="badge">@Cart.Count</span></NavLink>

              <NavLink href="orders">My orders</NavLink>

                  <NavLink href="admin/foods">Manage food</NavLink>
                  <NavLink href="admin/orders">Manage orders</NavLink>

              <span class="user">@context.User.Identity?.Name</span>
              <form action="account/logout" method="post" class="inline">
                  <button type="submit" class="link">Log out</button>
              </form>
              <NavLink href="account/login">Log in</NavLink>
              <NavLink href="account/register">Register</NavLink>
</nav>

@code {
      // Render again whenever the cart changes, so the badge stays correct
      protected override void OnInitialized() => Cart.OnChange += Refresh;

      private void Refresh() => InvokeAsync(StateHasChanged);

      public void Dispose() => Cart.OnChange -= Refresh;
}
`}
/>

- `NavLink` adds the `active` class to the link of the current page.
- The links change with the user: `AuthorizeView` shows **My orders** to logged-in users and the admin links only to the **Admin** role. The inner view gets `Context="adminContext"` because both views would otherwise name their parameter `context`.
- The cart badge updates by itself: `NavMenu` listens to `CartService.OnChange` (see **Cart** below).

In the below example, the menu page uses the real `FoodCard` component: a `[Parameter]` for the food and an **`EventCallback`** that tells the parent "add this". Use the filter and the buttons.

@if (menu is null)
{
      <p>Loading the menu...</p>
}
else
{
      @foreach (var name in Categories)
      {
          <button style="@(name == category ? "font-weight:bold" : "")" @onclick="() => category = name">@name</button>
      }

      @if (message is not null)
      {
          <p>@message</p>
      }

      @foreach (var food in Shown)
      {
      }
}

@code {
      // In the project: @inject FoodService Foods and @inject CartService Cart
      private MemoryFoodService Foods = AppServices.Container.GetRequiredService<MemoryFoodService>();
      private CartService Cart = AppServices.Container.GetRequiredService<CartService>();

      private List<FoodItem>? menu;
      private string category = "All";
      private string? message;

      private IEnumerable<string> Categories =>
          new[] { "All" }.Concat(menu!.Select(f => f.Category).Distinct());

      private IEnumerable<FoodItem> Shown =>
          category == "All" ? menu! : menu!.Where(f => f.Category == category);

      protected override async Task OnInitializedAsync()
      {
          menu = await Foods.GetMenuAsync();
      }

      private void AddToCart(FoodItem food)
      {
          Cart.Add(food);
          message = $"{food.Name} was added to your cart.";
      }
}
`,
    "Components/Pages/FoodCard.razor": `@using BlazorApp.Models

<div class="card" style="border:1px solid #ddd; border-radius:10px; padding:10px; margin:6px 0">
      <span class="tag">@Food.Category</span>
      <h3>@Food.Name</h3>
      <p class="desc">@Food.Description</p>
      <div class="row">
          <span class="price">Rs @Food.Price</span>
          <button class="btn" @onclick="() => OnAdd.InvokeAsync(Food)">Add to cart</button>
      </div>
</div>

@code {
      [Parameter, EditorRequired]
      public FoodItem Food { get; set; } = default!;

      // The parent decides what "add" means (see Home.razor)
      [Parameter]
      public EventCallback<FoodItem> OnAdd { get; set; }
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>

## Building the API

The same services also power a **Web API**, so other apps (a phone app, a WebAssembly client) can use the shop too (see **API Integration**).

| Method and route | Who | What it does |
|---|---|---|
| `GET api/foods` | Everyone | The menu |
| `GET api/foods/3` | Everyone | One item, or 404 |
| `POST`, `PUT`, `DELETE api/foods` | Admin | Change the menu |
| `GET api/orders` | Logged in | My orders |
| `POST api/orders` | Logged in | Place an order |
| `GET api/orders/all` | Admin | Every order |
| `PUT api/orders/5/status` | Admin | Change an order's status |

          await foods.GetAsync(id) is { } item ? item : NotFound();

      // POST api/foods
      [HttpPost]
      [Authorize(Roles = SeedData.AdminRole)]
      public async Task<ActionResult<FoodItem>> Create(FoodItem item)
      {
          var created = await foods.AddAsync(item);
          return CreatedAtAction(nameof(GetOne), new { id = created.Id }, created);
      }

      // PUT api/foods/3
      [HttpPut("{id:int}")]
      [Authorize(Roles = SeedData.AdminRole)]
      public async Task<IActionResult> Update(int id, FoodItem item)
      {
          if (id != item.Id) return BadRequest();
          return await foods.UpdateAsync(item) ? NoContent() : NotFound();
      }

      // DELETE api/foods/3
      [HttpDelete("{id:int}")]
      [Authorize(Roles = SeedData.AdminRole)]
      public async Task<IActionResult> Delete(int id) =>
          await foods.DeleteAsync(id) ? NoContent() : NotFound();
}
`}
/>

- The controller gets `FoodService` through its **primary constructor** (see **Dependency Injection**). It does no database work itself.
- `[ApiController]` checks the `[Required]` and `[Range]` attributes of `FoodItem` and answers **400** with the errors.
- `Program.cs` maps the controllers with `app.MapControllers()`.

- Each method asks the factory for a new `DbContext` and disposes it with `using`.

Test the API with the `TeaShop.http` file in Visual Studio or VS Code while the app runs:

## Authentication Setup

The shop uses **ASP.NET Core Identity** with the **cookie** scheme (see **Authentication**). These lines in `Program.cs` set it up:

| Line | Its job |
|---|---|
| `AddCascadingAuthenticationState()` | Every component can get the user as `Task<AuthenticationState>` |
| `AddAuthentication(...).AddIdentityCookies()` | The cookie schemes Identity uses |
| `ConfigureApplicationCookie(...)` | Where to send users who must log in (`/account/login`) or who are not allowed (`/access-denied`) |
| `AddIdentityCore<ApplicationUser>(...)` | Users, password rules and lockout after 5 wrong tries |
| `.AddRoles<IdentityRole>()` | Role support: `Admin` and `Customer` |
| `.AddEntityFrameworkStores<AppDbContext>()` | Save users and roles with EF Core |
| `.AddSignInManager()` | Log in and out (writes and deletes the cookie) |

`ApplicationUser` adds one field to Identity's user, and `SeedData` creates the roles and the demo accounts:

- `UserManager.CreateAsync(user, password)` **hashes** the password (see **Password Storage**). Only the hash is saved.
- `AddToRoleAsync` gives the user a role claim. It travels in the login cookie.

## User Registration

- **`Register.razor`** is a **static** page: the `_Imports.razor` in `Components/Account` adds `[ExcludeFromInteractiveRouting]` to every account page. A cookie can only be written on an HTTP response (see **Authentication**).
- `[SupplyParameterFromForm]` fills `Input` from the posted form, and `FormName="register"` names the form (see **Forms & Events**).
- `[Compare]` checks that both passwords match.

<h1>Create an account</h1>

@foreach (var problem in problems)
{
      <p class="error">@problem</p>
}

      <label>Full name <InputText @bind-Value="Input.FullName" /></label>
      <ValidationMessage For="() => Input.FullName" />

      <label>Email <InputText @bind-Value="Input.Email" autocomplete="username" /></label>
      <ValidationMessage For="() => Input.Email" />

      <label>Password <InputText type="password" @bind-Value="Input.Password" autocomplete="new-password" /></label>
      <ValidationMessage For="() => Input.Password" />

      <label>Confirm password <InputText type="password" @bind-Value="Input.ConfirmPassword" autocomplete="new-password" /></label>
      <ValidationMessage For="() => Input.ConfirmPassword" />

      <button type="submit" class="btn">Register</button>

<p>Already have an account? <a href="account/login">Log in</a></p>

@code {
      [SupplyParameterFromForm]
      private RegisterInput Input { get; set; } = default!;

      private List<string> problems = new();

      protected override void OnInitialized() => Input ??= new();

      private async Task RegisterAsync()
      {
          var user = new ApplicationUser
          {
              UserName = Input.Email,
              Email = Input.Email,
              FullName = Input.FullName,
          };

          // Hashes the password and saves the user in the database
          var result = await UserManager.CreateAsync(user, Input.Password);
          if (!result.Succeeded)
          {
              problems = result.Errors.Select(e => e.Description).ToList();
              return;
          }

          // Every new account is a customer. Admins are added by the seed data.
          await UserManager.AddToRoleAsync(user, SeedData.CustomerRole);

          // Log the new user in (writes the login cookie)
          await SignInManager.SignInAsync(user, isPersistent: false);
          Navigation.NavigateTo("/");
      }

      private sealed class RegisterInput
      {
          [Required, StringLength(50)]
          public string FullName { get; set; } = "";

          [Required, EmailAddress]
          public string Email { get; set; } = "";

          [Required, StringLength(100, MinimumLength = 8, ErrorMessage = "Use at least 8 characters.")]
          public string Password { get; set; } = "";

          [Compare(nameof(Password), ErrorMessage = "The passwords do not match.")]
          public string ConfirmPassword { get; set; } = "";
      }
}
`}
/>

- Identity's password rules (8+ characters, a digit, an uppercase letter, a symbol) come back as `result.Errors` and are shown at the top.
- New users always get the **Customer** role. Nobody can make themselves an admin.

## User Login and Logout

`Login.razor` is static too. It checks the password with **`PasswordSignInAsync`**, which also counts wrong tries (**lockout**):

<h1>Log in</h1>

@if (errorMessage is not null)
{
      <p class="error">@errorMessage</p>
}

      <label>Email <InputText @bind-Value="Input.Email" autocomplete="username" /></label>
      <ValidationMessage For="() => Input.Email" />

      <label>Password <InputText type="password" @bind-Value="Input.Password" autocomplete="current-password" /></label>
      <ValidationMessage For="() => Input.Password" />

      <label class="check"><InputCheckbox @bind-Value="Input.RememberMe" /> Remember me</label>

      <button type="submit" class="btn">Log in</button>

<p>No account yet? <a href="account/register">Register</a></p>
<p class="hint">Demo accounts: admin@teashop.com / Admin123! and ravi@teashop.com / Ravi1234!</p>

@code {
      [SupplyParameterFromForm]
      private LoginInput Input { get; set; } = default!;

      [SupplyParameterFromQuery]
      private string? ReturnUrl { get; set; }

      private string? errorMessage;

      protected override void OnInitialized() => Input ??= new();

      private async Task LogInAsync()
      {
          // Checks the password hash. If it matches, writes the login cookie.
          var result = await SignInManager.PasswordSignInAsync(
              Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);

          if (result.Succeeded)
          {
              Navigation.NavigateTo(SafeReturnUrl());
              return;
          }

          errorMessage = result.IsLockedOut
              ? "Too many wrong tries. Please wait a few minutes."
              : "Wrong email or password.";
      }

      // Only go back to pages of this site (never to another site's address)
      private string SafeReturnUrl()
      {
          if (string.IsNullOrEmpty(ReturnUrl)) return "/";
          if (ReturnUrl.StartsWith(Navigation.BaseUri, StringComparison.OrdinalIgnoreCase)) return ReturnUrl;
          if (ReturnUrl.StartsWith('/') && !ReturnUrl.StartsWith("//")) return ReturnUrl;
          return "/";
      }

      // LoginInput: Email, Password ([Required]) and RememberMe
}
`}
/>

- `ReturnUrl` brings the user back to the page they wanted, for example `/checkout`.
- `SafeReturnUrl` only accepts addresses on this site. Otherwise an attacker could send users a login link that ends on a fake site (an **open redirect**).
- **Logout** is a form in `NavMenu` that posts to `account/logout` with an `<AntiforgeryToken />`. The endpoint in `Program.cs` calls `SignInManager.SignOutAsync()`, which deletes the cookie.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-cap-auth">
  <title id="fig-cap-auth">Three rows. Register: the form posts to Register.razor, UserManager.CreateAsync saves the user with a password hash, and SignInAsync writes the cookie. Log in: Login.razor, PasswordSignInAsync checks the hash and writes the cookie. Log out: the NavMenu form posts to account/logout, and SignOutAsync deletes the cookie.</title>
  <defs><marker id="fig-cap-auth-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="15" width="120" height="44" rx="10" />
  <text className="t m" x="70" y="42" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Register</text>
  <rect className="pur" x="160" y="15" width="300" height="44" rx="10" />
  <text className="t m" x="310" y="42" textAnchor="middle" style={{ fontSize: 11 }}>CreateAsync + AddToRoleAsync + SignInAsync</text>
  <rect className="grn" x="490" y="15" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="42" textAnchor="middle" style={{ fontSize: 11 }}>cookie written</text>
  <rect className="blu" x="10" y="80" width="120" height="44" rx="10" />
  <text className="t m" x="70" y="107" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Log in</text>
  <rect className="pur" x="160" y="80" width="300" height="44" rx="10" />
  <text className="t m" x="310" y="107" textAnchor="middle" style={{ fontSize: 11 }}>PasswordSignInAsync (checks the hash)</text>
  <rect className="grn" x="490" y="80" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="107" textAnchor="middle" style={{ fontSize: 11 }}>cookie written</text>
  <rect className="blu" x="10" y="145" width="120" height="44" rx="10" />
  <text className="t m" x="70" y="172" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Log out</text>
  <rect className="pur" x="160" y="145" width="300" height="44" rx="10" />
  <text className="t m" x="310" y="172" textAnchor="middle" style={{ fontSize: 11 }}>POST account/logout + token → SignOutAsync</text>
  <rect className="org" x="490" y="145" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="172" textAnchor="middle" style={{ fontSize: 11 }}>cookie deleted</text>
  <path className="line" d="M130 37 H156" markerEnd="url(#fig-cap-auth-a)" />
  <path className="line" d="M460 37 H486" markerEnd="url(#fig-cap-auth-a)" />
  <path className="line" d="M130 102 H156" markerEnd="url(#fig-cap-auth-a)" />
  <path className="line" d="M460 102 H486" markerEnd="url(#fig-cap-auth-a)" />
  <path className="line" d="M130 167 H156" markerEnd="url(#fig-cap-auth-a)" />
  <path className="line" d="M460 167 H486" markerEnd="url(#fig-cap-auth-a)" />
</svg>
<figcaption>Register, log in and log out, as the Tea Shop does them.</figcaption>
</figure>

## Securing Pages and APIs

The shop protects every private part twice: on the **page** and on the **API** (see **Authorization**).

| What | How it is protected |
|---|---|
| Checkout and My orders | `@attribute [Authorize]` |
| Every admin page | `[Authorize(Roles = SeedData.AdminRole)]` in `Components/Admin/_Imports.razor` |
| `OrdersController` | `[Authorize]` on the class, `[Authorize(Roles = ...)]` on admin actions |
| Changing the menu by API | `[Authorize(Roles = SeedData.AdminRole)]` on `POST`, `PUT`, `DELETE` |
| Forms | Antiforgery tokens (`UseAntiforgery`, `<EditForm>`, `<AntiforgeryToken />`) |
| Prices and quantities | Checked again in `OrderService` on the server |

`Routes.razor` uses **`AuthorizeRouteView`**. Logged-out users go to the login page; logged-in users without the right role see "Access denied":

                  @if (context.User.Identity?.IsAuthenticated == true)
                  {
                      <h1>Access denied</h1>
                      <p>Sorry, your account may not open this page.</p>
                  }
                  else
                  {
                  }
                  <p>Checking your login...</p>
`}
/>

Hiding the admin links in `NavMenu` is only for a tidy screen. The real protection is `[Authorize]` on the pages and on the API. Try it: log in as Ravi and type `/admin/foods` in the address bar.

## Home Page

The home page (`Components/Pages/Home.razor`) loads the menu in **`OnInitializedAsync`** (see **Component Lifecycle**), filters it by category and shows one `FoodCard` per item. You ran a small version of it in **Layout and Navigation**. In the project, the services come from **`@inject`**:

...

@code {
      private List<FoodItem>? menu;
      private string category = "All";
      private string? message;

      private IEnumerable<string> Categories =>
          new[] { "All" }.Concat(menu!.Select(f => f.Category).Distinct());

      private IEnumerable<FoodItem> Shown =>
          category == "All" ? menu! : menu!.Where(f => f.Category == category);

      protected override async Task OnInitializedAsync()
      {
          menu = await Foods.GetMenuAsync();
      }

      private async Task AddToCartAsync(FoodItem food)
      {
          await Cart.AddAsync(food);
          message = $"{food.Name} was added to your cart.";
      }
}
`}
/>

- With Interactive Server, the page is **prerendered** first, so `OnInitializedAsync` runs twice (see **Server Rendering**). For a short menu that is fine.
- `@key="food.Id"` keeps each card matched to its item when the filter changes the list.

## Cart (State Management)

- **State** is data the app remembers while the user works, like the items in the cart.
- Several components need the cart at once: the menu adds to it, the badge in `NavMenu` counts it, the cart page and checkout show it.
- So the cart lives in one **scoped service**, `CartService` (see **Services**). In Blazor Server, "scoped" means **one cart per user connection**, shared by all components of that user.
- When the cart changes, `CartService` raises an **event**, `OnChange`. Components that show the cart **subscribe** to it and render again. They **unsubscribe** in `Dispose`, so a closed page is not kept alive.
- The cart is also saved in the browser's **localStorage** with `ProtectedLocalStorage` (JS interop under the hood), so it survives a reload and the static login page.

<figure className="blz-fig">
<svg viewBox="0 0 640 230" role="img" aria-labelledby="fig-cap-cart">
  <title id="fig-cap-cart">Animation: CartService in the middle. Home adds an item; an OnChange signal goes out to NavMenu (badge), the Cart page and Checkout; a save arrow goes to localStorage in the browser.</title>
  <defs><marker id="fig-cap-cart-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="240" y="80" width="160" height="60" rx="12" />
  <text className="t m" x="320" y="106" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>CartService</text>
  <text className="t" x="320" y="124" textAnchor="middle" style={{ fontSize: 10 }}>scoped, one per user</text>
  <rect className="blu" x="10" y="85" width="140" height="50" rx="10" />
  <text className="t m" x="80" y="115" textAnchor="middle" style={{ fontSize: 12 }}>Home: Add</text>
  <rect className="grn" x="490" y="10" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="37" textAnchor="middle" style={{ fontSize: 11 }}>NavMenu badge</text>
  <rect className="grn" x="490" y="88" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="115" textAnchor="middle" style={{ fontSize: 11 }}>Cart page</text>
  <rect className="grn" x="490" y="166" width="140" height="44" rx="10" />
  <text className="t m" x="560" y="193" textAnchor="middle" style={{ fontSize: 11 }}>Checkout</text>
  <rect className="org" x="240" y="180" width="160" height="40" rx="10" />
  <text className="t m" x="320" y="205" textAnchor="middle" style={{ fontSize: 11 }}>localStorage</text>
  <path className="line" d="M150 110 H236" markerEnd="url(#fig-cap-cart-a)" />
  <path className="line" d="M400 100 L486 34" markerEnd="url(#fig-cap-cart-a)" />
  <path className="line" d="M400 110 H486" markerEnd="url(#fig-cap-cart-a)" />
  <path className="line" d="M400 120 L486 186" markerEnd="url(#fig-cap-cart-a)" />
  <path className="line" d="M320 140 V176" markerEnd="url(#fig-cap-cart-a)" />
  <text className="t" x="443" y="80" textAnchor="middle" style={{ fontSize: 10 }}>OnChange</text>
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="150;320;560" keyTimes="0;0.45;1" dur="3s" repeatCount="indefinite" />
    <animate attributeName="cy" values="110;110;34" keyTimes="0;0.45;1" dur="3s" repeatCount="indefinite" />
  </circle>
  <circle r="6" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="150;320;560" keyTimes="0;0.45;1" dur="3s" repeatCount="indefinite" />
    <animate attributeName="cy" values="110;110;188" keyTimes="0;0.45;1" dur="3s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>One shared cart. Every component that shows it hears OnChange.</figcaption>
</figure>

          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));

      private async Task SaveAsync()
      {
          await storage.SetAsync(Key, Items);
          OnChange?.Invoke();
      }
}
`}
/>

In the below example, `CartBadge` and `CartView` are two separate components. Neither knows the other, but both use the same `CartService` and listen to `OnChange`. Add items and change the quantities.

<button @onclick='() => Cart.Add(new FoodItem { Id = 1, Name = "Masala Chai", Price = 30 })'>Add Masala Chai</button>
<button @onclick='() => Cart.Add(new FoodItem { Id = 4, Name = "Samosa", Price = 15 })'>Add Samosa</button>

<hr />

@code {
      // In the project: @inject CartService Cart
      private CartService Cart = AppServices.Container.GetRequiredService<CartService>();
}
`,
    "Components/Pages/CartBadge.razor": `@implements IDisposable
@using Microsoft.Extensions.DependencyInjection
@using BlazorApp.Services

<p><b>Cart: @Cart.Count item(s)</b></p>

@code {
      private CartService Cart = AppServices.Container.GetRequiredService<CartService>();

      // Render again whenever the shared cart changes
      protected override void OnInitialized() => Cart.OnChange += Refresh;

      private void Refresh() => InvokeAsync(StateHasChanged);

      public void Dispose() => Cart.OnChange -= Refresh;
}
`,
    "Components/Pages/CartView.razor": `@implements IDisposable
@using Microsoft.Extensions.DependencyInjection
@using BlazorApp.Services

@if (Cart.Count == 0)
{
      <p>Your cart is empty.</p>
}
else
{
      <table>
          @foreach (var item in Cart.Items)
          {
              <tr>
                  <td>@item.Name</td>
                  <td>
                      <button @onclick="() => Cart.ChangeQuantity(item.FoodItemId, -1)">-</button>
                      @item.Quantity
                      <button @onclick="() => Cart.ChangeQuantity(item.FoodItemId, 1)">+</button>
                  </td>
                  <td>Rs @(item.Price * item.Quantity)</td>
              </tr>
          }
      </table>
      <p>Total: Rs @Cart.Total</p>
      <button @onclick="Cart.Clear">Empty the cart</button>
}

@code {
      private CartService Cart = AppServices.Container.GetRequiredService<CartService>();

      protected override void OnInitialized() => Cart.OnChange += Refresh;

      private void Refresh() => InvokeAsync(StateHasChanged);

      public void Dispose() => Cart.OnChange -= Refresh;
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>

## Placing Orders (Forms and Validation)

- **Checkout** is a form for the customer's name, phone and address, built with **`EditForm`** and the **`CheckoutForm`** model (see **Form Validation**).
- `DataAnnotationsValidator` checks the attributes in the browser and shows friendly messages.
- On submit, the page sends the form and the cart lines to **`OrderService.PlaceOrderAsync`**. The service checks the form **again**, and takes every **price from the database** (see **Server-Side Validation**). The cart only sends food ids and quantities.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-cap-order">
  <title id="fig-cap-order">Animation: the checkout form sends name, phone, address and the cart lines (food id and quantity only). OrderService checks the form again, reads the prices from the database, saves the order, and the user lands on My orders.</title>
  <defs><marker id="fig-cap-order-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="60" width="140" height="80" rx="12" />
  <text className="t m" x="80" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Checkout</text>
  <text className="t" x="80" y="110" textAnchor="middle" style={{ fontSize: 10 }}>form + ids, quantities</text>
  <rect className="pur" x="200" y="50" width="200" height="100" rx="12" />
  <text className="t m" x="300" y="76" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>OrderService</text>
  <text className="t" x="300" y="98" textAnchor="middle" style={{ fontSize: 10 }}>1. validate again</text>
  <text className="t" x="300" y="116" textAnchor="middle" style={{ fontSize: 10 }}>2. prices from the database</text>
  <text className="t" x="300" y="134" textAnchor="middle" style={{ fontSize: 10 }}>3. save the order</text>
  <rect className="org" x="450" y="20" width="180" height="50" rx="10" />
  <text className="t m" x="540" y="50" textAnchor="middle" style={{ fontSize: 11 }}>teashop.db</text>
  <rect className="grn" x="450" y="130" width="180" height="50" rx="10" />
  <text className="t m" x="540" y="160" textAnchor="middle" style={{ fontSize: 11 }}>My orders</text>
  <path className="line" d="M150 100 H196" markerEnd="url(#fig-cap-order-a)" />
  <path className="line" d="M400 80 L446 50" markerEnd="url(#fig-cap-order-a)" />
  <path className="line" d="M400 120 L446 150" markerEnd="url(#fig-cap-order-a)" />
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="80;300;540;540;540" keyTimes="0;0.35;0.55;0.6;1" dur="5s" repeatCount="indefinite" />
    <animate attributeName="cy" values="100;100;45;155;155" keyTimes="0;0.35;0.55;0.6;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Prices never come from the browser. The server sets them.</figcaption>
</figure>

In the below example, the cart already holds two Masala Chai and a Samosa. Click **Place order** with empty fields to see the validation, then fill them in.

      <p>Name <InputText @bind-Value="form.Name" /></p>
      <ValidationMessage For="() => form.Name" />

      <p>Phone <InputText @bind-Value="form.Phone" /></p>
      <ValidationMessage For="() => form.Phone" />

      <p>Address <InputTextArea @bind-Value="form.Address" /></p>
      <ValidationMessage For="() => form.Address" />

      <button type="submit">Place order</button>

<p>@result</p>

@code {
      // In the project: @inject CartService Cart and @inject OrderService Orders
      private CartService Cart = AppServices.Container.GetRequiredService<CartService>();
      private MemoryOrderService Orders = AppServices.Container.GetRequiredService<MemoryOrderService>();

      private CheckoutForm form = new();
      private string result = "";

      protected override void OnInitialized()
      {
          // A cart to check out (in the project, the customer filled it on the menu)
          Cart.Clear();
          Cart.Add(new FoodItem { Id = 1, Name = "Masala Chai", Price = 30 });
          Cart.Add(new FoodItem { Id = 1, Name = "Masala Chai", Price = 30 });
          Cart.Add(new FoodItem { Id = 4, Name = "Samosa", Price = 15 });
      }

      private async Task PlaceOrderAsync()
      {
          // In the project, the user id comes from the authentication state
          var (order, problem) = await Orders.PlaceOrderAsync("ravi", form, Cart.ToOrderLines());
          if (order is null)
          {
              result = problem!;
              return;
          }
          Cart.Clear();
          result = $"Thank you! Order #{order.Id} was placed. Total: Rs {order.Total}";
      }
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>

- A phone like `abc` fails the `[RegularExpression]` rule, so the form is not sent.
- The real page reads the user id from the cascading **`Task<AuthenticationState>`**: `user.FindFirstValue(ClaimTypes.NameIdentifier)`, then clears the cart and navigates to `orders?placed=4`.

## Order History

**My orders** (`Components/Pages/MyOrders.razor`) shows only the orders of the logged-in user. The query filters by the user id from the authentication state, never by an id from the address bar:

- `[SupplyParameterFromQuery]` reads `?placed=4` from the address and shows a thank-you message.
- `.Include(o => o.Items)` in `OrderService` loads the order lines together with the orders (see **Database Handling**).

In the below example, Ravi's orders are listed with their items and status.

@if (orders is null)
{
      <p>Loading your orders...</p>
}
else
{
      @foreach (var order in orders)
      {
          <div style="border:1px solid #ddd; border-radius:10px; padding:8px; margin:6px 0">
              <b>Order #@order.Id</b> <i>@order.Status</i>
              <ul>
                  @foreach (var item in order.Items)
                  {
                      <li>@item.Quantity x @item.FoodName (Rs @item.UnitPrice)</li>
                  }
              </ul>
              Total: Rs @order.Total
          </div>
      }
}

@code {
      private MemoryOrderService Orders = AppServices.Container.GetRequiredService<MemoryOrderService>();
      private List<Order>? orders;

      protected override async Task OnInitializedAsync()
      {
          // In the project: the id of the logged-in user
          orders = await Orders.GetOrdersForUserAsync("ravi");
      }
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>
## Role-Based Authorization

The shop has two roles (see **Authorization**):

| Role | May do |
|---|---|
| **Customer** | Order, see their own orders |
| **Admin** | Everything a customer may do, plus manage food items and all orders |

- `Components/Admin/_Imports.razor` puts `@attribute [Authorize(Roles = SeedData.AdminRole)]` on **every** page in that folder at once.
- `NavMenu` shows the admin links with `<AuthorizeView Roles="Admin">`.
- The API checks the same role with `[Authorize(Roles = SeedData.AdminRole)]`.

In the below example, the pretend provider from **Authentication** logs in Ravi (Customer) or Meena (Admin). The menu links and the pages follow the role. Try **Manage food** as each user.

<button @onclick='() => Provider.LogIn("Meena", "Admin")'>Log in as Meena (Admin)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

      @* Like NavMenu *@
      <p>
          <button @onclick="() => page = typeof(MyOrders)">My orders</button>
              <button @onclick="() => page = typeof(ManageFoods)">Manage food</button>
              <i>Logged in as @context.User.Identity?.Name</i>
      </p>

      @* Like Routes.razor *@
              @if (context.User.Identity?.IsAuthenticated == true)
              {
                  <p>Access denied: your account may not open this page.</p>
              }
              else
              {
                  <p>Please log in (the project redirects to the login page).</p>
              }

@code {
      private Type page = typeof(ManageFoods);
      private RouteData Route => new(page, new Dictionary<string, object?>());

      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Components/Pages/ManageFoods.razor": `@page "/admin/foods"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles = "Admin")]

<h4>Manage food items</h4>
<p>Only admins see this page.</p>
`,
    "Components/Pages/MyOrders.razor": `@page "/orders"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

<h4>My orders</h4>
<p>Every logged-in user sees this page.</p>
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In the project, Identity reads the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role)
      {
          var claims = new[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Role, role) };
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- Meena sees the **Manage food** button and the page. Ravi does not see the button, and if he still opens the page, he gets "Access denied".

## Admin Pages

### Managing Food Items

**Manage food** (`/admin/foods`) lists every item and lets the admin add, edit and delete them with one `EditForm`:

- **Add** creates an empty `FoodItem` with `Id = 0`. **Edit** works on a **copy**, so **Cancel** leaves the table unchanged.
- **Save** calls `AddAsync` when `Id` is 0, otherwise `UpdateAsync`.
- **Delete** first asks with the browser's own `confirm()` box, called through **JS interop**: `await JS.InvokeAsync<bool>("confirm", ...)`.
- Unticking **On the menu** hides an item from customers without deleting it.

In the below example, the same page runs with `MemoryFoodService`. The code box asks "Delete? Yes / No" on the page instead of the browser's `confirm()` box. Add a new item, edit a price, then delete something.

@if (editing is not null)
{
          <p>Name <InputText @bind-Value="editing.Name" /></p>
          <ValidationMessage For="() => editing.Name" />
          <p>
              Category
                  <option>Tea</option>
                  <option>Snacks</option>
          </p>
          <p>Price <InputNumber @bind-Value="editing.Price" /></p>
          <ValidationMessage For="() => editing.Price" />
          <p><InputCheckbox @bind-Value="editing.IsAvailable" /> On the menu</p>
          <button type="submit">Save</button>
          <button type="button" @onclick="() => editing = null">Cancel</button>
}

<table>
      @foreach (var food in foods)
      {
          <tr>
              <td>@food.Name</td>
              <td>Rs @food.Price</td>
              <td>@(food.IsAvailable ? "On menu" : "Hidden")</td>
              <td>
                  <button @onclick="() => Edit(food)">Edit</button>
                  @if (deleting == food.Id)
                  {
                      <span>Delete? <button @onclick="() => DeleteAsync(food)">Yes</button> <button @onclick="() => deleting = 0">No</button></span>
                  }
                  else
                  {
                      <button @onclick="() => deleting = food.Id">Delete</button>
                  }
              </td>
          </tr>
      }
</table>

@code {
      // In the project: @inject FoodService Foods
      private MemoryFoodService Foods = AppServices.Container.GetRequiredService<MemoryFoodService>();

      private List<FoodItem> foods = new();
      private FoodItem? editing;
      private int deleting;

      protected override async Task OnInitializedAsync() => foods = await Foods.GetAllAsync();

      private void StartNew() => editing = new FoodItem();

      // Edit a copy, so Cancel leaves the table unchanged
      private void Edit(FoodItem food) => editing = new FoodItem
      {
          Id = food.Id, Name = food.Name, Description = food.Description,
          Category = food.Category, Price = food.Price, IsAvailable = food.IsAvailable,
      };

      private async Task SaveAsync()
      {
          if (editing!.Id == 0) await Foods.AddAsync(editing);
          else await Foods.UpdateAsync(editing);
          editing = null;
          foods = await Foods.GetAllAsync();
      }

      private async Task DeleteAsync(FoodItem food)
      {
          await Foods.DeleteAsync(food.Id);
          deleting = 0;
          foods = await Foods.GetAllAsync();
      }
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>

### Managing Orders

**Manage orders** (`/admin/orders`) shows every customer's orders. The kitchen changes the status with a `<select>`: **Placed → Preparing → Ready → Delivered** (or **Cancelled**). The **Open** filter hides finished orders.

- `@onchange` gives the chosen value as text. `Enum.TryParse` turns it back into an `OrderStatus`.
- Ravi sees the new status the next time he opens **My orders**.

In the below example, change the status of an order. Delivered orders leave the **Open** list.

<button @onclick='() => filter = "All"'>All</button>

@if (orders is not null)
{
      <p>@filter orders: @Shown.Count()</p>
      <table>
          @foreach (var order in Shown)
          {
              <tr>
                  <td>#@order.Id</td>
                  <td>@order.CustomerName</td>
                  <td>@string.Join(", ", order.Items.Select(i => i.Quantity + " x " + i.FoodName))</td>
                  <td>
                      <select value="@order.Status" @onchange="e => SetStatusAsync(order, e.Value?.ToString())">
                          @foreach (var status in Enum.GetValues<OrderStatus>())
                          {
                              <option value="@status">@status</option>
                          }
                      </select>
                  </td>
              </tr>
          }
      </table>
}

@code {
      // In the project: @inject OrderService Orders
      private MemoryOrderService Orders = AppServices.Container.GetRequiredService<MemoryOrderService>();

      private List<Order>? orders;
      private string filter = "Open";

      // Open orders are the ones the kitchen still has to finish
      private IEnumerable<Order> Shown => filter == "All"
          ? orders!
          : orders!.Where(o => o.Status is OrderStatus.Placed or OrderStatus.Preparing or OrderStatus.Ready);

      protected override async Task OnInitializedAsync() => orders = await Orders.GetAllOrdersAsync();

      private async Task SetStatusAsync(Order order, string? value)
      {
          if (Enum.TryParse<OrderStatus>(value, out var status))
          {
              await Orders.UpdateStatusAsync(order.Id, status);
              order.Status = status;
          }
      }
}
`,
    "Models/Order.cs": `namespace BlazorApp.Models;

public enum OrderStatus { Placed, Preparing, Ready, Delivered, Cancelled }

public class Order
{
      public int Id { get; set; }
      public string UserId { get; set; } = "";          // who ordered (Identity user id)
      public string CustomerName { get; set; } = "";
      public string Phone { get; set; } = "";
      public string Address { get; set; } = "";
      public string Notes { get; set; } = "";
      public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
      public OrderStatus Status { get; set; } = OrderStatus.Placed;
      public int Total { get; set; }
      public List<OrderItem> Items { get; set; } = new();
}

public class OrderItem
{
      public int Id { get; set; }
      public int OrderId { get; set; }
      public int FoodItemId { get; set; }
      public string FoodName { get; set; } = "";   // copied, so old orders keep their names
      public int UnitPrice { get; set; }           // copied, so old orders keep their prices
      public int Quantity { get; set; }
}
`,
    "Models/FoodItem.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// One item on the menu. The same rules check the admin form and the API.
public class FoodItem
{
      public int Id { get; set; }

      [Required, StringLength(40)]
      public string Name { get; set; } = "";

      [StringLength(200)]
      public string Description { get; set; } = "";

      [Required]
      public string Category { get; set; } = "Tea";

      [Range(1, 1000, ErrorMessage = "Price must be between 1 and 1000.")]
      public int Price { get; set; }          // in rupees

      public bool IsAvailable { get; set; } = true;
}
`,
    "Models/CheckoutForm.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

// What the customer types on the checkout page
public class CheckoutForm
{
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(50)]
      public string Name { get; set; } = "";

      [Required(ErrorMessage = "Please enter your phone number.")]
      [RegularExpression(@"^[0-9 +]{8,15}$", ErrorMessage = "Use 8 to 15 digits.")]
      public string Phone { get; set; } = "";

      [Required(ErrorMessage = "Please enter your address.")]
      [StringLength(200, MinimumLength = 10, ErrorMessage = "The address needs 10 to 200 characters.")]
      public string Address { get; set; } = "";

      [StringLength(200)]
      public string Notes { get; set; } = "";
}

// One line of an order request: which item, how many. Never a price.
public record OrderLine(int FoodItemId, int Quantity);

// The body of POST /api/orders
public class PlaceOrderRequest
{
      [Required]
      public CheckoutForm Customer { get; set; } = new();

      [MinLength(1, ErrorMessage = "The order is empty.")]
      public List<OrderLine> Items { get; set; } = new();
}
`,
    "Services/MemoryFoodService.cs": `namespace BlazorApp.Services;

using BlazorApp.Models;

// Stands in for FoodService (EF Core + SQLite) so the code boxes can run.
// Same methods, but the menu lives in a list.
public class MemoryFoodService
{
      private readonly List<FoodItem> foods = new()
      {
          new() { Id = 1, Name = "Masala Chai", Category = "Tea", Price = 30, Description = "Black tea with milk, ginger and cardamom." },
          new() { Id = 2, Name = "Ginger Tea", Category = "Tea", Price = 25, Description = "Strong tea with fresh ginger." },
          new() { Id = 3, Name = "Lemon Tea", Category = "Tea", Price = 20, Description = "Light tea with lemon and honey." },
          new() { Id = 4, Name = "Samosa", Category = "Snacks", Price = 15, Description = "Crispy pastry with spiced potato." },
          new() { Id = 5, Name = "Veg Puff", Category = "Snacks", Price = 20, Description = "Flaky puff with vegetable filling." },
      };
      private int nextId = 6;

      public async Task<List<FoodItem>> GetMenuAsync()
      {
          await Task.Delay(300);   // like a database call
          return foods.Where(f => f.IsAvailable).OrderBy(f => f.Category).ThenBy(f => f.Name).ToList();
      }

      public async Task<List<FoodItem>> GetAllAsync()
      {
          await Task.Delay(100);
          return foods.OrderBy(f => f.Category).ThenBy(f => f.Name).Select(Copy).ToList();
      }

      public Task<FoodItem?> GetAsync(int id) => Task.FromResult(foods.FirstOrDefault(f => f.Id == id));

      public Task<FoodItem> AddAsync(FoodItem item)
      {
          item.Id = nextId++;
          foods.Add(Copy(item));
          return Task.FromResult(item);
      }

      public Task<bool> UpdateAsync(FoodItem item)
      {
          var index = foods.FindIndex(f => f.Id == item.Id);
          if (index < 0) return Task.FromResult(false);
          foods[index] = Copy(item);
          return Task.FromResult(true);
      }

      public Task<bool> DeleteAsync(int id) => Task.FromResult(foods.RemoveAll(f => f.Id == id) > 0);

      private static FoodItem Copy(FoodItem f) => new()
      {
          Id = f.Id, Name = f.Name, Description = f.Description,
          Category = f.Category, Price = f.Price, IsAvailable = f.IsAvailable,
      };
}
`,
    "Services/MemoryOrderService.cs": `namespace BlazorApp.Services;

using System.ComponentModel.DataAnnotations;
using BlazorApp.Models;

// Stands in for OrderService (EF Core + SQLite). Same checks, orders kept in a list.
public class MemoryOrderService(MemoryFoodService foods)
{
      private readonly List<Order> orders = new()
      {
          new() { Id = 1, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Delivered, Total = 75,
                  Items = { new() { FoodName = "Masala Chai", UnitPrice = 30, Quantity = 2 }, new() { FoodName = "Samosa", UnitPrice = 15, Quantity = 1 } } },
          new() { Id = 2, UserId = "meena", CustomerName = "Meena", Phone = "98400 22222", Address = "4 Lake View, Coimbatore",
                  Status = OrderStatus.Preparing, Total = 45,
                  Items = { new() { FoodName = "Ginger Tea", UnitPrice = 25, Quantity = 1 }, new() { FoodName = "Veg Puff", UnitPrice = 20, Quantity = 1 } } },
          new() { Id = 3, UserId = "ravi", CustomerName = "Ravi", Phone = "98400 11111", Address = "12 Gandhi Road, Chennai",
                  Status = OrderStatus.Placed, Total = 20,
                  Items = { new() { FoodName = "Lemon Tea", UnitPrice = 20, Quantity = 1 } } },
      };

      public async Task<(Order? Order, string? Error)> PlaceOrderAsync(
          string userId, CheckoutForm customer, IEnumerable<OrderLine> lines)
      {
          // The same server-side checks as the real OrderService
          var errors = new List<ValidationResult>();
          if (!Validator.TryValidateObject(customer, new ValidationContext(customer), errors, true))
          {
              return (null, string.Join(" ", errors.Select(e => e.ErrorMessage)));
          }
          var wanted = lines.Where(l => l.Quantity > 0).ToList();
          if (wanted.Count == 0) return (null, "The order is empty.");

          var order = new Order
          {
              Id = orders.Max(o => o.Id) + 1, UserId = userId, CustomerName = customer.Name,
              Phone = customer.Phone, Address = customer.Address, Notes = customer.Notes,
          };
          foreach (var line in wanted)
          {
              var food = await foods.GetAsync(line.FoodItemId);   // the price comes from the menu
              if (food is null) return (null, "An item is no longer available.");
              order.Items.Add(new OrderItem { FoodItemId = food.Id, FoodName = food.Name, UnitPrice = food.Price, Quantity = line.Quantity });
          }
          order.Total = order.Items.Sum(i => i.UnitPrice * i.Quantity);
          orders.Add(order);
          return (order, null);
      }

      public Task<List<Order>> GetOrdersForUserAsync(string userId) =>
          Task.FromResult(orders.Where(o => o.UserId == userId).OrderByDescending(o => o.Id).ToList());

      public Task<List<Order>> GetAllOrdersAsync() =>
          Task.FromResult(orders.OrderByDescending(o => o.Id).ToList());

      public Task<bool> UpdateStatusAsync(int orderId, OrderStatus status)
      {
          var order = orders.FirstOrDefault(o => o.Id == orderId);
          if (order is null) return Task.FromResult(false);
          order.Status = status;
          return Task.FromResult(true);
      }
}
`,
    "Services/CartService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public class CartItem
{
      public int FoodItemId { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }        // shown in the cart only; the server sets the real price
      public int Quantity { get; set; }
}

// The cart: app state shared by every component of one user.
// (In the project it is also saved in localStorage. The code boxes keep it in memory.)
public class CartService
{

      public List<CartItem> Items { get; private set; } = new();
      public int Count => Items.Sum(i => i.Quantity);
      public int Total => Items.Sum(i => i.Price * i.Quantity);

      // Components subscribe to this to render again when the cart changes
      public event Action? OnChange;

      public void Add(FoodItem food)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == food.Id);
          if (line is null)
          {
              Items.Add(new CartItem { FoodItemId = food.Id, Name = food.Name, Price = food.Price, Quantity = 1 });
          }
          else if (line.Quantity < 20)
          {
              line.Quantity++;
          }
          OnChange?.Invoke();
      }

      public void ChangeQuantity(int foodItemId, int change)
      {
          var line = Items.FirstOrDefault(i => i.FoodItemId == foodItemId);
          if (line is not null)
          {
              line.Quantity = Math.Clamp(line.Quantity + change, 0, 20);
              if (line.Quantity == 0) Items.Remove(line);
          }
          OnChange?.Invoke();
      }

      public void Clear()
      {
          Items.Clear();
          OnChange?.Invoke();
      }

      public IEnumerable<OrderLine> ToOrderLines() =>
          Items.Select(i => new OrderLine(i.FoodItemId, i.Quantity));
}
`,
    "Services/AppServices.cs": `namespace BlazorApp.Services;

using Microsoft.Extensions.DependencyInjection;

// Stands in for Program.cs: the code boxes cannot have their own.
// In the project: builder.Services.AddScoped<FoodService>(); and so on.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<MemoryFoodService>();
          services.AddSingleton<MemoryOrderService>();
          services.AddSingleton<CartService>();
          return services.BuildServiceProvider();
      }
}
`,
  }}
/>

Ideas to extend the project on your own: an image for each food item, a "Reorder" button in My orders, email confirmation with Identity's email sender, a sales dashboard for the admin, or migrations instead of `EnsureCreatedAsync`.

## Download Project Files

### Download Tea Shop Project Source Code

<a href="/downloads/blazor-tea-shop.zip" download>Download blazor-tea-shop.zip</a>

The ZIP file contains the complete Tea Shop project: Blazor pages, the Web API, EF Core with SQLite, and ASP.NET Core Identity with roles.

| Folder | What it contains |
|---|---|
| `Components/` | Layout, navigation, pages, account pages, admin pages |
| `Controllers/` | `FoodsController`, `OrdersController` |
| `Services/` | `FoodService`, `OrderService`, `CartService` |
| `Data/` | `AppDbContext`, `ApplicationUser`, `SeedData` |
| `Models/` | `FoodItem`, `Order`, `OrderItem`, `CheckoutForm` |
| `TeaShop.http` | Sample API requests |

### Project Setup Instructions

You need the **.NET 10 SDK**.

1. Unzip the file and open a terminal in the `TeaShop` folder.
2. Trust the development certificate (once per computer):

   `dotnet dev-certs https --trust`

3. Start the app. The first run downloads the NuGet packages and creates `teashop.db`:

   `dotnet run --launch-profile https`

4. Open `https://localhost:7150` and log in:

   | Email | Password | Role |
   |---|---|---|
   | admin@teashop.com | Admin123! | Admin: menu, orders, manage food and orders |
   | ravi@teashop.com | Ravi1234! | Customer: menu, cart, checkout, my orders |

To start again with a fresh database, stop the app and delete `teashop.db`.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| A component member named like its page (`Cart` in `Cart.razor`) | Any name works | Name pages `CartPage.razor`, `MyOrders.razor` | CS0542: member names cannot be the same as their enclosing type |
| Interactive login or register pages | Every page can set a cookie | Keep account pages static (`[ExcludeFromInteractiveRouting]`) | The login cookie is never written |
| Not unsubscribing from `CartService.OnChange` | Events clean up by themselves | Unsubscribe in `Dispose` | Old components stay in memory and still render |
| Taking prices from the cart | The browser sends the right price | Read prices from the database in `OrderService` | Tampered requests buy food for free |
| Only hiding admin links | Hidden means protected | `[Authorize(Roles = ...)]` on pages and API actions | Customers open admin pages by typing the address |
| Returning to any `returnUrl` after login | A return address is always safe | Only accept addresses on your own site | Open redirect to an attacker's site |

</div>

## Check Yourself

## Exercises

## What to Remember

- A real Blazor app combines everything: **components** with parameters, a **layout** with navigation, **forms** with validation, **services** with DI, **EF Core**, a **Web API** and **security**.
- Keep database work in **services**. Pages and API controllers both use them.
- Share app-wide state (the cart) in a **scoped service** with an **OnChange** event. Unsubscribe in `Dispose`.
- **Identity** gives you users, roles and safe passwords. Keep account pages **static**, so they can write the cookie.
- Protect every private page **and** API with `[Authorize]`; use **roles** for admin areas. Hidden links are not protection.
- **Validate on the server** and take prices from the database.

Next: **Cheat Sheet**
