docs(rules): add MAUI and Blazor rules, close C# gaps

New C# topic rules for .NET MAUI and Blazor, both centered on
performance and cross-platform reuse. MAUI covers compilation strategy
per platform (ReadyToRun, NativeAOT), trim and AOT safety, lean startup,
CollectionView and flat layouts, and per-platform conventions. Blazor
covers render mode cost, WebAssembly payload size and AOT trade-offs,
prerender state, rendering cost, and Razor class libraries shared across
web, WebAssembly, and Hybrid hosts. The C# index and global routing now
name both.

The existing C# rules gain the net11.0 default of C# 15, async void only
for event handlers, explicit StringComparison, invariant culture for
machine data, UTC or DateTimeOffset for stored times, ProblemDetails,
and ValidateOnStart. Duplicate authorization and raw SQL guidance in the
architecture rule is merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian LechnerandClaude Opus 5.5 committed 2026-11-18 09:57:17 +01:00
1 parent b74357b586
commit ff33ea1327
9 files changed
+67 -6

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ Changes to or reviews of code, scripts, hooks, tests, infrastructure, integratio
Focused security (Codex paths under `rules/security/references/`): authentication, authorization, sessions, tokens, permissions, tenants => `auth.md` / `rules-security-auth`; inbound HTTP endpoints, request handling, API (de)serialization => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, XML parsing, deserialization => `files.md` / `rules-security-files`; outbound HTTP calls, webhooks, URL fetching, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; LLM calls, prompts, agents, tools, retrieval/RAG => `ai.md` / `rules-security-ai`; active security testing => `testing.md` / `rules-security-testing`.
Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`.
Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET, Blazor, MAUI => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`.
Cross-cutting: unclear requirements or significant choices => `rules/decision-rule.md` / `rules-decision-rule`; completion or review readiness => `rules/definition-of-done.md` / `rules-definition-of-done`; Git operations => `rules/git.md` / `rules-git`; Azure DevOps, Teams, Microsoft 365, SharePoint, SQL Server, Confluence, Grafana, or other connected remote systems => `rules/microsoft.md` / `rules-microsoft`; delegation or long-running work => `rules/orchestration.md` / `rules-orchestration`; behavior-preserving refactors => `rules/refactoring.md` / `rules-refactoring`.
+3 -1
View File
@@ -1,6 +1,6 @@
# C# Rules
For C# or .NET work, open only the topic rules relevant to the task. Follow repository conventions and load applicable shared security rules as well.
For C# or .NET work, including ASP.NET Core, Blazor, and .NET MAUI, open only the topic rules relevant to the task. Follow repository conventions and load applicable shared security rules as well.
| Topic | Codex rule | Claude skill |
| --- | --- | --- |
@@ -12,3 +12,5 @@ For C# or .NET work, open only the topic rules relevant to the task. Follow repo
| Security | `references/security.md` | `rules-csharp-security` |
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-csharp-safety-and-errors` |
| Tests, dependencies, and analyzers | `references/testing-and-dependencies.md` | `rules-csharp-testing-and-dependencies` |
| .NET MAUI apps | `references/maui.md` | `rules-csharp-maui` |
| Blazor components and apps | `references/blazor.md` | `rules-csharp-blazor` |
@@ -2,11 +2,11 @@
Apply these rules when designing public APIs, service boundaries, or application architecture.
* Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed. Authorization, resource ownership, and tenant scoping are never "already done": enforce them at the operation that accesses the data.
* Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed.
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
* Authenticate and authorize before accessing protected resources. Authorization, resource ownership, and tenant scoping are never "already done": keep the decision close to the protected operation, enforce ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
* Use explicit, bounded pagination for potentially large collections.
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries, and use `FromSql` or `FromSqlInterpolated` instead of concatenating into `FromSqlRaw`.
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries; raw SQL follows the C# security rules.
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
@@ -4,6 +4,7 @@ Apply these rules when adding or changing asynchronous APIs, background work, or
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
* Return `Task` or `ValueTask` from async methods. Use `async void` only for event handlers, because callers cannot await it and its exceptions escape to the synchronization context; catch and handle failures inside such handlers.
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
* In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread.
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`.
+26
View File
@@ -0,0 +1,26 @@
# C# Blazor
Apply these rules when building or changing Blazor components and apps. Performance and cross-platform reuse are the primary design goals. Check the target framework first: render modes, state persistence, and antiforgery behavior differ between .NET 8, 9, 10, and 11. Load the UI/UX rules for interface design and the shared web security rule for browser concerns.
## Performance
* Measure before optimizing: profile rendering, download size, and server memory in `Release` builds against a baseline.
* Choose the render mode for its cost: static server rendering for content, interactive server where latency is low and connections are few, WebAssembly where offline use or server load matters, and Auto to combine fast first load with client execution. Each mode moves cost between download size, server memory, and network latency.
* Keep WebAssembly payloads small: trim, lazy load rarely used assemblies with `BlazorWebAssemblyLazyLoad`, and serve compressed, fingerprinted assets. Enable AOT (`RunAOTCompilation`, with `WasmStripILAfterAOT`) only for CPU-heavy apps, because it speeds execution but enlarges the download.
* Expect prerendered components to initialize twice. Persist prerendered state with `PersistentComponentState`, or `[PersistentState]` on .NET 10+, instead of repeating service and database calls.
* Use streaming rendering (`[StreamRendering]`) to show content while slow data loads on static server rendering.
* Render less: virtualize large lists with `Virtualize`, give list items a stable `@key`, avoid unnecessary `StateHasChanged` calls, override `ShouldRender` for components with costly subtrees, and avoid creating thousands of small component instances in a loop when plain markup would do.
* Batch JavaScript interop. Avoid many fine-grained calls in loops, and pass small, serializable data.
* On interactive server rendering, keep circuit state small, release large objects promptly, and avoid per-user caches that grow without bounds.
## Cross-platform
* Put shared UI in a Razor class library that works in every host: Blazor Web App, WebAssembly, and Blazor Hybrid in .NET MAUI (`BlazorWebView`). Keep host-specific code out of it.
* Access platform features (device info, storage, files, notifications) through interfaces in the shared library, implemented per host and registered with dependency injection.
* Write components that work in every render mode they may run in: no browser-only APIs before the first render, no assumption of an HTTP context, and JavaScript interop only in `OnAfterRenderAsync(firstRender)`.
* Treat all WebAssembly and Hybrid client code and data as public. Never ship secrets or rely on client-side authorization; `AuthorizeView` and `[Authorize]` only hide UI. Enforce authorization in the server APIs and data access the client calls.
* Keep per-user state out of singleton services. On interactive server rendering, state lives in the user's circuit and is lost on disconnect; persist what must survive a reconnect or reload.
* Keep `app.UseAntiforgery()` in the pipeline. `EditForm` adds the token automatically; add `<AntiforgeryToken />` to plain HTML forms. Validate forms with a validator component and again on the server.
* Dispose `IJSObjectReference` and `DotNetObjectReference` instances in `DisposeAsync`, catch `JSDisconnectedException` there for server circuits, and implement `IDisposable` or `IAsyncDisposable` to unsubscribe events and stop timers.
* Never render untrusted content with `MarkupString`; let Razor encode it. Wrap risky regions in `ErrorBoundary` and keep detailed errors out of production.
* Test every host and render mode you ship, including Hybrid on each MAUI target platform.
@@ -2,7 +2,7 @@
Apply these rules when editing C# syntax, class structure, and everyday code organization.
* Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net10.0` defaults to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
* Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net11.0` defaults to C# 15 and `net10.0` to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
* Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
+28
View File
@@ -0,0 +1,28 @@
# C# .NET MAUI
Apply these rules when building or changing .NET MAUI apps. Performance and cross-platform behavior are the primary design goals. Check the project's `TargetFrameworks` first: runtimes, compilation defaults, and controls differ between MAUI 8, 9, 10, and 11. Load the UI/UX rules for interface design and the C# performance rule for measurement.
## Performance
* Measure before optimizing, on real devices in `Release` builds: profile startup and hot paths with `dotnet-trace` or the MAUI profiling tooling, and compare against a baseline. Emulators and `Debug` builds do not show shipping performance.
* Choose the compilation strategy per platform and record why: ReadyToRun (the `Release` default, with `MauiEnableFullReadyToRun` for faster startup at a larger package), or NativeAOT for the smallest size and fastest startup where the app and its libraries are trim and AOT compatible. On Android, ReadyToRun requires `PublishTrimmed=true`.
* Keep the app trim and AOT safe: compiled bindings with `x:DataType` everywhere, no reflection-based serialization or DI scanning, and no trim warnings left unexplained.
* Keep startup lean: register services in `MauiProgram` without doing work there, defer non-essential initialization until after the first page renders, and load data asynchronously.
* Use `CollectionView` (not the deprecated `ListView`) with simple, flat item templates, and virtualize long lists. Avoid nested scroll views and per-item heavy converters or bindings.
* Prefer flat `Grid` layouts over deeply nested `StackLayout` trees, use `Border` instead of the obsolete `Frame`, and avoid fixed sizes that force re-measuring.
* Size images for their display size, use platform-appropriate formats, and cache remote images. Never decode full-resolution images for thumbnails.
* Keep the main thread free: run I/O and CPU work off it, and marshal only UI updates back with `MainThread.BeginInvokeOnMainThread` or the dispatcher.
* Unsubscribe events and dispose resources when pages disappear, so navigation does not leak pages, view models, or native views.
## Cross-platform
* Share UI, view models, and services by default. Put platform code in the `Platforms` folders or partial classes behind interfaces, and choose `OnPlatform`, `OnIdiom`, or conditional compilation only for real platform differences.
* Follow each target platform's conventions where people notice them: navigation, back behavior, tab placement, dialogs, and system fonts. Apply Apple's conventions to iOS and Mac Catalyst targets, Material to Android, and Windows conventions to Windows.
* Design for every supported size class and input: phone, tablet, and desktop windows, touch, mouse, and keyboard, safe areas, and text scaling.
* Customize controls through handlers and their mappers. Treat Xamarin custom renderers and compatibility renderers as temporary migration steps.
* Use MVVM with view models free of view types; prefer the project's MVVM library, such as CommunityToolkit.Mvvm source generators. Register pages and view models through dependency injection and navigate with Shell routes and typed parameters where the app uses Shell.
* Store tokens and other secrets with `SecureStorage`, never `Preferences`. Wrap `SecureStorage` calls in error handling and exclude its file from Android Auto Backup, because restored values cannot be decrypted on a new device.
* Request runtime permissions through `Permissions` at the point of use, and keep the feature usable or explained when a permission is denied.
* Expect suspension and termination: persist essential state in lifecycle events and restore it on resume.
* Set `SemanticProperties.Description` and `SemanticProperties.Hint` on meaningful images and controls without a visible label.
* Build and test `Release` builds with trimming on every platform you ship. Trimming, AOT, and platform differences surface only there.
@@ -8,6 +8,7 @@ Apply these rules when handling external input, failures, logs, or sensitive inf
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
* Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads.
* Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container.
* In ASP.NET Core, return errors as `ProblemDetails` (`AddProblemDetails`) without internal details, and validate options at startup with `ValidateDataAnnotations` or a validator plus `ValidateOnStart()` so invalid configuration fails before the first request.
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
@@ -9,3 +9,6 @@ Apply these rules when designing type contracts, choosing collection shapes, or
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
* Avoid large mutable structs and direct exposure of mutable internal collections.
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
* Pass `StringComparison` explicitly (CA1307, CA1309): `Ordinal` or `OrdinalIgnoreCase` for identifiers, keys, paths, and protocol values; culture-aware comparison only for text shown to users.
* Parse and format machine-readable numbers and dates with `CultureInfo.InvariantCulture`, and user-facing values with the user's culture. Never rely on the thread's current culture for data exchanged with files, APIs, or databases.
* Store and compute times in UTC or as `DateTimeOffset`, and convert to local time only for display. Read the clock through `TimeProvider` where tests need control.