diff --git a/.claude/roadmap.md b/.claude/roadmap.md deleted file mode 100644 index 169d2ef..0000000 --- a/.claude/roadmap.md +++ /dev/null @@ -1,133 +0,0 @@ -# Grid — Repo Roadmap (for LLM context) - -Repo: github.com/csontosati/Grid — Game Launcher (Steam-like), ICS course project. -Status: MVP graded and complete. Currently **mid-migration away from .NET MAUI to Avalonia UI** -(MAUI has no Linux desktop target; team wants Linux support). Read this whole file before -touching anything — a lot changed recently and previous LLM sessions' assumptions may be stale. - -## Current architecture (as of last session) -``` -GameLib.App → .NET MAUI frontend, MVVM (CommunityToolkit.Mvvm) — BEING REPLACED, see below -GameLib.BL → Business logic: Facades + DTOs (Models), mapped from entities — stays as-is -GameLib.DAL → EF Core (Code First) + SQLite, Repository/UnitOfWork pattern — stays as-is -``` -Each layer has an `*Installer.cs` (`AppInstaller` / `BLInstaller` / `DALInstaller`) registering -its services into DI, wired up in `MauiProgram.cs`. xUnit tests cover DAL + BL only (App has no -tests, not worth adding given the pending rewrite). - -`main` now contains the **full app** (this was NOT true a few sessions ago — an earlier merge -attempt silently missed `solution/GameLib.App`; it was manually re-checked-out and fixed). -There is no longer a need to check other branches for "the real code" — `main` is current. - -## Domain model -Entities (DAL/Entities): User, Library, Game, Studio, Category, Timer. -Relations: User 1–N Library; Library N–N Game; Game N–N Category; Game 1–N Timer; Studio 1–N Game. -Enums: GameCategory, Pegi (age rating). - -## File map - -### GameLib.DAL — data access (UNCHANGED by the Avalonia migration) -- Entities/*.cs, Enums/*.cs — schema -- GameLibDbContext.cs — DbSets + relations (OnModelCreating) -- Factories/ — DbContextSqLiteFactory (runtime), DesignTimeDbContextFactory (EF CLI design-time; - DAL can act as its own `--startup-project` for `dotnet ef` commands, no need to involve App) -- Repositories/ (generic Repository+IRepository, EntityNotFoundException), UnitOfWork/ (UoW pattern) -- Mappers/*EntityMapper.cs — entity <-> other repr. -- Migrations/ — InitialMigration + snapshot -- Migrator/DbMigrator.cs + IDbMigrator.cs — applies migrations on startup -- Seeds/ — DbSeeder.cs (+IDbSeeder) and per-entity seed data — seeds dev DB with starter data -- DALInstaller.cs — registers DbContext factory, repos, UoW, migrator, seeder in DI -- **Known issue, fixed**: NU1903 vulnerabilities were present — `System.Security.Cryptography.Xml` - pinned to `10.0.11` (NOT 10.0.5 — that version is *also* on the vulnerable list, easy mistake to - repeat); `SQLitePCLRaw.lib.e_sqlite3` has no patched 2.1.x release yet, suppressed via - `NuGetAuditSuppress` in the csproj pointing at the upstream EF Core issue tracking it. Revisit - periodically — check if EF Core has bumped the transitive reference. - -### GameLib.BL — business logic (UNCHANGED by the Avalonia migration) -- Models/*.cs — DTOs (GameDetail/List, LibraryDetail/List, UserDetail/List, TimerModel, ModelBase) -- Mappers/*ModelMapper.cs — Entity -> DTO mapping -- Facades/ — GameFacade, LibraryFacade, UserFacade (+BaseFacade, IFacade, IGameFacade) — CRUD/query - API for the App layer, DB-level filter/sort. **Bug found+fixed**: `GameFacade.ApplyOrder`'s - switch was missing `age_desc` (fell through to unordered `_ => query`) — added, plus `name_desc` - for symmetry. Worth double-checking other facades for the same missing-case pattern. -- BLInstaller.cs, BussinesLogic.cs — DI registration for BL layer - -### GameLib.App — MAUI frontend, TO BE REPLACED (do not invest further here) -- MauiProgram.cs, AppInstaller.cs, Extensions/ServiceCollectionExtension.cs — app bootstrap & DI -- App.xaml(.cs), AppShell.xaml(.cs) — app root & Shell navigation -- ViewModels/ — AppShellViewModel, GameListViewModel, GameDetailViewModel, GameAddViewModel, - LibraryListViewModel, UserListViewModel, UserAddViewModel, UserSettingsViewModel (+ViewModelBase) - — **these survive the migration essentially unchanged**, pure MVVM Toolkit C#, no MAUI dependency -- Views/ — DiscoverView, GameAddView, GameDetailView, GameEditView, LibraryView, - LibraryGameDetailView, SignUpView, UserSelectionView, UserSettingsView (+ContentPageBase) - — full rewrite required (`.xaml` → Avalonia `.axaml`, `ContentPage` → `UserControl`/`Window`) -- Messages/ — MVVM Toolkit weak-messages (GameAdded/Deleted/Updated/Selected, - UserAdded/Deleted/Updated/Selected, LibrarySelected, LibraryGameDeleted, NewUserLibrary) - — **survive unchanged**, plain C#, no MAUI dependency -- Services/ — NavigationService, AlertService, MessengerService (+interfaces) — interfaces survive, - implementations need rewriting (NavigationService is wired to MAUI Shell, which has no Avalonia - equivalent — biggest single piece of migration work, see below) -- Converters/GameCategoryToStringConverter.cs; Models/RouteModel.cs — near-identical port -- Resources/ — Styles (Colors.xaml, Styles.xaml → Avalonia Styles/ControlTheme), Fonts, AppIcon, - Splash (drop, no mobile targets in Avalonia desktop), Texts (.resx localization — reusable as-is) -- Platforms/ — Android/iOS/MacCatalyst/Windows — **delete entirely**, Avalonia doesn't use MAUI's - per-platform head folders - -### Tests (xUnit) -- GameLib.Tests — DAL: CategoryTests, GameTests, LibraryTests, StudioTests, TimerTests, UserTests, DbContextTestsBase -- GameLib.BL.Tests — GameFacadeTests, LibraryFacadeTests, UserFacadeTests, FacadeTestsBase -- GameLib.Common.Tests — DeepAssert.cs + Seeds/ (shared test fixture data) - -### Root / infra -- solution/solution.slnx — solution file -- .github/workflows/ci.yml — GitHub Actions CI, builds+tests DAL+BL only (App excluded, needs - platform workloads unsuited to CI). **Branch protection is on for `main`** — no direct pushes, - PR + passing CI required. -- .azure/azure-pipelines.yml — legacy Azure Pipelines config, may be dead weight; unconfirmed - whether Azure DevOps is still actively wired to this repo -- .claude/roadmap.md — **this file** -- README.md — rewritten in English, describes MVP status, has a `## Usage` TODO section pending - -## Branches -`main` is current and complete — no need to check other branches for "the real code" anymore. -Already deleted (fully merged, redundant): DALTesting, GameDetail, New_Game, Views, init, -init_project_structure, review1, review2, add-ci-workflow. -Still present, unreviewed, believed superseded/abandoned (verify via GitHub compare view before -deleting): Discover, Library, LibraryViewModelImplementation, viewModels-initial, patch, -azure-pipelines. `3.submission` also likely still present — was the source of the App merge into -main, now redundant, safe to delete once `main` is confirmed solid. - -## Active migration: MAUI → Avalonia UI -Decision made: rebuild `GameLib.App` in Avalonia (not Blazor/Uno/Photino) specifically to -minimize rewrite effort, since it's XAML+MVVM like MAUI. Full comparison written up separately -(not yet committed to repo — ask if it needs to be re-created). - -**Plan**: pilot the port on one small view first (`UserSettingsView` or `SignUpView`) to nail the -Shell-replacement navigation pattern (Avalonia has no Shell equivalent — hand-roll via -`ViewLocator` + `ContentControl` swap, or a community nav package) and the DI bootstrap -(`Program.cs`/`App.axaml.cs` replacing `MauiProgram.cs`, reusing `DALInstaller`/`BLInstaller` -as-is). Once that pattern works, port remaining views mechanically against the same template. - -**Not yet started**: no `GameLib.Avalonia` (or similarly named) project exists yet in the repo. - -## Local dev environment notes -- Windows dev via VS Code (not Visual Studio, disliked) + WSL for git/bash work; .NET SDK - separately needed inside WSL if using it there (`sudo snap install dotnet --classic`) -- IDE decision made: **JetBrains Rider**, free for non-commercial use, for both team members - (confirm this is still current policy if it's been a while) -- To run DB migrations, always specify project explicitly to avoid EF CLI getting confused by - `GameLib.App`'s multi-targeting: - `dotnet ef database update --project solution\GameLib.DAL\GameLib.DAL.csproj --startup-project solution\GameLib.DAL\GameLib.DAL.csproj` -- If `NETSDK1064`/package-not-found errors appear after changing package versions, it's usually a - stale `obj/`/`bin/` cache — `Get-ChildItem -Recurse -Directory -Include bin,obj | Remove-Item -Recurse -Force` - then `dotnet nuget locals all --clear` then `dotnet restore` - -## For future LLM sessions -1. Work off `main` — it's current and complete, don't hunt for another branch. -2. If continuing the Avalonia migration: check whether `GameLib.App` still exists (MAUI) or has - been replaced/renamed yet — don't assume this file is still accurate on that point. -3. Contract-defining files to read first: GameLibDbContext.cs (schema), Facades/*.cs (BL API - surface), Models/*.cs (DTO shape), ViewModels/ (UI structure/behavior — these survive - regardless of UI framework), *Installer.cs files (DI wiring/how layers connect). -4. Load this file instead of re-scanning the full tree — but verify a few key facts on arrival - (does `GameLib.App` still exist, what's on `main`) since this file can go stale between sessions. \ No newline at end of file diff --git a/.claude/skills/grid-architecture/SKILL.md b/.claude/skills/grid-architecture/SKILL.md new file mode 100644 index 0000000..c1be3c0 --- /dev/null +++ b/.claude/skills/grid-architecture/SKILL.md @@ -0,0 +1,114 @@ +--- +name: grid-architecture +description: Architectural standards, domain model, layer contracts (DAL, BL, App), and development guidelines for the Grid project. Use whenever designing or modifying entities, DbContext, repositories, unit of work, facades, DTOs/models, seeding, security package pins, or inspecting contract-defining files. +--- + +# Grid Architecture & Domain Guide + +Architectural reference, domain model conventions, and layer boundaries for the Grid game launcher project. + +## 1. High-Level Architecture + +The solution adheres to a strict 3-tier separation of concerns: + +``` +[Presentation Layer] GameLib.App (MAUI, being migrated to Avalonia) + │ + ▼ +[Business Logic] GameLib.BL (Facades + DTO Models) + │ + ▼ +[Data Access Layer] GameLib.DAL (EF Core SQLite + Repository / Unit of Work) +``` + +Each layer provides an installer class (`DALInstaller.cs`, `BLInstaller.cs`, `AppInstaller.cs`) that registers its internal services, factories, and facades into Microsoft Dependency Injection (`IServiceCollection`). + +--- + +## 2. Domain Model & Relations + +Entities are defined in `GameLib.DAL/Entities/`: + +| Entity | Description | Relationships | +|---|---|---| +| `User` | Application user profile | `1 : N` Library | +| `Library` | User's game library | `N : 1` User, `N : N` Game (via join) | +| `Game` | Game title entry | `N : N` Library, `N : N` Category, `1 : N` Timer, `N : 1` Studio | +| `Studio` | Development/publishing studio | `1 : N` Game | +| `Category` | Game genre/category | `N : N` Game | +| `Timer` | Playtime tracking record | `N : 1` Game | + +### Enums (`GameLib.DAL/Enums/`) +- `GameCategory`: Action, Adventure, RPG, Strategy, Indie, etc. +- `Pegi`: Age rating categories (Pegi3, Pegi7, Pegi12, Pegi16, Pegi18). + +--- + +## 3. Data Access Layer (`GameLib.DAL`) + +- **Database**: SQLite via Entity Framework Core (Code First). +- **DbContext**: + - `GameLibDbContext`: Core context declaring DbSets and fluent relationship configurations (`OnModelCreating`). + - `DbContextSqLiteFactory`: Runtime factory instantiated by DI. + - `DesignTimeDbContextFactory`: Design-time factory used by `dotnet ef` CLI tools. +- **Repository & Unit of Work**: + - Generic `Repository` implementing `IRepository`. + - Throws `EntityNotFoundException` when entities cannot be resolved. + - `UnitOfWork` orchestrates transaction lifecycles and commits across repositories. +- **Mappers (`GameLib.DAL/Mappers/`)**: + - `*EntityMapper.cs`: Map database entities to internal DAL representations. +- **Migrations & Seeding**: + - `DbMigrator.cs` (`IDbMigrator`): Applies pending migrations automatically at application startup. + - `DbSeeder.cs` (`IDbSeeder`): Seeds starter games, users, studios, and libraries from `GameLib.DAL/Seeds/`. + +### ⚠️ Security Pins & NuGet Quirks in DAL +- **`System.Security.Cryptography.Xml`**: Explicitly pinned to `10.0.11`. + - *Warning*: Do not downgrade to `10.0.5` — `10.0.5` is also flagged as vulnerable in NuGet security advisories. +- **`SQLitePCLRaw.lib.e_sqlite3`**: Currently suppressed via `` in `GameLib.DAL.csproj` due to an upstream EF Core issue without a patched 2.1.x release. + +--- + +## 4. Business Logic Layer (`GameLib.BL`) + +- **DTOs / Models (`GameLib.BL/Models/`)**: + - Distinct DTOs for list and detail views (e.g., `GameListModel` vs `GameDetailModel`, `UserListModel` vs `UserDetailModel`). + - Base class: `ModelBase`. +- **Model Mappers (`GameLib.BL/Mappers/`)**: + - Handle conversions between DAL entities and BL DTO models (`GameModelMapper`, `UserModelMapper`, etc.). +- **Facades (`GameLib.BL/Facades/`)**: + - Public interface consumed by the presentation layer (`GameFacade`, `LibraryFacade`, `UserFacade`). + - Encapsulate CRUD, queries, and sorting/filtering. + - **Sorting switch convention**: Double-check sorting logic pattern in facades. For example, `GameFacade.ApplyOrder` must support both ascending and descending cases (`name`, `name_desc`, `age`, `age_desc`) rather than falling through to default ordering. + +--- + +## 5. Presentation Layer (`GameLib.App`) + +- **ViewModels**: Built on `CommunityToolkit.Mvvm` (`ObservableObject`, `[ObservableProperty]`, `[RelayCommand]`). + - Inherit from `ViewModelBase`. + - ViewModels communicate via weak messages (`CommunityToolkit.Mvvm.Messaging`). + - **Decoupled from MAUI**: ViewModels and Messages are 100% portable to Avalonia. +- **Services**: + - `INavigationService`: Abstraction for view switching and parameter passing. + - `IAlertService`: Abstraction for displaying dialogs and confirmations. + - `IMessengerService`: Abstraction for pub/sub messaging. + +--- + +## 6. Contract-Defining Files to Consult First + +When exploring or modifying functionality, inspect these files first: +1. `solution/GameLib.DAL/GameLibDbContext.cs` — Schema definitions and relationships. +2. `solution/GameLib.BL/Facades/*.cs` — Business logic and query API surface. +3. `solution/GameLib.BL/Models/*.cs` — DTO shapes and data contracts. +4. `solution/GameLib.App/ViewModels/` — UI behavior and screen states. +5. `*Installer.cs` — Dependency injection registrations and wiring across layers. + +--- + +## 7. Git & Development Workflow + +- **Branch**: Work directly off `main`. `main` is complete and contains the full application. +- **Branch Protection**: GitHub Actions CI builds and runs tests for DAL and BL on pull requests. Direct pushes to `main` are restricted. +- **Local Tooling**: JetBrains Rider (recommended) or VS Code on native Windows PowerShell. + diff --git a/.claude/skills/grid-runner/SKILL.md b/.claude/skills/grid-runner/SKILL.md new file mode 100644 index 0000000..8951c91 --- /dev/null +++ b/.claude/skills/grid-runner/SKILL.md @@ -0,0 +1,135 @@ +--- +name: grid-runner +description: Build, run, test, and manage EF Core database migrations for the Grid game launcher project on Windows. Use whenever building the solution, running GameLib.App, executing migrations, running xUnit tests, or troubleshooting common build/runtime issues like exit code 9009 or cache corruption. +--- + +# Grid Runner & Local Dev Workflow + +Instructions and command sequences for developing, building, running, and testing the Grid game launcher on Windows. + +## 1. Prerequisites & Environment + +- **OS / Shell**: Native Windows PowerShell (run at the repository root `C:\Users\...\Grid`). + - **Do NOT run Windows build targets from WSL** — the Windows build target (`net10.0-windows10.0.19041.0`) requires native Windows tooling. +- **SDK**: .NET 10 SDK. +- **Workloads**: + ```powershell + dotnet workload install maui + ``` +- **EF Core CLI**: + ```powershell + dotnet tool install --global dotnet-ef + # If already installed or acting up: + dotnet tool update --global dotnet-ef + ``` + +--- + +## 2. Quick Reference (Full Sequence) + +```powershell +# Ensure working directory is repo root +git checkout main +git pull origin main + +# 1. Update database +dotnet ef database update --project solution\GameLib.DAL\GameLib.DAL.csproj --startup-project solution\GameLib.DAL\GameLib.DAL.csproj + +# 2. Build the app +cd solution\GameLib.App +dotnet build -f net10.0-windows10.0.19041.0 + +# 3. Launch the app executable directly +cd bin\Debug\net10.0-windows10.0.19041.0\win-x64 +.\GameLib.App.exe +``` + +--- + +## 3. Database Migrations (EF Core) + +> [!IMPORTANT] +> **Always run EF Core CLI from the repository root** pointing both `--project` and `--startup-project` at `solution\GameLib.DAL\GameLib.DAL.csproj`. +> +> **Never** run `dotnet ef` inside `GameLib.App` or target `GameLib.App` as the startup project. Because `GameLib.App` has multi-targeting (Android, iOS, MacCatalyst, Windows), the EF CLI will fail or get confused. `GameLib.DAL` provides its own `DesignTimeDbContextFactory` to serve as its own startup project. + +### Apply Migrations +```powershell +dotnet ef database update --project solution\GameLib.DAL\GameLib.DAL.csproj --startup-project solution\GameLib.DAL\GameLib.DAL.csproj +``` +Expected output ends with `Done.` or `No migrations were applied. The database is already up to date.` + +### Add a New Migration +```powershell +dotnet ef migrations add --project solution\GameLib.DAL\GameLib.DAL.csproj --startup-project solution\GameLib.DAL\GameLib.DAL.csproj +``` + +--- + +## 4. Building and Running `GameLib.App` (Path A vs Path B) + +> [!CAUTION] +> **AI Agent Background Execution Quirk**: +> Automated agent tools run in headless background shells. Windows security prevents background subprocesses from rendering GUI windows on the user's interactive monitor (`MainWindowHandle` remains `0`). Therefore, **agents must build the app, and the user must launch the executable**. + +### Path A: User Manual Execution +Run directly in an interactive Windows PowerShell: +```powershell +cd solution\GameLib.App +dotnet build -f net10.0-windows10.0.19041.0 +cd bin\Debug\net10.0-windows10.0.19041.0\win-x64 +.\GameLib.App.exe +``` + +### Path B: AI Agent Assisted (Recommended when pairing with an LLM) +1. **Agent compiles the app**: + ```powershell + dotnet build solution\GameLib.App\GameLib.App.csproj -f net10.0-windows10.0.19041.0 + ``` +2. **User launches the executable**: + The agent reports compilation status and asks the user to run: + ```powershell + cd C:\Users\csont\Documents\GitHub\Grid\solution\GameLib.App\bin\Debug\net10.0-windows10.0.19041.0\win-x64; .\GameLib.App.exe + ``` + *(Or double-click `GameLib.App.exe` in File Explorer).* + + +--- + +## 5. Testing + +Unit tests cover `GameLib.DAL` and `GameLib.BL` using xUnit. The App project does not have unit tests. + +### Run All Tests +```powershell +dotnet test solution\solution.slnx +``` + +### Run Specific Test Projects +```powershell +dotnet test solution\GameLib.Tests\GameLib.Tests.csproj +dotnet test solution\GameLib.BL.Tests\GameLib.BL.Tests.csproj +``` + +--- + +## 6. Troubleshooting & Known Quirks + +### ⚠️ Exit Code 9009 on `dotnet build -t:Run` +**Issue**: Running `dotnet build -t:Run -f net10.0-windows10.0.19041.0` fails with: +`MSB3073: The command "...\GameLib.App.exe " exited with code 9009.` +**Cause**: The MSBuild `-t:Run` wrapper fails to launch the WinUI/AppSDK executable in this environment, even though compilation succeeded. +**Solution**: Never use `-t:Run`. Always split build and launch into two separate steps (build, then run `.\GameLib.App.exe`). + +### ⚠️ Warnings: NU1903 SQLitePCLRaw +**Issue**: `NU1903` warnings regarding `SQLitePCLRaw.lib.e_sqlite3` transitive packages. +**Status**: Expected and tracked. Suppressed via `NuGetAuditSuppress` in `GameLib.DAL.csproj`. Safe to ignore during local runs. + +### ⚠️ Stale `obj/` / `bin/` Caches (NETSDK1064 / Missing Packages) +If weird package-not-found errors occur after dependency modifications: +```powershell +Get-ChildItem -Recurse -Directory -Include bin,obj | Remove-Item -Recurse -Force +dotnet nuget locals all --clear +dotnet restore solution\solution.slnx +``` + diff --git a/.gitignore b/.gitignore index 0ba9de9..a9f8d28 100644 --- a/.gitignore +++ b/.gitignore @@ -362,4 +362,8 @@ MigrationBackup/ FodyWeavers.xsd /solution/.idea/.idea.solution/.idea -/local \ No newline at end of file +/local + +*.db +*.db-shm +*.db-wal \ No newline at end of file diff --git a/README.md b/README.md index 89be912..5bd6b07 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,17 @@ every push/PR to `main`. `GameLib.App` is excluded from CI since it requires MAU _TODO: add usage instructions here._ +## 🤖 AI Agent Workflows (Skills) + +This repository includes custom agent skills that allow AI coding assistants (like Claude Code) to seamlessly build, run, and understand the project. + +If you are pairing with an AI assistant in this repository, you can trigger these workflows directly in the chat using slash commands (e.g., `/grid-runner`): + +- **`/grid-runner`**: Automatically handles building the app, running EF Core database migrations, running xUnit tests, and managing the local Windows workflow. *(Use this to quickly start up and run the app!)* +- **`/grid-architecture`**: Teaches the agent the exact 3-tier layer contracts, domain models, relationships, and Git workflow. + +*(These skills are automatically discovered by the agent from the `.claude/skills/` directory).* + ## License Apache License 2.0 — see [LICENSE](LICENSE). \ No newline at end of file diff --git a/solution/GameLib.App/Services/AlertService.cs b/solution/GameLib.App/Services/AlertService.cs index 9919852..017d3d0 100644 --- a/solution/GameLib.App/Services/AlertService.cs +++ b/solution/GameLib.App/Services/AlertService.cs @@ -1,4 +1,4 @@ -using GameLib.App.Services; +using GameLib.App.Services; using System.Linq; namespace GameLib.App.Services; @@ -15,4 +15,15 @@ public async Task DisplayAsync(string title, string message) await page.DisplayAlertAsync(title, message, "OK"); } + + public async Task DisplayConfirmAsync(string title, string message, string accept, string cancel) + { + var page = Application.Current?.Windows.FirstOrDefault()?.Page; + if (page is null) + { + return false; + } + + return await page.DisplayAlert(title, message, accept, cancel); + } } \ No newline at end of file diff --git a/solution/GameLib.App/Services/Interfaces/IAlertService.cs b/solution/GameLib.App/Services/Interfaces/IAlertService.cs index c50f947..b8c87af 100644 --- a/solution/GameLib.App/Services/Interfaces/IAlertService.cs +++ b/solution/GameLib.App/Services/Interfaces/IAlertService.cs @@ -1,6 +1,7 @@ -namespace GameLib.App.Services; +namespace GameLib.App.Services; public interface IAlertService { Task DisplayAsync(string title, string message); + Task DisplayConfirmAsync(string title, string message, string accept, string cancel); } \ No newline at end of file diff --git a/solution/GameLib.App/ViewModels/GameAddViewModel.cs b/solution/GameLib.App/ViewModels/GameAddViewModel.cs index 52f1d6c..ea55a7b 100644 --- a/solution/GameLib.App/ViewModels/GameAddViewModel.cs +++ b/solution/GameLib.App/ViewModels/GameAddViewModel.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using GameLib.App.Messages; using GameLib.App.Services; @@ -14,7 +14,8 @@ namespace GameLib.App.ViewModels; public partial class GameAddViewModel( IFacade gameFacade, INavigationService navigationService, - IMessengerService messengerService) + IMessengerService messengerService, + IAlertService alertService) : ViewModelBase(messengerService) { private static readonly Guid DefaultStudioId = StudioSeeds.DefaultStudio.Id; @@ -41,13 +42,13 @@ private async Task SaveAsync() Game.StudioName = "2k"; if (string.IsNullOrWhiteSpace(Game.Name)) { - await Application.Current!.MainPage!.DisplayAlert("Error", "Game name is required.", "OK"); + await alertService.DisplayAsync("Error", "Game name is required."); return; } if (string.IsNullOrWhiteSpace(Game.ImageUrl)) { - await Application.Current!.MainPage!.DisplayAlert("Error", "Image URL is required", "OK"); + await alertService.DisplayAsync("Error", "Image URL is required"); return; } @@ -64,7 +65,7 @@ private async Task SaveAsync() var inner = ex.InnerException?.InnerException?.Message ?? ex.InnerException?.Message ?? ex.Message; - await Application.Current!.MainPage!.DisplayAlert("Error", $"Game creatin failed: {inner}", "OK"); + await alertService.DisplayAsync("Error", $"Game creatin failed: {inner}"); } messengerService.Send(new GameAddedMessage()); } diff --git a/solution/GameLib.App/ViewModels/GameDetailViewModel.cs b/solution/GameLib.App/ViewModels/GameDetailViewModel.cs index fec9b37..58f7e8b 100644 --- a/solution/GameLib.App/ViewModels/GameDetailViewModel.cs +++ b/solution/GameLib.App/ViewModels/GameDetailViewModel.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using GameLib.App.Messages; @@ -9,7 +9,6 @@ using GameLib.BL.Models; using GameLib.DAL.Entities; using GameLib.DAL.Enums; -using Microsoft.Maui.ApplicationModel; // MainThread using System.Collections.ObjectModel; namespace GameLib.App.ViewModels; @@ -18,7 +17,8 @@ public partial class GameDetailViewModel( IFacade gameFacade, LibraryFacade libraryFacade, INavigationService navigationService, - IMessengerService messengerService) : ViewModelBase(messengerService), IRecipient, IRecipient, IRecipient + IMessengerService messengerService, + IAlertService alertService) : ViewModelBase(messengerService), IRecipient, IRecipient, IRecipient { private Guid _gameId = Guid.Empty; private Guid UserId = Guid.Empty; @@ -50,15 +50,12 @@ private async Task LoadLibrariesAsync(Guid userId) { var libs = await libraryFacade.GetByUserAsync(userId); - MainThread.BeginInvokeOnMainThread(() => - { - Libraries.Clear(); - foreach (var l in libs) Libraries.Add(l); - }); + Libraries.Clear(); + foreach (var l in libs) Libraries.Add(l); } catch (Exception ex) { - await Application.Current.MainPage.DisplayAlert("Error", $"Viewing libraries unsuccessful: {ex.Message}", "OK"); + await alertService.DisplayAsync("Error", $"Viewing libraries unsuccessful: {ex.Message}"); } } @@ -78,7 +75,7 @@ protected override async Task LoadAsync() } catch (Exception ex) { - await Application.Current!.MainPage!.DisplayAlert("Error", $"Loading Game detail failed: {ex.Message}", "OK"); + await alertService.DisplayAsync("Error", $"Loading Game detail failed: {ex.Message}"); } } @@ -97,7 +94,7 @@ private async Task SaveAsync() if (string.IsNullOrWhiteSpace(Game.Name)) { - await Application.Current!.MainPage!.DisplayAlert("Error", "Game Name Cannot be left empty", "OK"); + await alertService.DisplayAsync("Error", "Game Name Cannot be left empty"); return; } @@ -134,7 +131,7 @@ private async Task SaveAsync() } catch (Exception ex) { - await Application.Current.MainPage.DisplayAlert("Error", $"Updated Game could not be saved: {ex.Message}", "OK"); + await alertService.DisplayAsync("Error", $"Updated Game could not be saved: {ex.Message}"); } } @@ -143,13 +140,13 @@ private async Task AddToLibraryAsync() { if (Game is null) { - await Application.Current.MainPage.DisplayAlert("Error", "No game selected.", "OK"); + await alertService.DisplayAsync("Error", "No game selected."); return; } if (SelectedLibrary is null) { - await Application.Current.MainPage.DisplayAlert("Info", "Please select a library first.", "OK"); + await alertService.DisplayAsync("Info", "Please select a library first."); return; } @@ -162,12 +159,9 @@ private async Task AddToLibraryAsync() } catch (Exception ex) { - await Application.Current.MainPage.DisplayAlert("Error", $"Could not add to library: {ex.Message}", "OK"); + await alertService.DisplayAsync("Error", $"Could not add to library: {ex.Message}"); } - await Application.Current!.MainPage!.DisplayAlert( - "Success", - "Game was added to your library", - "OK"); + await alertService.DisplayAsync("Success", "Game was added to your library"); } public async void Receive(GameSelectedMessage message) diff --git a/solution/GameLib.App/ViewModels/UserAddViewModel.cs b/solution/GameLib.App/ViewModels/UserAddViewModel.cs index 1266739..4dc3bc8 100644 --- a/solution/GameLib.App/ViewModels/UserAddViewModel.cs +++ b/solution/GameLib.App/ViewModels/UserAddViewModel.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using GameLib.App.Messages; using GameLib.App.Services; @@ -12,7 +12,8 @@ namespace GameLib.App.ViewModels; public partial class UserAddViewModel( IFacade userFacade, INavigationService navigationService, - IMessengerService messengerService) : ViewModelBase(messengerService) + IMessengerService messengerService, + IAlertService alertService) : ViewModelBase(messengerService) { [ObservableProperty] public partial UserDetailModel User { get; set; } = UserDetailModel.Empty; @@ -28,7 +29,7 @@ private async Task SaveAsync() { if (string.IsNullOrWhiteSpace(User.UserName)) { - await Application.Current!.MainPage!.DisplayAlert("Error", "Username is a required field.", "OK"); + await alertService.DisplayAsync("Error", "Username is a required field."); return; } @@ -43,7 +44,7 @@ private async Task SaveAsync() } catch (Exception ex) { - await Application.Current!.MainPage!.DisplayAlert("Error", $"Account Creation Unsuccessful: {ex.Message}", "OK"); + await alertService.DisplayAsync("Error", $"Account Creation Unsuccessful: {ex.Message}"); } diff --git a/solution/GameLib.App/ViewModels/UserSettingsViewModel.cs b/solution/GameLib.App/ViewModels/UserSettingsViewModel.cs index 08b45ca..3217f86 100644 --- a/solution/GameLib.App/ViewModels/UserSettingsViewModel.cs +++ b/solution/GameLib.App/ViewModels/UserSettingsViewModel.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using GameLib.App.Messages; @@ -13,7 +13,8 @@ namespace GameLib.App.ViewModels; public partial class UserSettingsViewModel( IFacade userFacade, LibraryFacade libraryFacade, - IMessengerService messengerService) + IMessengerService messengerService, + IAlertService alertService) : ViewModelBase(messengerService), IRecipient { [ObservableProperty] @@ -102,10 +103,7 @@ private async Task SaveUserAsync() if (string.IsNullOrWhiteSpace(User.UserName)) { - await Application.Current!.MainPage!.DisplayAlert( - "Error", - "Username is a required field.", - "OK"); + await alertService.DisplayAsync("Error", "Username is a required field."); return; } @@ -115,17 +113,11 @@ private async Task SaveUserAsync() MessengerService.Send(new UserUpdatedMessage(UserId)); - await Application.Current!.MainPage!.DisplayAlert( - "Success", - "Profile saved successfully.", - "OK"); + await alertService.DisplayAsync("Success", "Profile saved successfully."); } catch (Exception ex) { - await Application.Current!.MainPage!.DisplayAlert( - "Error", - $"Failed to save profile: {ex.Message}", - "OK"); + await alertService.DisplayAsync("Error", $"Failed to save profile: {ex.Message}"); } } @@ -135,7 +127,7 @@ private async Task DeleteAccountAsync() if (UserId == Guid.Empty || _isDeleted) return; - bool confirmed = await Application.Current!.MainPage!.DisplayAlert( + bool confirmed = await alertService.DisplayConfirmAsync( "Delete Account", "Are you sure you want to delete this account? This action cannot be undone.", "Delete", "Cancel");