Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@
<None Include="..\ProjectTemplates\Desktop\CSharp\SingleProjectPackagedApp\Package-managed.appxmanifest"
Pack="true"
PackagePath="content/WinAppSdk.CSharp.SingleProject/ProjectTemplate/Package.appxmanifest" />
<None Include="templates\single-project\Agents.md"
Pack="true"
PackagePath="content/WinAppSdk.CSharp.SingleProject/Agents.md" />
<None Include="templates\single-project\instructions\**\*.*"
Pack="true"
PackagePath="content/WinAppSdk.CSharp.SingleProject/instructions/%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<!-- Class library template -->
Expand Down
116 changes: 116 additions & 0 deletions dev/VSIX/DotnetNewTemplates/templates/single-project/Agents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Copilot Agent Instructions — WinUI 3 / WinAppSDK

## Project Overview

This is a **WinUI 3** desktop application built on the **Windows App SDK**. It uses MSIX packaging and supports x86, x64, and ARM64 architectures.

> **Source of truth for versions & names:** Always read the project `.csproj` to determine the current `TargetFramework`, `RuntimeIdentifiers`, `Platforms`, `RootNamespace`, and `Microsoft.WindowsAppSDK` package version. Never hard-code project names or version numbers in instruction files.
>
> Throughout this document and the instruction files, `<ProjectName>` is a placeholder — replace it with the actual project folder/assembly name (derived from the `.csproj` filename).

| Property | How to determine |
|---|---|
| UI Framework | WinUI 3 (`Microsoft.UI.Xaml`) — always used |
| App SDK | Read `Microsoft.WindowsAppSDK` version from `.csproj` `<PackageReference>` |
| Runtime / TFM | Read `<TargetFramework>` from `.csproj` (e.g., `net8.0-windows10.0.19041.0`) |
| Target OS | Derived from `<TargetFramework>` and `<TargetPlatformMinVersion>` in `.csproj` |
| Platforms | Read `<Platforms>` from `.csproj` (e.g., `x86;x64;ARM64`) |
| Packaging | MSIX (`<EnableMsixTooling>true</EnableMsixTooling>`) |
| Namespace | Read `<RootNamespace>` from `.csproj` |
| Nullable | Read `<Nullable>` from `.csproj` |

## Instruction Files Index

All detailed agent instructions are organized under `instructions/`:

| File | Scope |
|---|---|
| [design-principles.instructions.md](instructions/design-principles.instructions.md) | DRY, KISS, SOLID, YAGNI |
| [globalization.instructions.md](instructions/globalization.instructions.md) | Globalization & Localization |
| [accessibility.instructions.md](instructions/accessibility.instructions.md) | Accessibility |
| [security.instructions.md](instructions/security.instructions.md) | Security |
| [performance.instructions.md](instructions/performance.instructions.md) | Performance |
| [code-quality.instructions.md](instructions/code-quality.instructions.md) | Static Analysis, StyleCop, Code Cleanup |
| [winui-best-practices.instructions.md](instructions/winui-best-practices.instructions.md) | WinUI 3 / WinAppSDK patterns & references |
| [testing.instructions.md](instructions/testing.instructions.md) | Unit Testing, Build & Run |

## Core Agent Workflow

Every time you work on this codebase, follow this checklist:

### Before Writing Code
1. **Review the original goal** — Re-read the user's request and confirm you understand the intent.
2. **Check existing code** — Search for related implementations to avoid duplication (DRY).
3. **Find the right API** — If the task involves a platform capability (UI controls, file access, camera, notifications, sensors, etc.), look up the correct API in the [WinUI 3 API Reference](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/) before writing code.
4. **Plan the approach** — Consider SOLID principles and identify which classes/interfaces are involved.

### While Writing Code
5. **Apply Design Principles** — DRY, KISS, SOLID, YAGNI (see [design-principles](instructions/design-principles.instructions.md)).
6. **Follow Fundamentals** — Globalization ([globalization](instructions/globalization.instructions.md)), Accessibility ([accessibility](instructions/accessibility.instructions.md)), Security ([security](instructions/security.instructions.md)), Performance ([performance](instructions/performance.instructions.md)).
7. **Respect Code Quality Rules** — Static analysis & StyleCop (see [code-quality](instructions/code-quality.instructions.md)).
8. **Follow WinUI Patterns** — MVVM, x:Bind, community toolkit, and API verification (see [winui-best-practices](instructions/winui-best-practices.instructions.md)).

### After Writing Code
9. **Remove unused code** — Delete unused `using` statements, dead code, commented-out blocks.
10. **Write unit tests** — Every new public method/class needs tests (see [testing](instructions/testing.instructions.md)).
11. **Build the project** — Run `dotnet build -c Debug -p:Platform=x64` from the project folder and fix all warnings/errors.
12. **Run tests** — Run tests related to the change using `--filter` (see [testing](instructions/testing.instructions.md)). Run the full suite only when the change is cross-cutting.
13. **Register the MSIX package** — See [Build, Run & Deploy](#build-run--deploy) below.
14. **Re-review against original goal** — Confirm the implementation matches the user's request.

## Build, Run & Deploy

This is an MSIX-packaged WinUI 3 app. You **must** pass both `-c` (Configuration) and `-p:Platform=` to every `dotnet` command.

### Prerequisites

- **Developer Mode must be enabled** on Windows. Verify with:
```powershell
# Check developer mode
Get-WindowsDeveloperLicense
# If not enabled: Settings → System → For developers → Developer Mode → On
```

### Build

```powershell
# Run from the project folder containing the .csproj
cd <ProjectName>

# Debug x64 (default development target)
dotnet build -c Debug -p:Platform=x64

# Release x64
dotnet build -c Release -p:Platform=x64

# Other platforms
dotnet build -c Debug -p:Platform=x86
dotnet build -c Debug -p:Platform=ARM64
```

### Register & Run the MSIX Package (Sideload)

After building, register the app package so Windows can launch it:

```powershell
# Register the built MSIX package from the build output
# Path pattern: .\<ProjectName>\bin\<Platform>\<Configuration>\<TargetFramework>\win-<rid>\AppxManifest.xml
# Read <TargetFramework> from the project .csproj to build the correct path.
Add-AppxPackage -Register .\<ProjectName>\bin\x64\Debug\<TargetFramework>\win-x64\AppxManifest.xml
```

> **Note:** Replace `$(TargetFramework)` with the actual value from `.csproj` (e.g., `net8.0-windows10.0.19041.0`).
> Adjust `<Platform>` and `<Configuration>` to match your build target.

### Run Tests

```powershell
# Run from the test project folder
cd <ProjectName>.Tests
dotnet test -c Debug -p:Platform=x64
```

## Key Rules (Always Enforced)

- **Every change must build and pass tests** — Run `dotnet build` and `dotnet test` (see [Build, Run & Deploy](#build-run--deploy)) before considering any task complete.
- **Follow all instruction files** — The detailed rules in `instructions/` are authoritative. Do not skip them.
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
description: 'Accessibility requirements for interactive controls, keyboard navigation, screen readers, and contrast'
applyTo: '**/*.cs, **/*.xaml'
---

# Accessibility

These rules apply to **every UI change**. They are not optional add-ons.

---

## Rules

- **Every interactive control** must have an `AutomationProperties.Name` or `AutomationProperties.LabeledBy`.
- Add a stable, unique `AutomationProperties.AutomationId` for controls targeted by UI automation tests (and for key interactive elements).
- Use semantic XAML controls — prefer `Button`, `HyperlinkButton`, `ListView` over styled `Border`/`Grid` with click handlers.
- Ensure **keyboard navigation** works for all features:
- Logical tab order via `TabIndex`.
- `AccessKey` bindings for frequently used actions.
- `KeyboardAccelerator` for shortcut keys.
- Maintain **minimum contrast ratios** (4.5:1 for normal text, 3:1 for large text) — test in High Contrast mode.
- Support **screen readers** (Narrator / NVDA): test that all content is announced correctly.
- Images must have `AutomationProperties.Name` describing the image purpose (or `AutomationProperties.AccessibilityView="Raw"` for decorative images).
- Do not rely on colour alone to convey meaning — add icons, text, or patterns.

## Anti-patterns

- Clickable `TextBlock` or `Image` without `AutomationProperties`.
- Custom controls that are not keyboard-focusable.
- Using `Visibility.Collapsed` to "hide" content from screen readers (use `AccessibilityView` instead).

## Validation

- Build & register the MSIX package — see **Build, Run & Deploy** in `Agents.md`.
- Test keyboard navigation: tab through every new/changed UI area.
- Test High Contrast: switch to Windows High Contrast theme and verify readability.
- Run Accessibility Insights for Windows on the app.

### Verification Checklist

- [ ] All interactive controls have `AutomationProperties.Name`
- [ ] Keyboard navigation works for the changed area
- [ ] Tested with High Contrast theme enabled
- [ ] Tab through the entire UI with keyboard only.
- [ ] Verify key interactive controls have stable, unique `AutomationProperties.AutomationId` values (especially controls used by UI automation tests).
- [ ] Switch to Windows High Contrast theme and verify readability.
- [ ] Run Narrator and verify all controls are announced correctly.
- [ ] Run **Accessibility Insights for Windows** on the app.

## Must Read & Research

> **Agent Rule:** Before any accessibility-related change, you **must** fetch and review these references using `fetch_webpage`. Apply what you learn.

| # | Reference | When to consult |
|---|---|---|
| 1 | [Accessibility in WinUI](https://learn.microsoft.com/en-us/windows/apps/design/accessibility/accessibility) | Any UI change — verify accessibility approach |
| 2 | [AutomationProperties](https://learn.microsoft.com/en-us/windows/apps/design/accessibility/basic-accessibility-information) | Adding or modifying interactive controls |
| 3 | [Accessibility Insights](https://accessibilityinsights.io/docs/windows/overview/) | Testing tool — run before finalizing UI changes |
| 4 | [Keyboard Accessibility](https://learn.microsoft.com/en-us/windows/apps/design/accessibility/keyboard-accessibility) | Adding navigation, focus management, or shortcut keys |
| 5 | [High Contrast Themes](https://learn.microsoft.com/en-us/windows/apps/design/accessibility/high-contrast-themes) | Adding custom styles, colours, or theme resources |
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
description: 'Static analysis, StyleCop, EditorConfig, naming conventions, and code cleanup rules'
applyTo: '**/*.cs, **/*.editorconfig, **/stylecop.json'
---

# Code Quality — Static Analysis, StyleCop & Code Cleanup

Maintain strict code quality through automated analysis and consistent style enforcement.

---

## 1. Static Analysis (Roslyn Analyzers)

### Required Analyzer Packages

Add these to the `.csproj` if not already present:

```xml
<ItemGroup>
<!-- Use the latest stable versions; do not hard-code version numbers in instructions -->
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="*" />
<PackageReference Include="StyleCop.Analyzers" Version="*">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
```

### Analysis Configuration in `.csproj`

```xml
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<Nullable>enable</Nullable>
</PropertyGroup>
```

### Rule Enforcement

Follow **all** CA* (quality) and IDE* (code style) analyzer rules at their configured severity. Do not cherry-pick — obey every warning the analyzers report. When encountering a specific rule violation, fetch the corresponding documentation from the **Must Read & Research** references below to understand and apply the correct fix.

### `.editorconfig`

The project's `.editorconfig` in the solution root is the source of truth for code style. Obey all rules defined there. When creating or modifying `.editorconfig`, fetch the [EditorConfig Reference](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options) for the full list of available settings.

Key project conventions enforced via `.editorconfig`:
- Private fields use `_camelCase` prefix (SA1101 suppressed, SA1309 suppressed).
- File-scoped namespaces are required.
- `this.` qualification is not used.

---

## 2. StyleCop Rules

### StyleCop Configuration (`stylecop.json`)

Place this file in the project root alongside the `.csproj`:

```json
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"documentationRules": {
"companyName": "YourProjectName",
"copyrightText": "Copyright (c) {companyName}. All rights reserved.",
"xmlHeader": false,
"documentInterfaces": true,
"documentExposedElements": true,
"documentInternalElements": false,
"documentPrivateElements": false,
"documentPrivateFields": false
},
"orderingRules": {
"usingDirectivesPlacement": "outsideNamespace",
"systemUsingDirectivesFirst": true
},
"layoutRules": {
"newlineAtEndOfFile": "require"
},
"namingRules": {
"allowCommonHungarianPrefixes": false
}
}
}
```

### Rule Enforcement

Follow **all** SA* (StyleCop) rules at their configured severity. When encountering a specific SA* violation, fetch the [StyleCop Rules Reference](https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/DOCUMENTATION.md) to understand the rule and apply the correct fix. Do not suppress rules without justification in a code comment.

---

## 3. Code Cleanup Rules (Always Enforced)

### After Every Edit

1. **Remove unused `using` statements** — No unused imports should remain.
2. **Remove commented-out code** — Version control tracks history; dead code is noise.
3. **Remove unused variables and fields** — If it's declared but never read, delete it.
4. **Remove empty methods** — If an event handler or override does nothing, remove it.
5. **Simplify code** — Apply IDE suggestions (IDE0001–IDE0090) for:
- Removing unnecessary casts
- Simplifying `default` expressions
- Using pattern matching
- Using null-coalescing operators

### Naming Conventions

| Element | Convention | Example |
|---|---|---|
| Class / Struct | PascalCase | `MainViewModel` |
| Interface | I + PascalCase | `INavigationService` |
| Public method | PascalCase | `LoadDataAsync()` |
| Private method | PascalCase | `ValidateInput()` |
| Public property | PascalCase | `CurrentPage` |
| Private field | _camelCase | `_settingsService` |
| Parameter | camelCase | `userName` |
| Local variable | camelCase | `itemCount` |
| Constant | PascalCase | `MaxRetryCount` |
| Async method | Suffix `Async` | `FetchDataAsync()` |
| Boolean | Prefix `Is/Has/Can` | `IsLoading`, `HasAccess` |

### File Organization

Each `.cs` file should follow this order:

1. `using` directives (System first, then others, alphabetically)
2. Namespace declaration (file-scoped)
3. Class/struct/interface declaration
4. Inside the type:
1. Constants
2. Static fields
3. Instance fields
4. Constructors
5. Properties
6. Public methods
7. Private/internal methods
8. Event handlers
9. Nested types

---

## Validation

- Build & register the MSIX package — see **Build, Run & Deploy** in `Agents.md`.
- Fix **all** warnings — do not suppress without justification in a code comment.
- Verify no unused `using` statements remain after every edit.
- Verify no commented-out code remains.
- Confirm naming conventions match the table above for every new symbol.

---

## Must Read & Research

> **Agent Rule:** Before configuring analyzers, fixing warnings, or adjusting code style, you **must** fetch and review the relevant references below using `fetch_webpage`. Apply what you learn — do not skip this step.

| # | Reference | When to consult |
|---|---|---|
| 1 | [.NET Code Analysis Overview](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview) | Setting up or modifying analyzer configuration |
| 2 | [Code Style Rules (IDE0001–IDE0090)](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/) | Resolving IDE* warnings or adjusting `.editorconfig` |
| 3 | [Quality Rules (CA*)](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/) | Resolving CA* warnings or suppressing with justification |
| 4 | [StyleCop.Analyzers GitHub](https://github.com/DotNetAnalyzers/StyleCopAnalyzers) | Adding/updating StyleCop package or configuration |
| 5 | [StyleCop Rules Reference](https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/DOCUMENTATION.md) | Understanding specific SA* rule violations |
| 6 | [EditorConfig Reference](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options) | Modifying `.editorconfig` style or severity settings |
| 7 | [.NET Naming Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names) | Verifying naming patterns for types, members, parameters |
Loading